]> git.ipfire.org Git - thirdparty/hostap.git/blob - tests/hwsim/test_ap_wps.py
dc8635087e930ba245c467b2bd5eb41a1537eec8
[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 from test_sae import check_sae_capab
48
49 def wps_start_ap(apdev, ssid="test-wps-conf"):
50 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
51 "wpa_passphrase": "12345678", "wpa": "2",
52 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
53 return hostapd.add_ap(apdev, params)
54
55 @remote_compatible
56 def test_ap_wps_init(dev, apdev):
57 """Initial AP configuration with first WPS Enrollee"""
58 ssid = "test-wps"
59 hapd = hostapd.add_ap(apdev[0],
60 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
61 logger.info("WPS provisioning step")
62 hapd.request("WPS_PBC")
63 if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
64 raise Exception("PBC status not shown correctly")
65
66 id = dev[0].add_network()
67 dev[0].set_network_quoted(id, "ssid", "home")
68 dev[0].set_network_quoted(id, "psk", "12345678")
69 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
70
71 id = dev[0].add_network()
72 dev[0].set_network_quoted(id, "ssid", "home2")
73 dev[0].set_network(id, "bssid", "00:11:22:33:44:55")
74 dev[0].set_network(id, "key_mgmt", "NONE")
75 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
76
77 dev[0].request("WPS_PBC")
78 dev[0].wait_connected(timeout=30)
79 status = dev[0].get_status()
80 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
81 raise Exception("Not fully connected")
82 if status['ssid'] != ssid:
83 raise Exception("Unexpected SSID")
84 if status['pairwise_cipher'] != 'CCMP':
85 raise Exception("Unexpected encryption configuration")
86 if status['key_mgmt'] != 'WPA2-PSK':
87 raise Exception("Unexpected key_mgmt")
88
89 status = hapd.request("WPS_GET_STATUS")
90 if "PBC Status: Disabled" not in status:
91 raise Exception("PBC status not shown correctly")
92 if "Last WPS result: Success" not in status:
93 raise Exception("Last WPS result not shown correctly")
94 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
95 raise Exception("Peer address not shown correctly")
96 conf = hapd.request("GET_CONFIG")
97 if "wps_state=configured" not in conf:
98 raise Exception("AP not in WPS configured state")
99 if "wpa=3" not in conf:
100 raise Exception("AP not in WPA+WPA2 configuration")
101 if "rsn_pairwise_cipher=CCMP TKIP" not in conf:
102 raise Exception("Unexpected rsn_pairwise_cipher")
103 if "wpa_pairwise_cipher=CCMP TKIP" not in conf:
104 raise Exception("Unexpected wpa_pairwise_cipher")
105 if "group_cipher=TKIP" not in conf:
106 raise Exception("Unexpected group_cipher")
107
108 if len(dev[0].list_networks()) != 3:
109 raise Exception("Unexpected number of network blocks")
110
111 def test_ap_wps_init_2ap_pbc(dev, apdev):
112 """Initial two-radio AP configuration with first WPS PBC Enrollee"""
113 ssid = "test-wps"
114 params = {"ssid": ssid, "eap_server": "1", "wps_state": "1"}
115 hapd = hostapd.add_ap(apdev[0], params)
116 hostapd.add_ap(apdev[1], params)
117 logger.info("WPS provisioning step")
118 hapd.request("WPS_PBC")
119 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
120 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
121 bss = dev[0].get_bss(apdev[0]['bssid'])
122 if "[WPS-PBC]" not in bss['flags']:
123 raise Exception("WPS-PBC flag missing from AP1")
124 bss = dev[0].get_bss(apdev[1]['bssid'])
125 if "[WPS-PBC]" not in bss['flags']:
126 raise Exception("WPS-PBC flag missing from AP2")
127 dev[0].dump_monitor()
128 dev[0].request("SET wps_cred_processing 2")
129 dev[0].request("WPS_PBC")
130 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=30)
131 dev[0].request("SET wps_cred_processing 0")
132 if ev is None:
133 raise Exception("WPS cred event not seen")
134 if "100e" not in ev:
135 raise Exception("WPS attributes not included in the cred event")
136 dev[0].wait_connected(timeout=30)
137
138 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
139 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
140 bss = dev[1].get_bss(apdev[0]['bssid'])
141 if "[WPS-PBC]" in bss['flags']:
142 raise Exception("WPS-PBC flag not cleared from AP1")
143 bss = dev[1].get_bss(apdev[1]['bssid'])
144 if "[WPS-PBC]" in bss['flags']:
145 raise Exception("WPS-PBC flag not cleared from AP2")
146
147 def test_ap_wps_init_2ap_pin(dev, apdev):
148 """Initial two-radio AP configuration with first WPS PIN Enrollee"""
149 ssid = "test-wps"
150 params = {"ssid": ssid, "eap_server": "1", "wps_state": "1"}
151 hapd = hostapd.add_ap(apdev[0], params)
152 hostapd.add_ap(apdev[1], params)
153 logger.info("WPS provisioning step")
154 pin = dev[0].wps_read_pin()
155 hapd.request("WPS_PIN any " + pin)
156 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
157 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
158 bss = dev[0].get_bss(apdev[0]['bssid'])
159 if "[WPS-AUTH]" not in bss['flags']:
160 raise Exception("WPS-AUTH flag missing from AP1")
161 bss = dev[0].get_bss(apdev[1]['bssid'])
162 if "[WPS-AUTH]" not in bss['flags']:
163 raise Exception("WPS-AUTH flag missing from AP2")
164 dev[0].dump_monitor()
165 dev[0].request("WPS_PIN any " + pin)
166 dev[0].wait_connected(timeout=30)
167
168 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
169 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
170 bss = dev[1].get_bss(apdev[0]['bssid'])
171 if "[WPS-AUTH]" in bss['flags']:
172 raise Exception("WPS-AUTH flag not cleared from AP1")
173 bss = dev[1].get_bss(apdev[1]['bssid'])
174 if "[WPS-AUTH]" in bss['flags']:
175 raise Exception("WPS-AUTH flag not cleared from AP2")
176
177 @remote_compatible
178 def test_ap_wps_init_through_wps_config(dev, apdev):
179 """Initial AP configuration using wps_config command"""
180 ssid = "test-wps-init-config"
181 hapd = hostapd.add_ap(apdev[0],
182 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
183 if "FAIL" in hapd.request("WPS_CONFIG " + binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(b"12345678").decode()):
184 raise Exception("WPS_CONFIG command failed")
185 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
186 if ev is None:
187 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
188 # It takes some time for the AP to update Beacon and Probe Response frames,
189 # so wait here before requesting the scan to be started to avoid adding
190 # extra five second wait to the test due to fetching obsolete scan results.
191 hapd.ping()
192 time.sleep(0.2)
193 dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
194 pairwise="CCMP", group="CCMP")
195
196 if "FAIL" not in hapd.request("WPS_CONFIG foo"):
197 raise Exception("Invalid WPS_CONFIG accepted")
198
199 @remote_compatible
200 def test_ap_wps_init_through_wps_config_2(dev, apdev):
201 """AP configuration using wps_config and wps_cred_processing=2"""
202 ssid = "test-wps-init-config"
203 hapd = hostapd.add_ap(apdev[0],
204 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
205 "wps_cred_processing": "2"})
206 if "FAIL" in hapd.request("WPS_CONFIG " + binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(b"12345678").decode()):
207 raise Exception("WPS_CONFIG command failed")
208 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
209 if ev is None:
210 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
211 if "100e" not in ev:
212 raise Exception("WPS-NEW-AP-SETTINGS did not include Credential")
213
214 @remote_compatible
215 def test_ap_wps_invalid_wps_config_passphrase(dev, apdev):
216 """AP configuration using wps_config command with invalid passphrase"""
217 ssid = "test-wps-init-config"
218 hapd = hostapd.add_ap(apdev[0],
219 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
220 if "FAIL" not in hapd.request("WPS_CONFIG " + binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(b"1234567").decode()):
221 raise Exception("Invalid WPS_CONFIG command accepted")
222
223 def test_ap_wps_conf(dev, apdev):
224 """WPS PBC provisioning with configured AP"""
225 ssid = "test-wps-conf"
226 hapd = hostapd.add_ap(apdev[0],
227 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
228 "wpa_passphrase": "12345678", "wpa": "2",
229 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
230 logger.info("WPS provisioning step")
231 hapd.request("WPS_PBC")
232 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
233 dev[0].dump_monitor()
234 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
235 dev[0].wait_connected(timeout=30)
236 status = dev[0].get_status()
237 if status['wpa_state'] != 'COMPLETED':
238 raise Exception("Not fully connected")
239 if status['bssid'] != apdev[0]['bssid']:
240 raise Exception("Unexpected BSSID")
241 if status['ssid'] != ssid:
242 raise Exception("Unexpected SSID")
243 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
244 raise Exception("Unexpected encryption configuration")
245 if status['key_mgmt'] != 'WPA2-PSK':
246 raise Exception("Unexpected key_mgmt")
247
248 sta = hapd.get_sta(dev[0].p2p_interface_addr())
249 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
250 raise Exception("Device name not available in STA command")
251
252 def test_ap_wps_conf_5ghz(dev, apdev):
253 """WPS PBC provisioning with configured AP on 5 GHz band"""
254 try:
255 hapd = None
256 ssid = "test-wps-conf"
257 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
258 "wpa_passphrase": "12345678", "wpa": "2",
259 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
260 "country_code": "FI", "hw_mode": "a", "channel": "36"}
261 hapd = hostapd.add_ap(apdev[0], params)
262 logger.info("WPS provisioning step")
263 hapd.request("WPS_PBC")
264 dev[0].scan_for_bss(apdev[0]['bssid'], freq="5180")
265 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
266 dev[0].wait_connected(timeout=30)
267
268 sta = hapd.get_sta(dev[0].p2p_interface_addr())
269 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
270 raise Exception("Device name not available in STA command")
271 finally:
272 dev[0].request("DISCONNECT")
273 clear_regdom(hapd, dev)
274
275 def test_ap_wps_conf_chan14(dev, apdev):
276 """WPS PBC provisioning with configured AP on channel 14"""
277 try:
278 hapd = None
279 ssid = "test-wps-conf"
280 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
281 "wpa_passphrase": "12345678", "wpa": "2",
282 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
283 "country_code": "JP", "hw_mode": "b", "channel": "14"}
284 hapd = hostapd.add_ap(apdev[0], params)
285 logger.info("WPS provisioning step")
286 hapd.request("WPS_PBC")
287 dev[0].request("WPS_PBC")
288 dev[0].wait_connected(timeout=30)
289
290 sta = hapd.get_sta(dev[0].p2p_interface_addr())
291 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
292 raise Exception("Device name not available in STA command")
293 finally:
294 dev[0].request("DISCONNECT")
295 clear_regdom(hapd, dev)
296
297 @remote_compatible
298 def test_ap_wps_twice(dev, apdev):
299 """WPS provisioning with twice to change passphrase"""
300 ssid = "test-wps-twice"
301 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
302 "wpa_passphrase": "12345678", "wpa": "2",
303 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
304 hapd = hostapd.add_ap(apdev[0], params)
305 logger.info("WPS provisioning step")
306 hapd.request("WPS_PBC")
307 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
308 dev[0].dump_monitor()
309 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
310 dev[0].wait_connected(timeout=30)
311 dev[0].request("DISCONNECT")
312
313 logger.info("Restart AP with different passphrase and re-run WPS")
314 hostapd.remove_bss(apdev[0])
315 params['wpa_passphrase'] = 'another passphrase'
316 hapd = hostapd.add_ap(apdev[0], params)
317 logger.info("WPS provisioning step")
318 hapd.request("WPS_PBC")
319 dev[0].dump_monitor()
320 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
321 dev[0].wait_connected(timeout=30)
322 networks = dev[0].list_networks()
323 if len(networks) > 1:
324 raise Exception("Unexpected duplicated network block present")
325
326 @remote_compatible
327 def test_ap_wps_incorrect_pin(dev, apdev):
328 """WPS PIN provisioning with incorrect PIN"""
329 ssid = "test-wps-incorrect-pin"
330 hapd = hostapd.add_ap(apdev[0],
331 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
332 "wpa_passphrase": "12345678", "wpa": "2",
333 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
334
335 logger.info("WPS provisioning attempt 1")
336 hapd.request("WPS_PIN any 12345670")
337 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
338 dev[0].dump_monitor()
339 dev[0].request("WPS_PIN %s 55554444" % apdev[0]['bssid'])
340 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
341 if ev is None:
342 raise Exception("WPS operation timed out")
343 if "config_error=18" not in ev:
344 raise Exception("Incorrect config_error reported")
345 if "msg=8" not in ev:
346 raise Exception("PIN error detected on incorrect message")
347 dev[0].wait_disconnected(timeout=10)
348 dev[0].request("WPS_CANCEL")
349 # if a scan was in progress, wait for it to complete before trying WPS again
350 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
351
352 status = hapd.request("WPS_GET_STATUS")
353 if "Last WPS result: Failed" not in status:
354 raise Exception("WPS failure result not shown correctly")
355
356 logger.info("WPS provisioning attempt 2")
357 hapd.request("WPS_PIN any 12345670")
358 dev[0].dump_monitor()
359 dev[0].request("WPS_PIN %s 12344444" % apdev[0]['bssid'])
360 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
361 if ev is None:
362 raise Exception("WPS operation timed out")
363 if "config_error=18" not in ev:
364 raise Exception("Incorrect config_error reported")
365 if "msg=10" not in ev:
366 raise Exception("PIN error detected on incorrect message")
367 dev[0].wait_disconnected(timeout=10)
368
369 @remote_compatible
370 def test_ap_wps_conf_pin(dev, apdev):
371 """WPS PIN provisioning with configured AP"""
372 ssid = "test-wps-conf-pin"
373 hapd = hostapd.add_ap(apdev[0],
374 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
375 "wpa_passphrase": "12345678", "wpa": "2",
376 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
377 logger.info("WPS provisioning step")
378 pin = dev[0].wps_read_pin()
379 hapd.request("WPS_PIN any " + pin)
380 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
381 dev[0].dump_monitor()
382 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
383 dev[0].wait_connected(timeout=30)
384 status = dev[0].get_status()
385 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
386 raise Exception("Not fully connected")
387 if status['ssid'] != ssid:
388 raise Exception("Unexpected SSID")
389 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
390 raise Exception("Unexpected encryption configuration")
391 if status['key_mgmt'] != 'WPA2-PSK':
392 raise Exception("Unexpected key_mgmt")
393
394 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
395 bss = dev[1].get_bss(apdev[0]['bssid'])
396 if "[WPS-AUTH]" in bss['flags']:
397 raise Exception("WPS-AUTH flag not cleared")
398 logger.info("Try to connect from another station using the same PIN")
399 pin = dev[1].request("WPS_PIN " + apdev[0]['bssid'])
400 ev = dev[1].wait_event(["WPS-M2D", "CTRL-EVENT-CONNECTED"], timeout=30)
401 if ev is None:
402 raise Exception("Operation timed out")
403 if "WPS-M2D" not in ev:
404 raise Exception("Unexpected WPS operation started")
405 hapd.request("WPS_PIN any " + pin)
406 dev[1].wait_connected(timeout=30)
407
408 def test_ap_wps_conf_pin_mixed_mode(dev, apdev):
409 """WPS PIN provisioning with configured AP (WPA+WPA2)"""
410 ssid = "test-wps-conf-pin-mixed"
411 hapd = hostapd.add_ap(apdev[0],
412 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
413 "wpa_passphrase": "12345678", "wpa": "3",
414 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
415 "wpa_pairwise": "TKIP"})
416
417 logger.info("WPS provisioning step")
418 pin = dev[0].wps_read_pin()
419 hapd.request("WPS_PIN any " + pin)
420 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
421 dev[0].dump_monitor()
422 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
423 dev[0].wait_connected(timeout=30)
424 status = dev[0].get_status()
425 dev[0].request("REMOVE_NETWORK all")
426 dev[0].wait_disconnected()
427 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
428 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
429
430 logger.info("WPS provisioning step (auth_types=0x1b)")
431 if "OK" not in dev[0].request("SET wps_force_auth_types 0x1b"):
432 raise Exception("Failed to set wps_force_auth_types 0x1b")
433 pin = dev[0].wps_read_pin()
434 hapd.request("WPS_PIN any " + pin)
435 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
436 dev[0].dump_monitor()
437 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
438 dev[0].wait_connected(timeout=30)
439 status = dev[0].get_status()
440 dev[0].request("REMOVE_NETWORK all")
441 dev[0].wait_disconnected()
442 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
443 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
444
445 logger.info("WPS provisioning step (auth_types=0 encr_types=0)")
446 if "OK" not in dev[0].request("SET wps_force_auth_types 0"):
447 raise Exception("Failed to set wps_force_auth_types 0")
448 if "OK" not in dev[0].request("SET wps_force_encr_types 0"):
449 raise Exception("Failed to set wps_force_encr_types 0")
450 pin = dev[0].wps_read_pin()
451 hapd.request("WPS_PIN any " + pin)
452 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
453 dev[0].dump_monitor()
454 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
455 dev[0].wait_connected(timeout=30)
456 status = dev[0].get_status()
457 dev[0].request("REMOVE_NETWORK all")
458 dev[0].wait_disconnected()
459 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
460 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
461
462 dev[0].request("SET wps_force_auth_types ")
463 dev[0].request("SET wps_force_encr_types ")
464
465 @remote_compatible
466 def test_ap_wps_conf_pin_v1(dev, apdev):
467 """WPS PIN provisioning with configured WPS v1.0 AP"""
468 ssid = "test-wps-conf-pin-v1"
469 hapd = hostapd.add_ap(apdev[0],
470 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
471 "wpa_passphrase": "12345678", "wpa": "2",
472 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
473 logger.info("WPS provisioning step")
474 pin = dev[0].wps_read_pin()
475 hapd.request("SET wps_version_number 0x10")
476 hapd.request("WPS_PIN any " + pin)
477 found = False
478 for i in range(0, 10):
479 dev[0].scan(freq="2412")
480 if "[WPS-PIN]" in dev[0].request("SCAN_RESULTS"):
481 found = True
482 break
483 if not found:
484 hapd.request("SET wps_version_number 0x20")
485 raise Exception("WPS-PIN flag not seen in scan results")
486 dev[0].dump_monitor()
487 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
488 dev[0].wait_connected(timeout=30)
489 hapd.request("SET wps_version_number 0x20")
490
491 @remote_compatible
492 def test_ap_wps_conf_pin_2sta(dev, apdev):
493 """Two stations trying to use WPS PIN at the same time"""
494 ssid = "test-wps-conf-pin2"
495 hapd = hostapd.add_ap(apdev[0],
496 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
497 "wpa_passphrase": "12345678", "wpa": "2",
498 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
499 logger.info("WPS provisioning step")
500 pin = "12345670"
501 pin2 = "55554444"
502 hapd.request("WPS_PIN " + dev[0].get_status_field("uuid") + " " + pin)
503 hapd.request("WPS_PIN " + dev[1].get_status_field("uuid") + " " + pin)
504 dev[0].dump_monitor()
505 dev[1].dump_monitor()
506 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
507 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
508 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
509 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
510 dev[0].wait_connected(timeout=30)
511 dev[1].wait_connected(timeout=30)
512
513 @remote_compatible
514 def test_ap_wps_conf_pin_timeout(dev, apdev):
515 """WPS PIN provisioning with configured AP timing out PIN"""
516 ssid = "test-wps-conf-pin"
517 hapd = hostapd.add_ap(apdev[0],
518 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
519 "wpa_passphrase": "12345678", "wpa": "2",
520 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
521 addr = dev[0].p2p_interface_addr()
522 pin = dev[0].wps_read_pin()
523 if "FAIL" not in hapd.request("WPS_PIN "):
524 raise Exception("Unexpected success on invalid WPS_PIN")
525 hapd.request("WPS_PIN any " + pin + " 1")
526 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
527 time.sleep(1.1)
528 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
529 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=20)
530 if ev is None:
531 raise Exception("WPS-PIN-NEEDED event timed out")
532 ev = dev[0].wait_event(["WPS-M2D"])
533 if ev is None:
534 raise Exception("M2D not reported")
535 dev[0].request("WPS_CANCEL")
536
537 hapd.request("WPS_PIN any " + pin + " 20 " + addr)
538 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
539 dev[0].wait_connected(timeout=30)
540
541 def test_ap_wps_reg_connect(dev, apdev):
542 """WPS registrar using AP PIN to connect"""
543 ssid = "test-wps-reg-ap-pin"
544 appin = "12345670"
545 hostapd.add_ap(apdev[0],
546 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
547 "wpa_passphrase": "12345678", "wpa": "2",
548 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
549 "ap_pin": appin})
550 logger.info("WPS provisioning step")
551 dev[0].dump_monitor()
552 dev[0].flush_scan_cache()
553 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
554 dev[0].wps_reg(apdev[0]['bssid'], appin)
555 status = dev[0].get_status()
556 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
557 raise Exception("Not fully connected")
558 if status['ssid'] != ssid:
559 raise Exception("Unexpected SSID")
560 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
561 raise Exception("Unexpected encryption configuration")
562 if status['key_mgmt'] != 'WPA2-PSK':
563 raise Exception("Unexpected key_mgmt")
564
565 def test_ap_wps_reg_connect_zero_len_ap_pin(dev, apdev):
566 """hostapd with zero length ap_pin parameter"""
567 ssid = "test-wps-reg-ap-pin"
568 appin = ""
569 hostapd.add_ap(apdev[0],
570 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
571 "wpa_passphrase": "12345678", "wpa": "2",
572 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
573 "ap_pin": appin})
574 logger.info("WPS provisioning step")
575 dev[0].dump_monitor()
576 dev[0].flush_scan_cache()
577 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
578 dev[0].wps_reg(apdev[0]['bssid'], appin, no_wait=True)
579 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
580 if ev is None:
581 raise Exception("No WPS-FAIL reported")
582 if "msg=5 config_error=15" not in ev:
583 raise Exception("Unexpected WPS-FAIL: " + ev)
584
585 def test_ap_wps_reg_connect_mixed_mode(dev, apdev):
586 """WPS registrar using AP PIN to connect (WPA+WPA2)"""
587 ssid = "test-wps-reg-ap-pin"
588 appin = "12345670"
589 hostapd.add_ap(apdev[0],
590 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
591 "wpa_passphrase": "12345678", "wpa": "3",
592 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
593 "wpa_pairwise": "TKIP", "ap_pin": appin})
594 dev[0].flush_scan_cache()
595 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
596 dev[0].wps_reg(apdev[0]['bssid'], appin)
597 status = dev[0].get_status()
598 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
599 raise Exception("Not fully connected")
600 if status['ssid'] != ssid:
601 raise Exception("Unexpected SSID")
602 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
603 raise Exception("Unexpected encryption configuration")
604 if status['key_mgmt'] != 'WPA2-PSK':
605 raise Exception("Unexpected key_mgmt")
606
607 def test_ap_wps_reg_override_ap_settings(dev, apdev):
608 """WPS registrar and ap_settings override"""
609 ap_settings = "/tmp/ap_wps_reg_override_ap_settings"
610 try:
611 os.remove(ap_settings)
612 except:
613 pass
614 # Override AP Settings with values that point to another AP
615 data = build_wsc_attr(ATTR_NETWORK_INDEX, b'\x01')
616 data += build_wsc_attr(ATTR_SSID, b"test")
617 data += build_wsc_attr(ATTR_AUTH_TYPE, b'\x00\x01')
618 data += build_wsc_attr(ATTR_ENCR_TYPE, b'\x00\x01')
619 data += build_wsc_attr(ATTR_NETWORK_KEY, b'')
620 data += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[1]['bssid'].replace(':', '')))
621 with open(ap_settings, "wb") as f:
622 f.write(data)
623 ssid = "test-wps-reg-ap-pin"
624 appin = "12345670"
625 hostapd.add_ap(apdev[0],
626 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
627 "wpa_passphrase": "12345678", "wpa": "2",
628 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
629 "ap_pin": appin, "ap_settings": ap_settings})
630 hapd2 = hostapd.add_ap(apdev[1], {"ssid": "test"})
631 dev[0].flush_scan_cache()
632 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
633 dev[0].scan_for_bss(apdev[1]['bssid'], freq=2412)
634 dev[0].wps_reg(apdev[0]['bssid'], appin)
635 ev = hapd2.wait_event(['AP-STA-CONNECTED'], timeout=10)
636 os.remove(ap_settings)
637 if ev is None:
638 raise Exception("No connection with the other AP")
639
640 def check_wps_reg_failure(dev, ap, appin):
641 dev.request("WPS_REG " + ap['bssid'] + " " + appin)
642 ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
643 if ev is None:
644 raise Exception("WPS operation timed out")
645 if "WPS-SUCCESS" in ev:
646 raise Exception("WPS operation succeeded unexpectedly")
647 if "config_error=15" not in ev:
648 raise Exception("WPS setup locked state was not reported correctly")
649
650 def test_ap_wps_random_ap_pin(dev, apdev):
651 """WPS registrar using random AP PIN"""
652 ssid = "test-wps-reg-random-ap-pin"
653 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
654 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
655 "wpa_passphrase": "12345678", "wpa": "2",
656 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
657 "device_name": "Wireless AP", "manufacturer": "Company",
658 "model_name": "WAP", "model_number": "123",
659 "serial_number": "12345", "device_type": "6-0050F204-1",
660 "os_version": "01020300",
661 "config_methods": "label push_button",
662 "uuid": ap_uuid, "upnp_iface": "lo"}
663 hapd = hostapd.add_ap(apdev[0], params)
664 appin = hapd.request("WPS_AP_PIN random")
665 if "FAIL" in appin:
666 raise Exception("Could not generate random AP PIN")
667 if appin not in hapd.request("WPS_AP_PIN get"):
668 raise Exception("Could not fetch current AP PIN")
669 logger.info("WPS provisioning step")
670 dev[0].flush_scan_cache()
671 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
672 dev[0].wps_reg(apdev[0]['bssid'], appin)
673
674 hapd.request("WPS_AP_PIN disable")
675 logger.info("WPS provisioning step with AP PIN disabled")
676 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
677 check_wps_reg_failure(dev[1], apdev[0], appin)
678
679 logger.info("WPS provisioning step with AP PIN reset")
680 appin = "12345670"
681 hapd.request("WPS_AP_PIN set " + appin)
682 dev[1].wps_reg(apdev[0]['bssid'], appin)
683 dev[0].request("REMOVE_NETWORK all")
684 dev[1].request("REMOVE_NETWORK all")
685 dev[0].wait_disconnected(timeout=10)
686 dev[1].wait_disconnected(timeout=10)
687
688 logger.info("WPS provisioning step after AP PIN timeout")
689 hapd.request("WPS_AP_PIN disable")
690 appin = hapd.request("WPS_AP_PIN random 1")
691 time.sleep(1.1)
692 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
693 raise Exception("AP PIN unexpectedly still enabled")
694 check_wps_reg_failure(dev[0], apdev[0], appin)
695
696 logger.info("WPS provisioning step after AP PIN timeout(2)")
697 hapd.request("WPS_AP_PIN disable")
698 appin = "12345670"
699 hapd.request("WPS_AP_PIN set " + appin + " 1")
700 time.sleep(1.1)
701 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
702 raise Exception("AP PIN unexpectedly still enabled")
703 check_wps_reg_failure(dev[1], apdev[0], appin)
704
705 with fail_test(hapd, 1, "os_get_random;wps_generate_pin"):
706 hapd.request("WPS_AP_PIN random 1")
707 hapd.request("WPS_AP_PIN disable")
708
709 with alloc_fail(hapd, 1, "upnp_wps_set_ap_pin"):
710 hapd.request("WPS_AP_PIN set 12345670")
711 hapd.request("WPS_AP_PIN disable")
712
713 if "FAIL" not in hapd.request("WPS_AP_PIN set"):
714 raise Exception("Invalid WPS_AP_PIN accepted")
715 if "FAIL" not in hapd.request("WPS_AP_PIN foo"):
716 raise Exception("Invalid WPS_AP_PIN accepted")
717
718 def test_ap_wps_reg_config(dev, apdev):
719 """WPS registrar configuring an AP using AP PIN"""
720 ssid = "test-wps-init-ap-pin"
721 appin = "12345670"
722 hostapd.add_ap(apdev[0],
723 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
724 "ap_pin": appin})
725 logger.info("WPS configuration step")
726 dev[0].flush_scan_cache()
727 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
728 dev[0].dump_monitor()
729 new_ssid = "wps-new-ssid"
730 new_passphrase = "1234567890"
731 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
732 new_passphrase)
733 status = dev[0].get_status()
734 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
735 raise Exception("Not fully connected")
736 if status['ssid'] != new_ssid:
737 raise Exception("Unexpected SSID")
738 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
739 raise Exception("Unexpected encryption configuration")
740 if status['key_mgmt'] != 'WPA2-PSK':
741 raise Exception("Unexpected key_mgmt")
742
743 logger.info("Re-configure back to open")
744 dev[0].request("REMOVE_NETWORK all")
745 dev[0].flush_scan_cache()
746 dev[0].dump_monitor()
747 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-open", "OPEN", "NONE", "")
748 status = dev[0].get_status()
749 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
750 raise Exception("Not fully connected")
751 if status['ssid'] != "wps-open":
752 raise Exception("Unexpected SSID")
753 if status['key_mgmt'] != 'NONE':
754 raise Exception("Unexpected key_mgmt")
755
756 def test_ap_wps_reg_config_ext_processing(dev, apdev):
757 """WPS registrar configuring an AP with external config processing"""
758 ssid = "test-wps-init-ap-pin"
759 appin = "12345670"
760 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
761 "wps_cred_processing": "1", "ap_pin": appin}
762 hapd = hostapd.add_ap(apdev[0], params)
763 dev[0].flush_scan_cache()
764 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
765 new_ssid = "wps-new-ssid"
766 new_passphrase = "1234567890"
767 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
768 new_passphrase, no_wait=True)
769 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
770 if ev is None:
771 raise Exception("WPS registrar operation timed out")
772 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=15)
773 if ev is None:
774 raise Exception("WPS configuration timed out")
775 if "1026" not in ev:
776 raise Exception("AP Settings missing from event")
777 hapd.request("SET wps_cred_processing 0")
778 if "FAIL" in hapd.request("WPS_CONFIG " + binascii.hexlify(new_ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(new_passphrase.encode()).decode()):
779 raise Exception("WPS_CONFIG command failed")
780 dev[0].wait_connected(timeout=15)
781
782 def test_ap_wps_reg_config_tkip(dev, apdev):
783 """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
784 skip_with_fips(dev[0])
785 ssid = "test-wps-init-ap"
786 appin = "12345670"
787 hostapd.add_ap(apdev[0],
788 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
789 "ap_pin": appin})
790 logger.info("WPS configuration step")
791 dev[0].flush_scan_cache()
792 dev[0].request("SET wps_version_number 0x10")
793 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
794 dev[0].dump_monitor()
795 new_ssid = "wps-new-ssid-with-tkip"
796 new_passphrase = "1234567890"
797 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
798 new_passphrase)
799 logger.info("Re-connect to verify WPA2 mixed mode")
800 dev[0].request("DISCONNECT")
801 id = 0
802 dev[0].set_network(id, "pairwise", "CCMP")
803 dev[0].set_network(id, "proto", "RSN")
804 dev[0].connect_network(id)
805 status = dev[0].get_status()
806 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
807 raise Exception("Not fully connected: wpa_state={} bssid={}".format(status['wpa_state'], status['bssid']))
808 if status['ssid'] != new_ssid:
809 raise Exception("Unexpected SSID")
810 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
811 raise Exception("Unexpected encryption configuration")
812 if status['key_mgmt'] != 'WPA2-PSK':
813 raise Exception("Unexpected key_mgmt")
814
815 def test_ap_wps_setup_locked(dev, apdev):
816 """WPS registrar locking up AP setup on AP PIN failures"""
817 ssid = "test-wps-incorrect-ap-pin"
818 appin = "12345670"
819 hapd = hostapd.add_ap(apdev[0],
820 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
821 "wpa_passphrase": "12345678", "wpa": "2",
822 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
823 "ap_pin": appin})
824 new_ssid = "wps-new-ssid-test"
825 new_passphrase = "1234567890"
826
827 dev[0].flush_scan_cache()
828 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
829 ap_setup_locked = False
830 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
831 dev[0].dump_monitor()
832 logger.info("Try incorrect AP PIN - attempt " + pin)
833 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
834 "CCMP", new_passphrase, no_wait=True)
835 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
836 if ev is None:
837 raise Exception("Timeout on receiving WPS operation failure event")
838 if "CTRL-EVENT-CONNECTED" in ev:
839 raise Exception("Unexpected connection")
840 if "config_error=15" in ev:
841 logger.info("AP Setup Locked")
842 ap_setup_locked = True
843 elif "config_error=18" not in ev:
844 raise Exception("config_error=18 not reported")
845 dev[0].wait_disconnected(timeout=10)
846 time.sleep(0.1)
847 if not ap_setup_locked:
848 raise Exception("AP setup was not locked")
849 dev[0].request("WPS_CANCEL")
850 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True,
851 only_new=True)
852 bss = dev[0].get_bss(apdev[0]['bssid'])
853 if 'wps_ap_setup_locked' not in bss or bss['wps_ap_setup_locked'] != '1':
854 logger.info("BSS: " + str(bss))
855 raise Exception("AP Setup Locked not indicated in scan results")
856
857 status = hapd.request("WPS_GET_STATUS")
858 if "Last WPS result: Failed" not in status:
859 raise Exception("WPS failure result not shown correctly")
860 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
861 raise Exception("Peer address not shown correctly")
862
863 time.sleep(0.5)
864 dev[0].dump_monitor()
865 logger.info("WPS provisioning step")
866 pin = dev[0].wps_read_pin()
867 hapd.request("WPS_PIN any " + pin)
868 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
869 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
870 if ev is None:
871 raise Exception("WPS success was not reported")
872 dev[0].wait_connected(timeout=30)
873
874 appin = hapd.request("WPS_AP_PIN random")
875 if "FAIL" in appin:
876 raise Exception("Could not generate random AP PIN")
877 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=10)
878 if ev is None:
879 raise Exception("Failed to unlock AP PIN")
880
881 def test_ap_wps_setup_locked_timeout(dev, apdev):
882 """WPS re-enabling AP PIN after timeout"""
883 ssid = "test-wps-incorrect-ap-pin"
884 appin = "12345670"
885 hapd = hostapd.add_ap(apdev[0],
886 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
887 "wpa_passphrase": "12345678", "wpa": "2",
888 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
889 "ap_pin": appin})
890 new_ssid = "wps-new-ssid-test"
891 new_passphrase = "1234567890"
892
893 dev[0].flush_scan_cache()
894 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
895 ap_setup_locked = False
896 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
897 dev[0].dump_monitor()
898 logger.info("Try incorrect AP PIN - attempt " + pin)
899 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
900 "CCMP", new_passphrase, no_wait=True)
901 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"], timeout=15)
902 if ev is None:
903 raise Exception("Timeout on receiving WPS operation failure event")
904 if "CTRL-EVENT-CONNECTED" in ev:
905 raise Exception("Unexpected connection")
906 if "config_error=15" in ev:
907 logger.info("AP Setup Locked")
908 ap_setup_locked = True
909 break
910 elif "config_error=18" not in ev:
911 raise Exception("config_error=18 not reported")
912 dev[0].wait_disconnected(timeout=10)
913 time.sleep(0.1)
914 if not ap_setup_locked:
915 raise Exception("AP setup was not locked")
916 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=80)
917 if ev is None:
918 raise Exception("AP PIN did not get unlocked on 60 second timeout")
919
920 def test_ap_wps_setup_locked_2(dev, apdev):
921 """WPS AP configured for special ap_setup_locked=2 mode"""
922 ssid = "test-wps-ap-pin"
923 appin = "12345670"
924 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
925 "wpa_passphrase": "12345678", "wpa": "2",
926 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
927 "ap_pin": appin, "ap_setup_locked": "2"}
928 hapd = hostapd.add_ap(apdev[0], params)
929 new_ssid = "wps-new-ssid-test"
930 new_passphrase = "1234567890"
931
932 dev[0].flush_scan_cache()
933 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
934 dev[0].wps_reg(apdev[0]['bssid'], appin)
935 dev[0].request("REMOVE_NETWORK all")
936 dev[0].wait_disconnected()
937
938 hapd.dump_monitor()
939 dev[0].dump_monitor()
940 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK",
941 "CCMP", new_passphrase, no_wait=True)
942
943 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
944 if ev is None:
945 raise Exception("hostapd did not report WPS failure")
946 if "msg=12 config_error=15" not in ev:
947 raise Exception("Unexpected failure reason (AP): " + ev)
948
949 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
950 if ev is None:
951 raise Exception("Timeout on receiving WPS operation failure event")
952 if "CTRL-EVENT-CONNECTED" in ev:
953 raise Exception("Unexpected connection")
954 if "config_error=15" not in ev:
955 raise Exception("Unexpected failure reason (STA): " + ev)
956 dev[0].request("WPS_CANCEL")
957 dev[0].wait_disconnected()
958
959 @remote_compatible
960 def test_ap_wps_pbc_overlap_2ap(dev, apdev):
961 """WPS PBC session overlap with two active APs"""
962 params = {"ssid": "wps1", "eap_server": "1", "wps_state": "2",
963 "wpa_passphrase": "12345678", "wpa": "2",
964 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
965 "wps_independent": "1"}
966 hapd = hostapd.add_ap(apdev[0], params)
967 params = {"ssid": "wps2", "eap_server": "1", "wps_state": "2",
968 "wpa_passphrase": "123456789", "wpa": "2",
969 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
970 "wps_independent": "1"}
971 hapd2 = hostapd.add_ap(apdev[1], params)
972 hapd.request("WPS_PBC")
973 hapd2.request("WPS_PBC")
974 logger.info("WPS provisioning step")
975 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
976 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
977 dev[0].request("WPS_PBC")
978 ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
979 if ev is None:
980 raise Exception("PBC session overlap not detected")
981 hapd.request("DISABLE")
982 hapd2.request("DISABLE")
983 dev[0].flush_scan_cache()
984
985 @remote_compatible
986 def test_ap_wps_pbc_overlap_2sta(dev, apdev):
987 """WPS PBC session overlap with two active STAs"""
988 ssid = "test-wps-pbc-overlap"
989 hapd = hostapd.add_ap(apdev[0],
990 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
991 "wpa_passphrase": "12345678", "wpa": "2",
992 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
993 logger.info("WPS provisioning step")
994 hapd.request("WPS_PBC")
995 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
996 dev[0].dump_monitor()
997 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
998 dev[1].dump_monitor()
999 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1000 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1001 ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
1002 if ev is None:
1003 raise Exception("PBC session overlap not detected (dev0)")
1004 if "config_error=12" not in ev:
1005 raise Exception("PBC session overlap not correctly reported (dev0)")
1006 dev[0].request("WPS_CANCEL")
1007 dev[0].request("DISCONNECT")
1008 ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
1009 if ev is None:
1010 raise Exception("PBC session overlap not detected (dev1)")
1011 if "config_error=12" not in ev:
1012 raise Exception("PBC session overlap not correctly reported (dev1)")
1013 dev[1].request("WPS_CANCEL")
1014 dev[1].request("DISCONNECT")
1015 hapd.request("WPS_CANCEL")
1016 ret = hapd.request("WPS_PBC")
1017 if "FAIL" not in ret:
1018 raise Exception("PBC mode allowed to be started while PBC overlap still active")
1019 hapd.request("DISABLE")
1020 dev[0].flush_scan_cache()
1021 dev[1].flush_scan_cache()
1022
1023 @remote_compatible
1024 def test_ap_wps_cancel(dev, apdev):
1025 """WPS AP cancelling enabled config method"""
1026 ssid = "test-wps-ap-cancel"
1027 hapd = hostapd.add_ap(apdev[0],
1028 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1029 "wpa_passphrase": "12345678", "wpa": "2",
1030 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
1031 bssid = apdev[0]['bssid']
1032
1033 logger.info("Verify PBC enable/cancel")
1034 hapd.request("WPS_PBC")
1035 dev[0].scan(freq="2412")
1036 dev[0].scan(freq="2412")
1037 bss = dev[0].get_bss(apdev[0]['bssid'])
1038 if "[WPS-PBC]" not in bss['flags']:
1039 raise Exception("WPS-PBC flag missing")
1040 if "FAIL" in hapd.request("WPS_CANCEL"):
1041 raise Exception("WPS_CANCEL failed")
1042 dev[0].scan(freq="2412")
1043 dev[0].scan(freq="2412")
1044 bss = dev[0].get_bss(apdev[0]['bssid'])
1045 if "[WPS-PBC]" in bss['flags']:
1046 raise Exception("WPS-PBC flag not cleared")
1047
1048 logger.info("Verify PIN enable/cancel")
1049 hapd.request("WPS_PIN any 12345670")
1050 dev[0].scan(freq="2412")
1051 dev[0].scan(freq="2412")
1052 bss = dev[0].get_bss(apdev[0]['bssid'])
1053 if "[WPS-AUTH]" not in bss['flags']:
1054 raise Exception("WPS-AUTH flag missing")
1055 if "FAIL" in hapd.request("WPS_CANCEL"):
1056 raise Exception("WPS_CANCEL failed")
1057 dev[0].scan(freq="2412")
1058 dev[0].scan(freq="2412")
1059 bss = dev[0].get_bss(apdev[0]['bssid'])
1060 if "[WPS-AUTH]" in bss['flags']:
1061 raise Exception("WPS-AUTH flag not cleared")
1062
1063 def test_ap_wps_er_add_enrollee(dev, apdev):
1064 """WPS ER configuring AP and adding a new enrollee using PIN"""
1065 try:
1066 _test_ap_wps_er_add_enrollee(dev, apdev)
1067 finally:
1068 dev[0].request("WPS_ER_STOP")
1069
1070 def _test_ap_wps_er_add_enrollee(dev, apdev):
1071 ssid = "wps-er-add-enrollee"
1072 ap_pin = "12345670"
1073 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1074 hostapd.add_ap(apdev[0],
1075 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
1076 "device_name": "Wireless AP", "manufacturer": "Company",
1077 "model_name": "WAP", "model_number": "123",
1078 "serial_number": "12345", "device_type": "6-0050F204-1",
1079 "os_version": "01020300",
1080 'friendly_name': "WPS AP - <>&'\" - TEST",
1081 "config_methods": "label push_button",
1082 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1083 logger.info("WPS configuration step")
1084 new_passphrase = "1234567890"
1085 dev[0].dump_monitor()
1086 dev[0].flush_scan_cache()
1087 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1088 dev[0].wps_reg(apdev[0]['bssid'], ap_pin, ssid, "WPA2PSK", "CCMP",
1089 new_passphrase)
1090 status = dev[0].get_status()
1091 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1092 raise Exception("Not fully connected")
1093 if status['ssid'] != ssid:
1094 raise Exception("Unexpected SSID")
1095 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
1096 raise Exception("Unexpected encryption configuration")
1097 if status['key_mgmt'] != 'WPA2-PSK':
1098 raise Exception("Unexpected key_mgmt")
1099
1100 logger.info("Start ER")
1101 dev[0].request("WPS_ER_START ifname=lo")
1102 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1103 if ev is None:
1104 raise Exception("AP discovery timed out")
1105 if ap_uuid not in ev:
1106 raise Exception("Expected AP UUID not found")
1107 if "|WPS AP - &lt;&gt;&amp;&apos;&quot; - TEST|Company|" not in ev:
1108 raise Exception("Expected friendly name not found")
1109
1110 logger.info("Learn AP configuration through UPnP")
1111 dev[0].dump_monitor()
1112 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1113 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1114 if ev is None:
1115 raise Exception("AP learn timed out")
1116 if ap_uuid not in ev:
1117 raise Exception("Expected AP UUID not in settings")
1118 if "ssid=" + ssid not in ev:
1119 raise Exception("Expected SSID not in settings")
1120 if "key=" + new_passphrase not in ev:
1121 raise Exception("Expected passphrase not in settings")
1122 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1123 if ev is None:
1124 raise Exception("WPS-FAIL after AP learn timed out")
1125 time.sleep(0.1)
1126
1127 logger.info("Add Enrollee using ER")
1128 pin = dev[1].wps_read_pin()
1129 dev[0].dump_monitor()
1130 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1131 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1132 dev[1].dump_monitor()
1133 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1134 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
1135 if ev is None:
1136 raise Exception("Enrollee did not report success")
1137 dev[1].wait_connected(timeout=15)
1138 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1139 if ev is None:
1140 raise Exception("WPS ER did not report success")
1141 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1142
1143 logger.info("Add a specific Enrollee using ER")
1144 pin = dev[2].wps_read_pin()
1145 addr2 = dev[2].p2p_interface_addr()
1146 dev[0].dump_monitor()
1147 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1148 dev[2].dump_monitor()
1149 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1150 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1151 if ev is None:
1152 raise Exception("Enrollee not seen")
1153 if addr2 not in ev:
1154 raise Exception("Unexpected Enrollee MAC address")
1155 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
1156 dev[2].wait_connected(timeout=30)
1157 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1158 if ev is None:
1159 raise Exception("WPS ER did not report success")
1160
1161 logger.info("Verify registrar selection behavior")
1162 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1163 dev[1].request("DISCONNECT")
1164 dev[1].wait_disconnected(timeout=10)
1165 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1166 dev[1].scan(freq="2412")
1167 bss = dev[1].get_bss(apdev[0]['bssid'])
1168 if "[WPS-AUTH]" not in bss['flags']:
1169 # It is possible for scan to miss an update especially when running
1170 # tests under load with multiple VMs, so allow another attempt.
1171 dev[1].scan(freq="2412")
1172 bss = dev[1].get_bss(apdev[0]['bssid'])
1173 if "[WPS-AUTH]" not in bss['flags']:
1174 raise Exception("WPS-AUTH flag missing")
1175
1176 logger.info("Stop ER")
1177 dev[0].dump_monitor()
1178 dev[0].request("WPS_ER_STOP")
1179 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
1180 if ev is None:
1181 raise Exception("WPS ER unsubscription timed out")
1182 # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
1183 # a bit before verifying that the scan results have changed.
1184 time.sleep(0.2)
1185
1186 for i in range(0, 10):
1187 dev[1].request("BSS_FLUSH 0")
1188 dev[1].scan(freq="2412", only_new=True)
1189 bss = dev[1].get_bss(apdev[0]['bssid'])
1190 if bss and 'flags' in bss and "[WPS-AUTH]" not in bss['flags']:
1191 break
1192 logger.debug("WPS-AUTH flag was still in place - wait a bit longer")
1193 time.sleep(0.1)
1194 if "[WPS-AUTH]" in bss['flags']:
1195 raise Exception("WPS-AUTH flag not removed")
1196
1197 def test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1198 """WPS ER adding a new enrollee identified by UUID"""
1199 try:
1200 _test_ap_wps_er_add_enrollee_uuid(dev, apdev)
1201 finally:
1202 dev[0].request("WPS_ER_STOP")
1203
1204 def _test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1205 ssid = "wps-er-add-enrollee"
1206 ap_pin = "12345670"
1207 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1208 hostapd.add_ap(apdev[0],
1209 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1210 "wpa_passphrase": "12345678", "wpa": "2",
1211 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1212 "device_name": "Wireless AP", "manufacturer": "Company",
1213 "model_name": "WAP", "model_number": "123",
1214 "serial_number": "12345", "device_type": "6-0050F204-1",
1215 "os_version": "01020300",
1216 "config_methods": "label push_button",
1217 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1218 logger.info("WPS configuration step")
1219 dev[0].flush_scan_cache()
1220 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1221 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1222
1223 logger.info("Start ER")
1224 dev[0].request("WPS_ER_START ifname=lo")
1225 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1226 if ev is None:
1227 raise Exception("AP discovery timed out")
1228 if ap_uuid not in ev:
1229 raise Exception("Expected AP UUID not found")
1230
1231 logger.info("Learn AP configuration through UPnP")
1232 dev[0].dump_monitor()
1233 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1234 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1235 if ev is None:
1236 raise Exception("AP learn timed out")
1237 if ap_uuid not in ev:
1238 raise Exception("Expected AP UUID not in settings")
1239 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1240 if ev is None:
1241 raise Exception("WPS-FAIL after AP learn timed out")
1242 time.sleep(0.1)
1243
1244 logger.info("Add a specific Enrollee using ER (PBC/UUID)")
1245 addr1 = dev[1].p2p_interface_addr()
1246 dev[0].dump_monitor()
1247 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1248 dev[1].dump_monitor()
1249 dev[1].request("WPS_PBC %s" % apdev[0]['bssid'])
1250 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1251 if ev is None:
1252 raise Exception("Enrollee not seen")
1253 if addr1 not in ev:
1254 raise Exception("Unexpected Enrollee MAC address")
1255 uuid = ev.split(' ')[1]
1256 dev[0].request("WPS_ER_PBC " + uuid)
1257 dev[1].wait_connected(timeout=30)
1258 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1259 if ev is None:
1260 raise Exception("WPS ER did not report success")
1261
1262 logger.info("Add a specific Enrollee using ER (PIN/UUID)")
1263 pin = dev[2].wps_read_pin()
1264 addr2 = dev[2].p2p_interface_addr()
1265 dev[0].dump_monitor()
1266 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1267 dev[2].dump_monitor()
1268 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1269 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1270 if ev is None:
1271 raise Exception("Enrollee not seen")
1272 if addr2 not in ev:
1273 raise Exception("Unexpected Enrollee MAC address")
1274 uuid = ev.split(' ')[1]
1275 dev[0].request("WPS_ER_PIN " + uuid + " " + pin)
1276 dev[2].wait_connected(timeout=30)
1277 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1278 if ev is None:
1279 raise Exception("WPS ER did not report success")
1280
1281 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-REMOVE"], timeout=15)
1282 if ev is None:
1283 raise Exception("No Enrollee STA entry timeout seen")
1284
1285 logger.info("Stop ER")
1286 dev[0].dump_monitor()
1287 dev[0].request("WPS_ER_STOP")
1288
1289 def test_ap_wps_er_multi_add_enrollee(dev, apdev):
1290 """Multiple WPS ERs adding a new enrollee using PIN"""
1291 try:
1292 _test_ap_wps_er_multi_add_enrollee(dev, apdev)
1293 finally:
1294 for i in range(2):
1295 dev[i].request("WPS_ER_STOP")
1296
1297 def _test_ap_wps_er_multi_add_enrollee(dev, apdev):
1298 ssid = "wps-er-add-enrollee"
1299 ap_pin = "12345670"
1300 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1301 hostapd.add_ap(apdev[0],
1302 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1303 "wpa_passphrase": "12345678", "wpa": "2",
1304 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1305 "device_name": "Wireless AP", "manufacturer": "Company",
1306 "model_name": "WAP", "model_number": "123",
1307 "serial_number": "12345", "device_type": "6-0050F204-1",
1308 "os_version": "01020300",
1309 'friendly_name': "WPS AP",
1310 "config_methods": "label push_button",
1311 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1312
1313 for i in range(2):
1314 dev[i].flush_scan_cache()
1315 dev[i].scan_for_bss(apdev[0]['bssid'], freq=2412)
1316 dev[i].wps_reg(apdev[0]['bssid'], ap_pin)
1317 for i in range(2):
1318 dev[i].request("WPS_ER_START ifname=lo")
1319 for i in range(2):
1320 ev = dev[i].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1321 if ev is None:
1322 raise Exception("AP discovery timed out")
1323 dev[i].dump_monitor()
1324 for i in range(2):
1325 dev[i].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1326 for i in range(2):
1327 ev = dev[i].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1328 if ev is None:
1329 raise Exception("AP learn timed out")
1330 ev = dev[i].wait_event(["WPS-FAIL"], timeout=15)
1331 if ev is None:
1332 raise Exception("WPS-FAIL after AP learn timed out")
1333
1334 time.sleep(0.1)
1335
1336 pin = dev[2].wps_read_pin()
1337 addr = dev[2].own_addr()
1338 dev[0].dump_monitor()
1339 dev[0].request("WPS_ER_PIN any " + pin + " " + addr)
1340 dev[1].dump_monitor()
1341 dev[1].request("WPS_ER_PIN any " + pin + " " + addr)
1342
1343 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1344 dev[2].dump_monitor()
1345 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1346 ev = dev[2].wait_event(["WPS-SUCCESS"], timeout=30)
1347 if ev is None:
1348 raise Exception("Enrollee did not report success")
1349 dev[2].wait_connected(timeout=15)
1350
1351 def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1352 """WPS ER connected to AP and adding a new enrollee using PBC"""
1353 try:
1354 _test_ap_wps_er_add_enrollee_pbc(dev, apdev)
1355 finally:
1356 dev[0].request("WPS_ER_STOP")
1357
1358 def _test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1359 ssid = "wps-er-add-enrollee-pbc"
1360 ap_pin = "12345670"
1361 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1362 hostapd.add_ap(apdev[0],
1363 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1364 "wpa_passphrase": "12345678", "wpa": "2",
1365 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1366 "device_name": "Wireless AP", "manufacturer": "Company",
1367 "model_name": "WAP", "model_number": "123",
1368 "serial_number": "12345", "device_type": "6-0050F204-1",
1369 "os_version": "01020300",
1370 "config_methods": "label push_button",
1371 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1372 logger.info("Learn AP configuration")
1373 dev[0].flush_scan_cache()
1374 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1375 dev[0].dump_monitor()
1376 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1377 status = dev[0].get_status()
1378 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1379 raise Exception("Not fully connected")
1380
1381 logger.info("Start ER")
1382 dev[0].request("WPS_ER_START ifname=lo")
1383 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1384 if ev is None:
1385 raise Exception("AP discovery timed out")
1386 if ap_uuid not in ev:
1387 raise Exception("Expected AP UUID not found")
1388
1389 enrollee = dev[1].p2p_interface_addr()
1390
1391 if "FAIL-UNKNOWN-UUID" not in dev[0].request("WPS_ER_PBC " + enrollee):
1392 raise Exception("Unknown UUID not reported")
1393
1394 logger.info("Add Enrollee using ER and PBC")
1395 dev[0].dump_monitor()
1396 dev[1].dump_monitor()
1397 dev[1].request("WPS_PBC")
1398
1399 for i in range(0, 2):
1400 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1401 if ev is None:
1402 raise Exception("Enrollee discovery timed out")
1403 if enrollee in ev:
1404 break
1405 if i == 1:
1406 raise Exception("Expected Enrollee not found")
1407 if "FAIL-NO-AP-SETTINGS" not in dev[0].request("WPS_ER_PBC " + enrollee):
1408 raise Exception("Unknown UUID not reported")
1409 logger.info("Use learned network configuration on ER")
1410 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1411 if "OK" not in dev[0].request("WPS_ER_PBC " + enrollee):
1412 raise Exception("WPS_ER_PBC failed")
1413
1414 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
1415 if ev is None:
1416 raise Exception("Enrollee did not report success")
1417 dev[1].wait_connected(timeout=15)
1418 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1419 if ev is None:
1420 raise Exception("WPS ER did not report success")
1421 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1422
1423 def test_ap_wps_er_pbc_overlap(dev, apdev):
1424 """WPS ER connected to AP and PBC session overlap"""
1425 try:
1426 _test_ap_wps_er_pbc_overlap(dev, apdev)
1427 finally:
1428 dev[0].request("WPS_ER_STOP")
1429
1430 def _test_ap_wps_er_pbc_overlap(dev, apdev):
1431 ssid = "wps-er-add-enrollee-pbc"
1432 ap_pin = "12345670"
1433 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1434 hostapd.add_ap(apdev[0],
1435 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1436 "wpa_passphrase": "12345678", "wpa": "2",
1437 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1438 "device_name": "Wireless AP", "manufacturer": "Company",
1439 "model_name": "WAP", "model_number": "123",
1440 "serial_number": "12345", "device_type": "6-0050F204-1",
1441 "os_version": "01020300",
1442 "config_methods": "label push_button",
1443 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1444 dev[0].flush_scan_cache()
1445 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1446 dev[0].dump_monitor()
1447 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1448
1449 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1450 dev[2].scan_for_bss(apdev[0]['bssid'], freq="2412")
1451 # avoid leaving dev 1 or 2 as the last Probe Request to the AP
1452 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True)
1453
1454 dev[0].dump_monitor()
1455 dev[0].request("WPS_ER_START ifname=lo")
1456
1457 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1458 if ev is None:
1459 raise Exception("AP discovery timed out")
1460 if ap_uuid not in ev:
1461 raise Exception("Expected AP UUID not found")
1462
1463 # verify BSSID selection of the AP instead of UUID
1464 if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
1465 raise Exception("Could not select AP based on BSSID")
1466
1467 dev[0].dump_monitor()
1468 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1469 dev[2].request("WPS_PBC " + apdev[0]['bssid'])
1470 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1471 if ev is None:
1472 raise Exception("PBC scan failed")
1473 ev = dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1474 if ev is None:
1475 raise Exception("PBC scan failed")
1476 found1 = False
1477 found2 = False
1478 addr1 = dev[1].own_addr()
1479 addr2 = dev[2].own_addr()
1480 for i in range(3):
1481 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1482 if ev is None:
1483 raise Exception("Enrollee discovery timed out")
1484 if addr1 in ev:
1485 found1 = True
1486 if found2:
1487 break
1488 if addr2 in ev:
1489 found2 = True
1490 if found1:
1491 break
1492 if dev[0].request("WPS_ER_PBC " + ap_uuid) != "FAIL-PBC-OVERLAP\n":
1493 raise Exception("PBC overlap not reported")
1494 dev[1].request("WPS_CANCEL")
1495 dev[2].request("WPS_CANCEL")
1496 if dev[0].request("WPS_ER_PBC foo") != "FAIL\n":
1497 raise Exception("Invalid WPS_ER_PBC accepted")
1498
1499 def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1500 """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
1501 try:
1502 _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev)
1503 finally:
1504 dev[0].request("WPS_ER_STOP")
1505
1506 def _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1507 ssid = "wps-er-add-enrollee-pbc"
1508 ap_pin = "12345670"
1509 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1510 hostapd.add_ap(apdev[0],
1511 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1512 "wpa_passphrase": "12345678", "wpa": "2",
1513 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1514 "device_name": "Wireless AP", "manufacturer": "Company",
1515 "model_name": "WAP", "model_number": "123",
1516 "serial_number": "12345", "device_type": "6-0050F204-1",
1517 "os_version": "01020300",
1518 "config_methods": "label push_button",
1519 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1520 logger.info("Learn AP configuration")
1521 dev[0].request("SET wps_version_number 0x10")
1522 dev[0].flush_scan_cache()
1523 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1524 dev[0].dump_monitor()
1525 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1526 status = dev[0].get_status()
1527 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1528 raise Exception("Not fully connected")
1529
1530 logger.info("Start ER")
1531 dev[0].request("WPS_ER_START ifname=lo")
1532 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1533 if ev is None:
1534 raise Exception("AP discovery timed out")
1535 if ap_uuid not in ev:
1536 raise Exception("Expected AP UUID not found")
1537
1538 logger.info("Use learned network configuration on ER")
1539 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1540
1541 logger.info("Add Enrollee using ER and PIN")
1542 enrollee = dev[1].p2p_interface_addr()
1543 pin = dev[1].wps_read_pin()
1544 dev[0].dump_monitor()
1545 dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
1546 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1547 dev[1].dump_monitor()
1548 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1549 dev[1].wait_connected(timeout=30)
1550 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1551 if ev is None:
1552 raise Exception("WPS ER did not report success")
1553
1554 @remote_compatible
1555 def test_ap_wps_er_config_ap(dev, apdev):
1556 """WPS ER configuring AP over UPnP"""
1557 try:
1558 _test_ap_wps_er_config_ap(dev, apdev)
1559 finally:
1560 dev[0].request("WPS_ER_STOP")
1561
1562 def _test_ap_wps_er_config_ap(dev, apdev):
1563 ssid = "wps-er-ap-config"
1564 ap_pin = "12345670"
1565 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1566 hostapd.add_ap(apdev[0],
1567 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1568 "wpa_passphrase": "12345678", "wpa": "2",
1569 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1570 "device_name": "Wireless AP", "manufacturer": "Company",
1571 "model_name": "WAP", "model_number": "123",
1572 "serial_number": "12345", "device_type": "6-0050F204-1",
1573 "os_version": "01020300",
1574 "config_methods": "label push_button",
1575 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1576
1577 logger.info("Connect ER to the AP")
1578 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
1579
1580 logger.info("WPS configuration step")
1581 dev[0].request("WPS_ER_START ifname=lo")
1582 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1583 if ev is None:
1584 raise Exception("AP discovery timed out")
1585 if ap_uuid not in ev:
1586 raise Exception("Expected AP UUID not found")
1587 new_passphrase = "1234567890"
1588 dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
1589 binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " +
1590 binascii.hexlify(new_passphrase.encode()).decode())
1591 ev = dev[0].wait_event(["WPS-SUCCESS"])
1592 if ev is None:
1593 raise Exception("WPS ER configuration operation timed out")
1594 dev[0].wait_disconnected(timeout=10)
1595 dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
1596
1597 logger.info("WPS ER restart")
1598 dev[0].request("WPS_ER_START")
1599 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1600 if ev is None:
1601 raise Exception("AP discovery timed out on ER restart")
1602 if ap_uuid not in ev:
1603 raise Exception("Expected AP UUID not found on ER restart")
1604 if "OK" not in dev[0].request("WPS_ER_STOP"):
1605 raise Exception("WPS_ER_STOP failed")
1606 if "OK" not in dev[0].request("WPS_ER_STOP"):
1607 raise Exception("WPS_ER_STOP failed")
1608
1609 @remote_compatible
1610 def test_ap_wps_er_cache_ap_settings(dev, apdev):
1611 """WPS ER caching AP settings"""
1612 try:
1613 _test_ap_wps_er_cache_ap_settings(dev, apdev)
1614 finally:
1615 dev[0].request("WPS_ER_STOP")
1616
1617 def _test_ap_wps_er_cache_ap_settings(dev, apdev):
1618 ssid = "wps-er-add-enrollee"
1619 ap_pin = "12345670"
1620 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1621 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1622 "wpa_passphrase": "12345678", "wpa": "2",
1623 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1624 "device_name": "Wireless AP", "manufacturer": "Company",
1625 "model_name": "WAP", "model_number": "123",
1626 "serial_number": "12345", "device_type": "6-0050F204-1",
1627 "os_version": "01020300",
1628 "config_methods": "label push_button",
1629 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
1630 hapd = hostapd.add_ap(apdev[0], params)
1631 dev[0].flush_scan_cache()
1632 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1633 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1634 id = int(dev[0].list_networks()[0]['id'])
1635 dev[0].set_network(id, "scan_freq", "2412")
1636
1637 dev[0].request("WPS_ER_START ifname=lo")
1638 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1639 if ev is None:
1640 raise Exception("AP discovery timed out")
1641 if ap_uuid not in ev:
1642 raise Exception("Expected AP UUID not found")
1643
1644 dev[0].dump_monitor()
1645 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1646 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1647 if ev is None:
1648 raise Exception("AP learn timed out")
1649 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1650 if ev is None:
1651 raise Exception("WPS-FAIL after AP learn timed out")
1652 time.sleep(0.1)
1653
1654 hapd.disable()
1655
1656 for i in range(2):
1657 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE", "CTRL-EVENT-DISCONNECTED"],
1658 timeout=15)
1659 if ev is None:
1660 raise Exception("AP removal or disconnection timed out")
1661
1662 hapd = hostapd.add_ap(apdev[0], params)
1663 for i in range(2):
1664 ev = dev[0].wait_event(["WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED"],
1665 timeout=15)
1666 if ev is None:
1667 raise Exception("AP discovery or connection timed out")
1668
1669 pin = dev[1].wps_read_pin()
1670 dev[0].dump_monitor()
1671 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1672
1673 time.sleep(0.2)
1674
1675 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1676 dev[1].dump_monitor()
1677 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1678 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
1679 if ev is None:
1680 raise Exception("Enrollee did not report success")
1681 dev[1].wait_connected(timeout=15)
1682 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1683 if ev is None:
1684 raise Exception("WPS ER did not report success")
1685
1686 dev[0].dump_monitor()
1687 dev[0].request("WPS_ER_STOP")
1688
1689 def test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1690 """WPS ER caching AP settings (OOM)"""
1691 try:
1692 _test_ap_wps_er_cache_ap_settings_oom(dev, apdev)
1693 finally:
1694 dev[0].request("WPS_ER_STOP")
1695
1696 def _test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1697 ssid = "wps-er-add-enrollee"
1698 ap_pin = "12345670"
1699 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1700 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1701 "wpa_passphrase": "12345678", "wpa": "2",
1702 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1703 "device_name": "Wireless AP", "manufacturer": "Company",
1704 "model_name": "WAP", "model_number": "123",
1705 "serial_number": "12345", "device_type": "6-0050F204-1",
1706 "os_version": "01020300",
1707 "config_methods": "label push_button",
1708 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
1709 hapd = hostapd.add_ap(apdev[0], params)
1710 dev[0].flush_scan_cache()
1711 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1712 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1713 id = int(dev[0].list_networks()[0]['id'])
1714 dev[0].set_network(id, "scan_freq", "2412")
1715
1716 dev[0].request("WPS_ER_START ifname=lo")
1717 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1718 if ev is None:
1719 raise Exception("AP discovery timed out")
1720 if ap_uuid not in ev:
1721 raise Exception("Expected AP UUID not found")
1722
1723 dev[0].dump_monitor()
1724 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1725 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1726 if ev is None:
1727 raise Exception("AP learn timed out")
1728 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1729 if ev is None:
1730 raise Exception("WPS-FAIL after AP learn timed out")
1731 time.sleep(0.1)
1732
1733 with alloc_fail(dev[0], 1, "=wps_er_ap_use_cached_settings"):
1734 hapd.disable()
1735
1736 for i in range(2):
1737 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE",
1738 "CTRL-EVENT-DISCONNECTED"],
1739 timeout=15)
1740 if ev is None:
1741 raise Exception("AP removal or disconnection timed out")
1742
1743 hapd = hostapd.add_ap(apdev[0], params)
1744 for i in range(2):
1745 ev = dev[0].wait_event(["WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED"],
1746 timeout=15)
1747 if ev is None:
1748 raise Exception("AP discovery or connection timed out")
1749
1750 dev[0].request("WPS_ER_STOP")
1751
1752 def test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1753 """WPS ER caching AP settings (OOM 2)"""
1754 try:
1755 _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev)
1756 finally:
1757 dev[0].request("WPS_ER_STOP")
1758
1759 def _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1760 ssid = "wps-er-add-enrollee"
1761 ap_pin = "12345670"
1762 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1763 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1764 "wpa_passphrase": "12345678", "wpa": "2",
1765 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1766 "device_name": "Wireless AP", "manufacturer": "Company",
1767 "model_name": "WAP", "model_number": "123",
1768 "serial_number": "12345", "device_type": "6-0050F204-1",
1769 "os_version": "01020300",
1770 "config_methods": "label push_button",
1771 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
1772 hapd = hostapd.add_ap(apdev[0], params)
1773 dev[0].flush_scan_cache()
1774 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1775 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1776 id = int(dev[0].list_networks()[0]['id'])
1777 dev[0].set_network(id, "scan_freq", "2412")
1778
1779 dev[0].request("WPS_ER_START ifname=lo")
1780 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1781 if ev is None:
1782 raise Exception("AP discovery timed out")
1783 if ap_uuid not in ev:
1784 raise Exception("Expected AP UUID not found")
1785
1786 dev[0].dump_monitor()
1787 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1788 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1789 if ev is None:
1790 raise Exception("AP learn timed out")
1791 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1792 if ev is None:
1793 raise Exception("WPS-FAIL after AP learn timed out")
1794 time.sleep(0.1)
1795
1796 with alloc_fail(dev[0], 1, "=wps_er_ap_cache_settings"):
1797 hapd.disable()
1798
1799 for i in range(2):
1800 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE",
1801 "CTRL-EVENT-DISCONNECTED"],
1802 timeout=15)
1803 if ev is None:
1804 raise Exception("AP removal or disconnection timed out")
1805
1806 hapd = hostapd.add_ap(apdev[0], params)
1807 for i in range(2):
1808 ev = dev[0].wait_event(["WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED"],
1809 timeout=15)
1810 if ev is None:
1811 raise Exception("AP discovery or connection timed out")
1812
1813 dev[0].request("WPS_ER_STOP")
1814
1815 def test_ap_wps_er_subscribe_oom(dev, apdev):
1816 """WPS ER subscribe OOM"""
1817 try:
1818 _test_ap_wps_er_subscribe_oom(dev, apdev)
1819 finally:
1820 dev[0].request("WPS_ER_STOP")
1821
1822 def _test_ap_wps_er_subscribe_oom(dev, apdev):
1823 ssid = "wps-er-add-enrollee"
1824 ap_pin = "12345670"
1825 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1826 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1827 "wpa_passphrase": "12345678", "wpa": "2",
1828 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1829 "device_name": "Wireless AP", "manufacturer": "Company",
1830 "model_name": "WAP", "model_number": "123",
1831 "serial_number": "12345", "device_type": "6-0050F204-1",
1832 "os_version": "01020300",
1833 "config_methods": "label push_button",
1834 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
1835 hapd = hostapd.add_ap(apdev[0], params)
1836 dev[0].flush_scan_cache()
1837 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1838 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1839 id = int(dev[0].list_networks()[0]['id'])
1840 dev[0].set_network(id, "scan_freq", "2412")
1841
1842 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_subscribe"):
1843 dev[0].request("WPS_ER_START ifname=lo")
1844 for i in range(50):
1845 res = dev[0].request("GET_ALLOC_FAIL")
1846 if res.startswith("0:"):
1847 break
1848 time.sleep(0.1)
1849 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=0)
1850 if ev:
1851 raise Exception("Unexpected AP discovery during OOM")
1852
1853 dev[0].request("WPS_ER_STOP")
1854
1855 def test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1856 """WPS ER SetSelectedRegistrar OOM"""
1857 try:
1858 _test_ap_wps_er_set_sel_reg_oom(dev, apdev)
1859 finally:
1860 dev[0].request("WPS_ER_STOP")
1861
1862 def _test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1863 ssid = "wps-er-add-enrollee"
1864 ap_pin = "12345670"
1865 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1866 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1867 "wpa_passphrase": "12345678", "wpa": "2",
1868 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1869 "device_name": "Wireless AP", "manufacturer": "Company",
1870 "model_name": "WAP", "model_number": "123",
1871 "serial_number": "12345", "device_type": "6-0050F204-1",
1872 "os_version": "01020300",
1873 "config_methods": "label push_button",
1874 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
1875 hapd = hostapd.add_ap(apdev[0], params)
1876 dev[0].flush_scan_cache()
1877 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1878 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1879
1880 dev[0].request("WPS_ER_START ifname=lo")
1881 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1882 if ev is None:
1883 raise Exception("AP not discovered")
1884
1885 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1886 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1887 if ev is None:
1888 raise Exception("AP learn timed out")
1889 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1890 if ev is None:
1891 raise Exception("WPS-FAIL timed out")
1892 time.sleep(0.1)
1893
1894 for func in ["http_client_url_parse;wps_er_send_set_sel_reg",
1895 "wps_er_soap_hdr;wps_er_send_set_sel_reg",
1896 "http_client_addr;wps_er_send_set_sel_reg",
1897 "wpabuf_alloc;wps_er_set_sel_reg"]:
1898 with alloc_fail(dev[0], 1, func):
1899 if "OK" not in dev[0].request("WPS_ER_PBC " + ap_uuid):
1900 raise Exception("WPS_ER_PBC failed")
1901 ev = dev[0].wait_event(["WPS-PBC-ACTIVE"], timeout=3)
1902 if ev is None:
1903 raise Exception("WPS-PBC-ACTIVE not seen")
1904
1905 dev[0].request("WPS_ER_STOP")
1906
1907 @remote_compatible
1908 def test_ap_wps_er_learn_oom(dev, apdev):
1909 """WPS ER learn OOM"""
1910 try:
1911 _test_ap_wps_er_learn_oom(dev, apdev)
1912 finally:
1913 dev[0].request("WPS_ER_STOP")
1914
1915 def _test_ap_wps_er_learn_oom(dev, apdev):
1916 ssid = "wps-er-add-enrollee"
1917 ap_pin = "12345670"
1918 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1919 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1920 "wpa_passphrase": "12345678", "wpa": "2",
1921 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1922 "device_name": "Wireless AP", "manufacturer": "Company",
1923 "model_name": "WAP", "model_number": "123",
1924 "serial_number": "12345", "device_type": "6-0050F204-1",
1925 "os_version": "01020300",
1926 "config_methods": "label push_button",
1927 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
1928 hapd = hostapd.add_ap(apdev[0], params)
1929 dev[0].flush_scan_cache()
1930 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1931 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1932
1933 dev[0].request("WPS_ER_START ifname=lo")
1934 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1935 if ev is None:
1936 raise Exception("AP not discovered")
1937
1938 for func in ["wps_er_http_put_message_cb",
1939 "xml_get_base64_item;wps_er_http_put_message_cb",
1940 "http_client_url_parse;wps_er_ap_put_message",
1941 "wps_er_soap_hdr;wps_er_ap_put_message",
1942 "http_client_addr;wps_er_ap_put_message"]:
1943 with alloc_fail(dev[0], 1, func):
1944 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1945 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=1)
1946 if ev is not None:
1947 raise Exception("AP learn succeeded during OOM")
1948
1949 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1950 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=10)
1951 if ev is None:
1952 raise Exception("AP learn did not succeed")
1953
1954 if "FAIL" not in dev[0].request("WPS_ER_LEARN 00000000-9e5c-4e73-bd82-f89cbcd10d7e " + ap_pin):
1955 raise Exception("WPS_ER_LEARN for unknown AP accepted")
1956
1957 dev[0].request("WPS_ER_STOP")
1958
1959 def test_ap_wps_fragmentation(dev, apdev):
1960 """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
1961 ssid = "test-wps-fragmentation"
1962 appin = "12345670"
1963 hapd = hostapd.add_ap(apdev[0],
1964 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1965 "wpa_passphrase": "12345678", "wpa": "3",
1966 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1967 "wpa_pairwise": "TKIP", "ap_pin": appin,
1968 "fragment_size": "50"})
1969 logger.info("WPS provisioning step (PBC)")
1970 hapd.request("WPS_PBC")
1971 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1972 dev[0].dump_monitor()
1973 dev[0].request("SET wps_fragment_size 50")
1974 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1975 dev[0].wait_connected(timeout=30)
1976 status = dev[0].get_status()
1977 if status['wpa_state'] != 'COMPLETED':
1978 raise Exception("Not fully connected")
1979 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1980 raise Exception("Unexpected encryption configuration")
1981 if status['key_mgmt'] != 'WPA2-PSK':
1982 raise Exception("Unexpected key_mgmt")
1983
1984 logger.info("WPS provisioning step (PIN)")
1985 pin = dev[1].wps_read_pin()
1986 hapd.request("WPS_PIN any " + pin)
1987 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1988 dev[1].request("SET wps_fragment_size 50")
1989 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1990 dev[1].wait_connected(timeout=30)
1991 status = dev[1].get_status()
1992 if status['wpa_state'] != 'COMPLETED':
1993 raise Exception("Not fully connected")
1994 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1995 raise Exception("Unexpected encryption configuration")
1996 if status['key_mgmt'] != 'WPA2-PSK':
1997 raise Exception("Unexpected key_mgmt")
1998
1999 logger.info("WPS connection as registrar")
2000 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2001 dev[2].request("SET wps_fragment_size 50")
2002 dev[2].wps_reg(apdev[0]['bssid'], appin)
2003 status = dev[2].get_status()
2004 if status['wpa_state'] != 'COMPLETED':
2005 raise Exception("Not fully connected")
2006 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
2007 raise Exception("Unexpected encryption configuration")
2008 if status['key_mgmt'] != 'WPA2-PSK':
2009 raise Exception("Unexpected key_mgmt")
2010
2011 @remote_compatible
2012 def test_ap_wps_new_version_sta(dev, apdev):
2013 """WPS compatibility with new version number on the station"""
2014 ssid = "test-wps-ver"
2015 hapd = hostapd.add_ap(apdev[0],
2016 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2017 "wpa_passphrase": "12345678", "wpa": "2",
2018 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2019 logger.info("WPS provisioning step")
2020 hapd.request("WPS_PBC")
2021 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2022 dev[0].dump_monitor()
2023 dev[0].request("SET wps_version_number 0x43")
2024 dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
2025 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2026 dev[0].wait_connected(timeout=30)
2027
2028 @remote_compatible
2029 def test_ap_wps_new_version_ap(dev, apdev):
2030 """WPS compatibility with new version number on the AP"""
2031 ssid = "test-wps-ver"
2032 hapd = hostapd.add_ap(apdev[0],
2033 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2034 "wpa_passphrase": "12345678", "wpa": "2",
2035 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2036 logger.info("WPS provisioning step")
2037 if "FAIL" in hapd.request("SET wps_version_number 0x43"):
2038 raise Exception("Failed to enable test functionality")
2039 hapd.request("WPS_PBC")
2040 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2041 dev[0].dump_monitor()
2042 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2043 dev[0].wait_connected(timeout=30)
2044 hapd.request("SET wps_version_number 0x20")
2045
2046 @remote_compatible
2047 def test_ap_wps_check_pin(dev, apdev):
2048 """Verify PIN checking through control interface"""
2049 hapd = hostapd.add_ap(apdev[0],
2050 {"ssid": "wps", "eap_server": "1", "wps_state": "2",
2051 "wpa_passphrase": "12345678", "wpa": "2",
2052 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2053 for t in [("12345670", "12345670"),
2054 ("12345678", "FAIL-CHECKSUM"),
2055 ("12345", "FAIL"),
2056 ("123456789", "FAIL"),
2057 ("1234-5670", "12345670"),
2058 ("1234 5670", "12345670"),
2059 ("1-2.3:4 5670", "12345670")]:
2060 res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
2061 res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
2062 if res != res2:
2063 raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
2064 if res != t[1]:
2065 raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
2066
2067 if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
2068 raise Exception("Unexpected WPS_CHECK_PIN success")
2069 if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
2070 raise Exception("Unexpected WPS_CHECK_PIN success")
2071
2072 for i in range(0, 10):
2073 pin = dev[0].request("WPS_PIN get")
2074 rpin = dev[0].request("WPS_CHECK_PIN " + pin).rstrip('\n')
2075 if pin != rpin:
2076 raise Exception("Random PIN validation failed for " + pin)
2077
2078 def test_ap_wps_pin_get_failure(dev, apdev):
2079 """PIN generation failure"""
2080 with fail_test(dev[0], 1,
2081 "os_get_random;wpa_supplicant_ctrl_iface_wps_pin"):
2082 if "FAIL" not in dev[0].request("WPS_PIN get"):
2083 raise Exception("WPS_PIN did not report failure")
2084
2085 def test_ap_wps_wep_config(dev, apdev):
2086 """WPS 2.0 AP rejecting WEP configuration"""
2087 ssid = "test-wps-config"
2088 appin = "12345670"
2089 hapd = hostapd.add_ap(apdev[0],
2090 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2091 "ap_pin": appin})
2092 dev[0].flush_scan_cache()
2093 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2094 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
2095 "hello", no_wait=True)
2096 ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
2097 if ev is None:
2098 raise Exception("WPS-FAIL timed out")
2099 if "reason=2" not in ev:
2100 raise Exception("Unexpected reason code in WPS-FAIL")
2101 status = hapd.request("WPS_GET_STATUS")
2102 if "Last WPS result: Failed" not in status:
2103 raise Exception("WPS failure result not shown correctly")
2104 if "Failure Reason: WEP Prohibited" not in status:
2105 raise Exception("Failure reason not reported correctly")
2106 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
2107 raise Exception("Peer address not shown correctly")
2108
2109 def test_ap_wps_wep_enroll(dev, apdev):
2110 """WPS 2.0 STA rejecting WEP configuration"""
2111 ssid = "test-wps-wep"
2112 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2113 "skip_cred_build": "1", "extra_cred": "wps-wep-cred"}
2114 hapd = hostapd.add_ap(apdev[0], params)
2115 hapd.request("WPS_PBC")
2116 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2117 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2118 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
2119 if ev is None:
2120 raise Exception("WPS-FAIL event timed out")
2121 if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
2122 raise Exception("Unexpected WPS-FAIL event: " + ev)
2123
2124 @remote_compatible
2125 def test_ap_wps_ie_fragmentation(dev, apdev):
2126 """WPS AP using fragmented WPS IE"""
2127 ssid = "test-wps-ie-fragmentation"
2128 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2129 "wpa_passphrase": "12345678", "wpa": "2",
2130 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2131 "device_name": "1234567890abcdef1234567890abcdef",
2132 "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
2133 "model_name": "1234567890abcdef1234567890abcdef",
2134 "model_number": "1234567890abcdef1234567890abcdef",
2135 "serial_number": "1234567890abcdef1234567890abcdef"}
2136 hapd = hostapd.add_ap(apdev[0], params)
2137 hapd.request("WPS_PBC")
2138 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2139 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2140 dev[0].wait_connected(timeout=30)
2141 bss = dev[0].get_bss(apdev[0]['bssid'])
2142 if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
2143 logger.info("Device Name not received correctly")
2144 logger.info(bss)
2145 # This can fail if Probe Response frame is missed and Beacon frame was
2146 # used to fill in the BSS entry. This can happen, e.g., during heavy
2147 # load every now and then and is not really an error, so try to
2148 # workaround by runnign another scan.
2149 dev[0].scan(freq="2412", only_new=True)
2150 bss = dev[0].get_bss(apdev[0]['bssid'])
2151 if not bss or "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
2152 logger.info(bss)
2153 raise Exception("Device Name not received correctly")
2154 if len(re.findall("dd..0050f204", bss['ie'])) != 2:
2155 raise Exception("Unexpected number of WPS IEs")
2156
2157 def get_psk(pskfile):
2158 psks = {}
2159 with open(pskfile, "r") as f:
2160 lines = f.read().splitlines()
2161 for l in lines:
2162 if l == "# WPA PSKs":
2163 continue
2164 vals = l.split(' ')
2165 if len(vals) != 3 or vals[0] != "wps=1":
2166 continue
2167 addr = vals[1]
2168 psk = vals[2]
2169 psks[addr] = psk
2170 return psks
2171
2172 def test_ap_wps_per_station_psk(dev, apdev):
2173 """WPS PBC provisioning with per-station PSK"""
2174 addr0 = dev[0].own_addr()
2175 addr1 = dev[1].own_addr()
2176 addr2 = dev[2].own_addr()
2177 ssid = "wps"
2178 appin = "12345670"
2179 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2180 try:
2181 os.remove(pskfile)
2182 except:
2183 pass
2184
2185 hapd = None
2186 try:
2187 with open(pskfile, "w") as f:
2188 f.write("# WPA PSKs\n")
2189
2190 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2191 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2192 "rsn_pairwise": "CCMP", "ap_pin": appin,
2193 "wpa_psk_file": pskfile}
2194 hapd = hostapd.add_ap(apdev[0], params)
2195
2196 logger.info("First enrollee")
2197 hapd.request("WPS_PBC")
2198 dev[0].flush_scan_cache()
2199 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2200 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2201 dev[0].wait_connected(timeout=30)
2202
2203 logger.info("Second enrollee")
2204 hapd.request("WPS_PBC")
2205 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2206 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
2207 dev[1].wait_connected(timeout=30)
2208
2209 logger.info("External registrar")
2210 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2211 dev[2].wps_reg(apdev[0]['bssid'], appin)
2212
2213 logger.info("Verifying PSK results")
2214 psks = get_psk(pskfile)
2215 if addr0 not in psks:
2216 raise Exception("No PSK recorded for sta0")
2217 if addr1 not in psks:
2218 raise Exception("No PSK recorded for sta1")
2219 if addr2 not in psks:
2220 raise Exception("No PSK recorded for sta2")
2221 if psks[addr0] == psks[addr1]:
2222 raise Exception("Same PSK recorded for sta0 and sta1")
2223 if psks[addr0] == psks[addr2]:
2224 raise Exception("Same PSK recorded for sta0 and sta2")
2225 if psks[addr1] == psks[addr2]:
2226 raise Exception("Same PSK recorded for sta1 and sta2")
2227
2228 dev[0].request("REMOVE_NETWORK all")
2229 logger.info("Second external registrar")
2230 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2231 dev[0].wps_reg(apdev[0]['bssid'], appin)
2232 psks2 = get_psk(pskfile)
2233 if addr0 not in psks2:
2234 raise Exception("No PSK recorded for sta0(reg)")
2235 if psks[addr0] == psks2[addr0]:
2236 raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
2237 finally:
2238 os.remove(pskfile)
2239 if hapd:
2240 dev[0].request("DISCONNECT")
2241 dev[1].request("DISCONNECT")
2242 dev[2].request("DISCONNECT")
2243 hapd.disable()
2244 dev[0].flush_scan_cache()
2245 dev[1].flush_scan_cache()
2246 dev[2].flush_scan_cache()
2247
2248 def test_ap_wps_per_station_psk_preset(dev, apdev):
2249 """WPS PIN provisioning with per-station PSK preset"""
2250 addr0 = dev[0].own_addr()
2251 addr1 = dev[1].own_addr()
2252 addr2 = dev[2].own_addr()
2253 ssid = "wps"
2254 appin = "12345670"
2255 pskfile = "/tmp/ap_wps_per_enrollee_psk_preset.psk_file"
2256 try:
2257 os.remove(pskfile)
2258 except:
2259 pass
2260
2261 hapd = None
2262 try:
2263 with open(pskfile, "w") as f:
2264 f.write("# WPA PSKs\n")
2265 f.write("wps=1 " + addr0 + " preset-passphrase-0\n")
2266 f.write("wps=1 " + addr2 + " preset-passphrase-2\n")
2267
2268 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2269 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2270 "rsn_pairwise": "CCMP", "ap_pin": appin,
2271 "wpa_psk_file": pskfile}
2272 hapd = hostapd.add_ap(apdev[0], params)
2273 bssid = hapd.own_addr()
2274
2275 logger.info("First enrollee")
2276 pin = dev[0].wps_read_pin()
2277 hapd.request("WPS_PIN any " + pin)
2278 dev[0].scan_for_bss(bssid, freq=2412)
2279 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
2280 dev[0].wait_connected(timeout=30)
2281
2282 logger.info("Second enrollee")
2283 pin = dev[1].wps_read_pin()
2284 hapd.request("WPS_PIN any " + pin)
2285 dev[1].scan_for_bss(bssid, freq=2412)
2286 dev[1].request("WPS_PIN %s %s" % (bssid, pin))
2287 dev[1].wait_connected(timeout=30)
2288
2289 logger.info("External registrar")
2290 dev[2].scan_for_bss(bssid, freq=2412)
2291 dev[2].wps_reg(bssid, appin)
2292
2293 logger.info("Verifying PSK results")
2294 psks = get_psk(pskfile)
2295 if addr0 not in psks:
2296 raise Exception("No PSK recorded for sta0")
2297 if addr1 not in psks:
2298 raise Exception("No PSK recorded for sta1")
2299 if addr2 not in psks:
2300 raise Exception("No PSK recorded for sta2")
2301 logger.info("PSK[0]: " + psks[addr0])
2302 logger.info("PSK[1]: " + psks[addr1])
2303 logger.info("PSK[2]: " + psks[addr2])
2304 if psks[addr0] == psks[addr1]:
2305 raise Exception("Same PSK recorded for sta0 and sta1")
2306 if psks[addr0] == psks[addr2]:
2307 raise Exception("Same PSK recorded for sta0 and sta2")
2308 if psks[addr1] == psks[addr2]:
2309 raise Exception("Same PSK recorded for sta1 and sta2")
2310 pmk0 = hapd.request("GET_PMK " + addr0)
2311 pmk1 = hapd.request("GET_PMK " + addr1)
2312 pmk2 = hapd.request("GET_PMK " + addr2)
2313 logger.info("PMK[0]: " + pmk0)
2314 logger.info("PMK[1]: " + pmk1)
2315 logger.info("PMK[2]: " + pmk2)
2316 if pmk0 != "565faec21ff04702d9d17c464e1301efd36c8a3ea46bb866b4bec7fed4384579":
2317 raise Exception("PSK[0] mismatch")
2318 if psks[addr1] != pmk1:
2319 raise Exception("PSK[1] mismatch")
2320 if psks[addr2] != pmk2:
2321 raise Exception("PSK[2] mismatch")
2322
2323 dev[0].request("REMOVE_NETWORK all")
2324 dev[0].wait_disconnected()
2325 dev[0].dump_monitor()
2326 logger.info("First enrollee again")
2327 pin = dev[0].wps_read_pin()
2328 hapd.request("WPS_PIN any " + pin)
2329 dev[0].scan_for_bss(bssid, freq=2412)
2330 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
2331 dev[0].wait_connected(timeout=30)
2332 psks2 = get_psk(pskfile)
2333 if addr0 not in psks2:
2334 raise Exception("No PSK recorded for sta0 (2)")
2335 if psks[addr0] != psks2[addr0]:
2336 raise Exception("Different PSK recorded for sta0(enrollee) and sta0(enrollee 2)")
2337 finally:
2338 os.remove(pskfile)
2339
2340 def test_ap_wps_per_station_psk_failure(dev, apdev):
2341 """WPS PBC provisioning with per-station PSK (file not writable)"""
2342 addr0 = dev[0].p2p_dev_addr()
2343 addr1 = dev[1].p2p_dev_addr()
2344 addr2 = dev[2].p2p_dev_addr()
2345 ssid = "wps"
2346 appin = "12345670"
2347 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2348 try:
2349 os.remove(pskfile)
2350 except:
2351 pass
2352
2353 hapd = None
2354 try:
2355 with open(pskfile, "w") as f:
2356 f.write("# WPA PSKs\n")
2357
2358 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2359 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2360 "rsn_pairwise": "CCMP", "ap_pin": appin,
2361 "wpa_psk_file": pskfile}
2362 hapd = hostapd.add_ap(apdev[0], params)
2363 if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
2364 raise Exception("Failed to set wpa_psk_file")
2365
2366 logger.info("First enrollee")
2367 hapd.request("WPS_PBC")
2368 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2369 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2370 dev[0].wait_connected(timeout=30)
2371
2372 logger.info("Second enrollee")
2373 hapd.request("WPS_PBC")
2374 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2375 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
2376 dev[1].wait_connected(timeout=30)
2377
2378 logger.info("External registrar")
2379 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2380 dev[2].wps_reg(apdev[0]['bssid'], appin)
2381
2382 logger.info("Verifying PSK results")
2383 psks = get_psk(pskfile)
2384 if len(psks) > 0:
2385 raise Exception("PSK recorded unexpectedly")
2386 finally:
2387 if hapd:
2388 for i in range(3):
2389 dev[i].request("DISCONNECT")
2390 hapd.disable()
2391 for i in range(3):
2392 dev[i].flush_scan_cache()
2393 os.remove(pskfile)
2394
2395 def test_ap_wps_pin_request_file(dev, apdev):
2396 """WPS PIN provisioning with configured AP"""
2397 ssid = "wps"
2398 pinfile = "/tmp/ap_wps_pin_request_file.log"
2399 if os.path.exists(pinfile):
2400 os.remove(pinfile)
2401 hapd = hostapd.add_ap(apdev[0],
2402 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2403 "wps_pin_requests": pinfile,
2404 "wpa_passphrase": "12345678", "wpa": "2",
2405 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2406 uuid = dev[0].get_status_field("uuid")
2407 pin = dev[0].wps_read_pin()
2408 try:
2409 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2410 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
2411 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
2412 if ev is None:
2413 raise Exception("PIN needed event not shown")
2414 if uuid not in ev:
2415 raise Exception("UUID mismatch")
2416 dev[0].request("WPS_CANCEL")
2417 success = False
2418 with open(pinfile, "r") as f:
2419 lines = f.readlines()
2420 for l in lines:
2421 if uuid in l:
2422 success = True
2423 break
2424 if not success:
2425 raise Exception("PIN request entry not in the log file")
2426 finally:
2427 try:
2428 os.remove(pinfile)
2429 except:
2430 pass
2431
2432 def test_ap_wps_auto_setup_with_config_file(dev, apdev):
2433 """WPS auto-setup with configuration file"""
2434 conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
2435 ifname = apdev[0]['ifname']
2436 try:
2437 with open(conffile, "w") as f:
2438 f.write("driver=nl80211\n")
2439 f.write("hw_mode=g\n")
2440 f.write("channel=1\n")
2441 f.write("ieee80211n=1\n")
2442 f.write("interface=%s\n" % ifname)
2443 f.write("ctrl_interface=/var/run/hostapd\n")
2444 f.write("ssid=wps\n")
2445 f.write("eap_server=1\n")
2446 f.write("wps_state=1\n")
2447 hapd = hostapd.add_bss(apdev[0], ifname, conffile)
2448 hapd.request("WPS_PBC")
2449 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2450 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2451 dev[0].wait_connected(timeout=30)
2452 with open(conffile, "r") as f:
2453 lines = f.read().splitlines()
2454 vals = dict()
2455 for l in lines:
2456 try:
2457 [name, value] = l.split('=', 1)
2458 vals[name] = value
2459 except ValueError as e:
2460 if "# WPS configuration" in l:
2461 pass
2462 else:
2463 raise Exception("Unexpected configuration line: " + l)
2464 if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
2465 raise Exception("Incorrect configuration: " + str(vals))
2466 finally:
2467 try:
2468 os.remove(conffile)
2469 except:
2470 pass
2471
2472 def test_ap_wps_pbc_timeout(dev, apdev, params):
2473 """wpa_supplicant PBC walk time and WPS ER SelReg timeout [long]"""
2474 if not params['long']:
2475 raise HwsimSkip("Skip test case with long duration due to --long not specified")
2476 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2477 hapd = add_ssdp_ap(apdev[0], ap_uuid)
2478
2479 location = ssdp_get_location(ap_uuid)
2480 urls = upnp_get_urls(location)
2481 eventurl = urlparse(urls['event_sub_url'])
2482 ctrlurl = urlparse(urls['control_url'])
2483
2484 url = urlparse(location)
2485 conn = HTTPConnection(url.netloc)
2486
2487 class WPSERHTTPServer(StreamRequestHandler):
2488 def handle(self):
2489 data = self.rfile.readline().strip()
2490 logger.debug(data)
2491 self.wfile.write(gen_wps_event())
2492
2493 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
2494 server.timeout = 1
2495
2496 headers = {"callback": '<http://127.0.0.1:12345/event>',
2497 "NT": "upnp:event",
2498 "timeout": "Second-1234"}
2499 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2500 resp = conn.getresponse()
2501 if resp.status != 200:
2502 raise Exception("Unexpected HTTP response: %d" % resp.status)
2503 sid = resp.getheader("sid")
2504 logger.debug("Subscription SID " + sid)
2505
2506 msg = '''<?xml version="1.0"?>
2507 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
2508 <s:Body>
2509 <u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
2510 <NewMessage>EEoAARAQQQABARASAAIAABBTAAIxSBBJAA4ANyoAASABBv///////xBIABA2LbR7pTpRkYj7
2511 VFi5hrLk
2512 </NewMessage>
2513 </u:SetSelectedRegistrar>
2514 </s:Body>
2515 </s:Envelope>'''
2516 headers = {"Content-type": 'text/xml; charset="utf-8"'}
2517 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
2518 conn.request("POST", ctrlurl.path, msg, headers)
2519 resp = conn.getresponse()
2520 if resp.status != 200:
2521 raise Exception("Unexpected HTTP response: %d" % resp.status)
2522
2523 server.handle_request()
2524
2525 logger.info("Start WPS_PBC and wait for PBC walk time expiration")
2526 if "OK" not in dev[0].request("WPS_PBC"):
2527 raise Exception("WPS_PBC failed")
2528
2529 start = os.times()[4]
2530
2531 server.handle_request()
2532 dev[1].request("BSS_FLUSH 0")
2533 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2534 only_new=True)
2535 bss = dev[1].get_bss(apdev[0]['bssid'])
2536 logger.debug("BSS: " + str(bss))
2537 if '[WPS-AUTH]' not in bss['flags']:
2538 raise Exception("WPS not indicated authorized")
2539
2540 server.handle_request()
2541
2542 wps_timeout_seen = False
2543
2544 while True:
2545 hapd.dump_monitor()
2546 dev[1].dump_monitor()
2547 if not wps_timeout_seen:
2548 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=0)
2549 if ev is not None:
2550 logger.info("PBC timeout seen")
2551 wps_timeout_seen = True
2552 else:
2553 dev[0].dump_monitor()
2554 now = os.times()[4]
2555 if now - start > 130:
2556 raise Exception("Selected registration information not removed")
2557 dev[1].request("BSS_FLUSH 0")
2558 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2559 only_new=True)
2560 bss = dev[1].get_bss(apdev[0]['bssid'])
2561 logger.debug("BSS: " + str(bss))
2562 if '[WPS-AUTH]' not in bss['flags']:
2563 break
2564 server.handle_request()
2565
2566 server.server_close()
2567
2568 if wps_timeout_seen:
2569 return
2570
2571 now = os.times()[4]
2572 if now < start + 150:
2573 dur = start + 150 - now
2574 else:
2575 dur = 1
2576 logger.info("Continue waiting for PBC timeout (%d sec)" % dur)
2577 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=dur)
2578 if ev is None:
2579 raise Exception("WPS-TIMEOUT not reported")
2580
2581 def add_ssdp_ap(ap, ap_uuid):
2582 ssid = "wps-ssdp"
2583 ap_pin = "12345670"
2584 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2585 "wpa_passphrase": "12345678", "wpa": "2",
2586 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2587 "device_name": "Wireless AP", "manufacturer": "Company",
2588 "model_name": "WAP", "model_number": "123",
2589 "serial_number": "12345", "device_type": "6-0050F204-1",
2590 "os_version": "01020300",
2591 "config_methods": "label push_button",
2592 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
2593 "friendly_name": "WPS Access Point",
2594 "manufacturer_url": "http://www.example.com/",
2595 "model_description": "Wireless Access Point",
2596 "model_url": "http://www.example.com/model/",
2597 "upc": "123456789012"}
2598 return hostapd.add_ap(ap, params)
2599
2600 def ssdp_send(msg, no_recv=False):
2601 socket.setdefaulttimeout(1)
2602 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2603 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2604 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2605 sock.bind(("127.0.0.1", 0))
2606 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2607 if no_recv:
2608 return None
2609 return sock.recv(1000).decode()
2610
2611 def ssdp_send_msearch(st, no_recv=False):
2612 msg = '\r\n'.join([
2613 'M-SEARCH * HTTP/1.1',
2614 'HOST: 239.255.255.250:1900',
2615 'MX: 1',
2616 'MAN: "ssdp:discover"',
2617 'ST: ' + st,
2618 '', ''])
2619 return ssdp_send(msg, no_recv=no_recv)
2620
2621 def test_ap_wps_ssdp_msearch(dev, apdev):
2622 """WPS AP and SSDP M-SEARCH messages"""
2623 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2624 add_ssdp_ap(apdev[0], ap_uuid)
2625
2626 msg = '\r\n'.join([
2627 'M-SEARCH * HTTP/1.1',
2628 'Host: 239.255.255.250:1900',
2629 'Mx: 1',
2630 'Man: "ssdp:discover"',
2631 'St: urn:schemas-wifialliance-org:device:WFADevice:1',
2632 '', ''])
2633 ssdp_send(msg)
2634
2635 msg = '\r\n'.join([
2636 'M-SEARCH * HTTP/1.1',
2637 'host:\t239.255.255.250:1900\t\t\t\t \t\t',
2638 'mx: \t1\t\t ',
2639 'man: \t \t "ssdp:discover" ',
2640 'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
2641 '', ''])
2642 ssdp_send(msg)
2643
2644 ssdp_send_msearch("ssdp:all")
2645 ssdp_send_msearch("upnp:rootdevice")
2646 ssdp_send_msearch("uuid:" + ap_uuid)
2647 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
2648 ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1")
2649
2650 msg = '\r\n'.join([
2651 'M-SEARCH * HTTP/1.1',
2652 'HOST:\t239.255.255.250:1900',
2653 'MAN: "ssdp:discover"',
2654 'MX: 130',
2655 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2656 '', ''])
2657 ssdp_send(msg, no_recv=True)
2658
2659 def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
2660 """WPS AP and invalid SSDP M-SEARCH messages"""
2661 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2662 add_ssdp_ap(apdev[0], ap_uuid)
2663
2664 socket.setdefaulttimeout(1)
2665 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2666 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2667 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2668 sock.bind(("127.0.0.1", 0))
2669
2670 logger.debug("Missing MX")
2671 msg = '\r\n'.join([
2672 'M-SEARCH * HTTP/1.1',
2673 'HOST: 239.255.255.250:1900',
2674 'MAN: "ssdp:discover"',
2675 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2676 '', ''])
2677 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2678
2679 logger.debug("Negative MX")
2680 msg = '\r\n'.join([
2681 'M-SEARCH * HTTP/1.1',
2682 'HOST: 239.255.255.250:1900',
2683 'MX: -1',
2684 'MAN: "ssdp:discover"',
2685 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2686 '', ''])
2687 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2688
2689 logger.debug("Invalid MX")
2690 msg = '\r\n'.join([
2691 'M-SEARCH * HTTP/1.1',
2692 'HOST: 239.255.255.250:1900',
2693 'MX; 1',
2694 'MAN: "ssdp:discover"',
2695 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2696 '', ''])
2697 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2698
2699 logger.debug("Missing MAN")
2700 msg = '\r\n'.join([
2701 'M-SEARCH * HTTP/1.1',
2702 'HOST: 239.255.255.250:1900',
2703 'MX: 1',
2704 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2705 '', ''])
2706 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2707
2708 logger.debug("Invalid MAN")
2709 msg = '\r\n'.join([
2710 'M-SEARCH * HTTP/1.1',
2711 'HOST: 239.255.255.250:1900',
2712 'MX: 1',
2713 'MAN: foo',
2714 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2715 '', ''])
2716 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2717 msg = '\r\n'.join([
2718 'M-SEARCH * HTTP/1.1',
2719 'HOST: 239.255.255.250:1900',
2720 'MX: 1',
2721 'MAN; "ssdp:discover"',
2722 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2723 '', ''])
2724 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2725
2726 logger.debug("Missing HOST")
2727 msg = '\r\n'.join([
2728 'M-SEARCH * HTTP/1.1',
2729 'MAN: "ssdp:discover"',
2730 'MX: 1',
2731 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2732 '', ''])
2733 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2734
2735 logger.debug("Missing ST")
2736 msg = '\r\n'.join([
2737 'M-SEARCH * HTTP/1.1',
2738 'HOST: 239.255.255.250:1900',
2739 'MAN: "ssdp:discover"',
2740 'MX: 1',
2741 '', ''])
2742 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2743
2744 logger.debug("Mismatching ST")
2745 msg = '\r\n'.join([
2746 'M-SEARCH * HTTP/1.1',
2747 'HOST: 239.255.255.250:1900',
2748 'MAN: "ssdp:discover"',
2749 'MX: 1',
2750 'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
2751 '', ''])
2752 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2753 msg = '\r\n'.join([
2754 'M-SEARCH * HTTP/1.1',
2755 'HOST: 239.255.255.250:1900',
2756 'MAN: "ssdp:discover"',
2757 'MX: 1',
2758 'ST: foo:bar',
2759 '', ''])
2760 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2761 msg = '\r\n'.join([
2762 'M-SEARCH * HTTP/1.1',
2763 'HOST: 239.255.255.250:1900',
2764 'MAN: "ssdp:discover"',
2765 'MX: 1',
2766 'ST: foobar',
2767 '', ''])
2768 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2769
2770 logger.debug("Invalid ST")
2771 msg = '\r\n'.join([
2772 'M-SEARCH * HTTP/1.1',
2773 'HOST: 239.255.255.250:1900',
2774 'MAN: "ssdp:discover"',
2775 'MX: 1',
2776 'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
2777 '', ''])
2778 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2779
2780 logger.debug("Invalid M-SEARCH")
2781 msg = '\r\n'.join([
2782 'M+SEARCH * HTTP/1.1',
2783 'HOST: 239.255.255.250:1900',
2784 'MAN: "ssdp:discover"',
2785 'MX: 1',
2786 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2787 '', ''])
2788 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2789 msg = '\r\n'.join([
2790 'M-SEARCH-* HTTP/1.1',
2791 'HOST: 239.255.255.250:1900',
2792 'MAN: "ssdp:discover"',
2793 'MX: 1',
2794 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2795 '', ''])
2796 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2797
2798 logger.debug("Invalid message format")
2799 sock.sendto(b"NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
2800 msg = '\r'.join([
2801 'M-SEARCH * HTTP/1.1',
2802 'HOST: 239.255.255.250:1900',
2803 'MAN: "ssdp:discover"',
2804 'MX: 1',
2805 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2806 '', ''])
2807 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2808
2809 try:
2810 r = sock.recv(1000)
2811 raise Exception("Unexpected M-SEARCH response: " + r)
2812 except socket.timeout:
2813 pass
2814
2815 logger.debug("Valid M-SEARCH")
2816 msg = '\r\n'.join([
2817 'M-SEARCH * HTTP/1.1',
2818 'HOST: 239.255.255.250:1900',
2819 'MAN: "ssdp:discover"',
2820 'MX: 1',
2821 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2822 '', ''])
2823 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2824
2825 try:
2826 r = sock.recv(1000)
2827 pass
2828 except socket.timeout:
2829 raise Exception("No SSDP response")
2830
2831 def test_ap_wps_ssdp_burst(dev, apdev):
2832 """WPS AP and SSDP burst"""
2833 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2834 add_ssdp_ap(apdev[0], ap_uuid)
2835
2836 msg = '\r\n'.join([
2837 'M-SEARCH * HTTP/1.1',
2838 'HOST: 239.255.255.250:1900',
2839 'MAN: "ssdp:discover"',
2840 'MX: 1',
2841 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2842 '', ''])
2843 socket.setdefaulttimeout(1)
2844 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2845 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2846 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2847 sock.bind(("127.0.0.1", 0))
2848 for i in range(0, 25):
2849 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2850 resp = 0
2851 while True:
2852 try:
2853 r = sock.recv(1000).decode()
2854 if not r.startswith("HTTP/1.1 200 OK\r\n"):
2855 raise Exception("Unexpected message: " + r)
2856 resp += 1
2857 except socket.timeout:
2858 break
2859 if resp < 20:
2860 raise Exception("Too few SSDP responses")
2861
2862 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2863 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2864 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2865 sock.bind(("127.0.0.1", 0))
2866 for i in range(0, 25):
2867 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2868 while True:
2869 try:
2870 r = sock.recv(1000).decode()
2871 if ap_uuid in r:
2872 break
2873 except socket.timeout:
2874 raise Exception("No SSDP response")
2875
2876 def ssdp_get_location(uuid):
2877 res = ssdp_send_msearch("uuid:" + uuid)
2878 location = None
2879 for l in res.splitlines():
2880 if l.lower().startswith("location:"):
2881 location = l.split(':', 1)[1].strip()
2882 break
2883 if location is None:
2884 raise Exception("No UPnP location found")
2885 return location
2886
2887 def upnp_get_urls(location):
2888 if sys.version_info[0] > 2:
2889 conn = urlopen(location)
2890 else:
2891 conn = urlopen(location, proxies={})
2892 tree = ET.parse(conn)
2893 root = tree.getroot()
2894 urn = '{urn:schemas-upnp-org:device-1-0}'
2895 service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
2896 res = {}
2897 res['scpd_url'] = urljoin(location, service.find(urn + 'SCPDURL').text)
2898 res['control_url'] = urljoin(location,
2899 service.find(urn + 'controlURL').text)
2900 res['event_sub_url'] = urljoin(location,
2901 service.find(urn + 'eventSubURL').text)
2902 return res
2903
2904 def upnp_soap_action(conn, path, action, include_soap_action=True,
2905 soap_action_override=None, newmsg=None, neweventtype=None,
2906 neweventmac=None):
2907 soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
2908 wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
2909 ET.register_namespace('soapenv', soapns)
2910 ET.register_namespace('wfa', wpsns)
2911 attrib = {}
2912 attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
2913 root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
2914 body = ET.SubElement(root, "{%s}Body" % soapns)
2915 act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
2916 if newmsg:
2917 msg = ET.SubElement(act, "NewMessage")
2918 msg.text = base64.b64encode(newmsg.encode()).decode()
2919 if neweventtype:
2920 msg = ET.SubElement(act, "NewWLANEventType")
2921 msg.text = neweventtype
2922 if neweventmac:
2923 msg = ET.SubElement(act, "NewWLANEventMAC")
2924 msg.text = neweventmac
2925
2926 headers = {"Content-type": 'text/xml; charset="utf-8"'}
2927 if include_soap_action:
2928 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
2929 elif soap_action_override:
2930 headers["SOAPAction"] = soap_action_override
2931 decl = b'<?xml version=\'1.0\' encoding=\'utf8\'?>\n'
2932 conn.request("POST", path, decl + ET.tostring(root), headers)
2933 return conn.getresponse()
2934
2935 def test_ap_wps_upnp(dev, apdev):
2936 """WPS AP and UPnP operations"""
2937 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2938 add_ssdp_ap(apdev[0], ap_uuid)
2939
2940 location = ssdp_get_location(ap_uuid)
2941 urls = upnp_get_urls(location)
2942
2943 if sys.version_info[0] > 2:
2944 conn = urlopen(urls['scpd_url'])
2945 else:
2946 conn = urlopen(urls['scpd_url'], proxies={})
2947 scpd = conn.read()
2948
2949 if sys.version_info[0] > 2:
2950 try:
2951 conn = urlopen(urljoin(location, "unknown.html"))
2952 raise Exception("Unexpected HTTP response to GET unknown URL")
2953 except HTTPError as e:
2954 if e.code != 404:
2955 raise Exception("Unexpected HTTP response to GET unknown URL")
2956 else:
2957 conn = urlopen(urljoin(location, "unknown.html"), proxies={})
2958 if conn.getcode() != 404:
2959 raise Exception("Unexpected HTTP response to GET unknown URL")
2960
2961 url = urlparse(location)
2962 conn = HTTPConnection(url.netloc)
2963 #conn.set_debuglevel(1)
2964 headers = {"Content-type": 'text/xml; charset="utf-8"',
2965 "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"'}
2966 conn.request("POST", "hello", "\r\n\r\n", headers)
2967 resp = conn.getresponse()
2968 if resp.status != 404:
2969 raise Exception("Unexpected HTTP response: %d" % resp.status)
2970
2971 conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
2972 resp = conn.getresponse()
2973 if resp.status != 501:
2974 raise Exception("Unexpected HTTP response: %d" % resp.status)
2975
2976 headers = {"Content-type": 'text/xml; charset="utf-8"',
2977 "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"'}
2978 ctrlurl = urlparse(urls['control_url'])
2979 conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
2980 resp = conn.getresponse()
2981 if resp.status != 401:
2982 raise Exception("Unexpected HTTP response: %d" % resp.status)
2983
2984 logger.debug("GetDeviceInfo without SOAPAction header")
2985 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2986 include_soap_action=False)
2987 if resp.status != 401:
2988 raise Exception("Unexpected HTTP response: %d" % resp.status)
2989
2990 logger.debug("GetDeviceInfo with invalid SOAPAction header")
2991 for act in ["foo",
2992 "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
2993 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
2994 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
2995 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2996 include_soap_action=False,
2997 soap_action_override=act)
2998 if resp.status != 401:
2999 raise Exception("Unexpected HTTP response: %d" % resp.status)
3000
3001 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
3002 if resp.status != 200:
3003 raise Exception("Unexpected HTTP response: %d" % resp.status)
3004 dev = resp.read().decode()
3005 if "NewDeviceInfo" not in dev:
3006 raise Exception("Unexpected GetDeviceInfo response")
3007
3008 logger.debug("PutMessage without required parameters")
3009 resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
3010 if resp.status != 600:
3011 raise Exception("Unexpected HTTP response: %d" % resp.status)
3012
3013 logger.debug("PutWLANResponse without required parameters")
3014 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
3015 if resp.status != 600:
3016 raise Exception("Unexpected HTTP response: %d" % resp.status)
3017
3018 logger.debug("SetSelectedRegistrar from unregistered ER")
3019 resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
3020 if resp.status != 501:
3021 raise Exception("Unexpected HTTP response: %d" % resp.status)
3022
3023 logger.debug("Unknown action")
3024 resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
3025 if resp.status != 401:
3026 raise Exception("Unexpected HTTP response: %d" % resp.status)
3027
3028 def test_ap_wps_upnp_subscribe(dev, apdev):
3029 """WPS AP and UPnP event subscription"""
3030 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3031 hapd = add_ssdp_ap(apdev[0], ap_uuid)
3032
3033 location = ssdp_get_location(ap_uuid)
3034 urls = upnp_get_urls(location)
3035 eventurl = urlparse(urls['event_sub_url'])
3036
3037 url = urlparse(location)
3038 conn = HTTPConnection(url.netloc)
3039 #conn.set_debuglevel(1)
3040 headers = {"callback": '<http://127.0.0.1:12345/event>',
3041 "timeout": "Second-1234"}
3042 conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
3043 resp = conn.getresponse()
3044 if resp.status != 412:
3045 raise Exception("Unexpected HTTP response: %d" % resp.status)
3046
3047 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3048 resp = conn.getresponse()
3049 if resp.status != 412:
3050 raise Exception("Unexpected HTTP response: %d" % resp.status)
3051
3052 headers = {"NT": "upnp:event",
3053 "timeout": "Second-1234"}
3054 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3055 resp = conn.getresponse()
3056 if resp.status != 412:
3057 raise Exception("Unexpected HTTP response: %d" % resp.status)
3058
3059 headers = {"callback": '<http://127.0.0.1:12345/event>',
3060 "NT": "upnp:foobar",
3061 "timeout": "Second-1234"}
3062 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3063 resp = conn.getresponse()
3064 if resp.status != 400:
3065 raise Exception("Unexpected HTTP response: %d" % resp.status)
3066
3067 logger.debug("Valid subscription")
3068 headers = {"callback": '<http://127.0.0.1:12345/event>',
3069 "NT": "upnp:event",
3070 "timeout": "Second-1234"}
3071 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3072 resp = conn.getresponse()
3073 if resp.status != 200:
3074 raise Exception("Unexpected HTTP response: %d" % resp.status)
3075 sid = resp.getheader("sid")
3076 logger.debug("Subscription SID " + sid)
3077
3078 logger.debug("Invalid re-subscription")
3079 headers = {"NT": "upnp:event",
3080 "sid": "123456734567854",
3081 "timeout": "Second-1234"}
3082 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3083 resp = conn.getresponse()
3084 if resp.status != 400:
3085 raise Exception("Unexpected HTTP response: %d" % resp.status)
3086
3087 logger.debug("Invalid re-subscription")
3088 headers = {"NT": "upnp:event",
3089 "sid": "uuid:123456734567854",
3090 "timeout": "Second-1234"}
3091 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3092 resp = conn.getresponse()
3093 if resp.status != 400:
3094 raise Exception("Unexpected HTTP response: %d" % resp.status)
3095
3096 logger.debug("Invalid re-subscription")
3097 headers = {"callback": '<http://127.0.0.1:12345/event>',
3098 "NT": "upnp:event",
3099 "sid": sid,
3100 "timeout": "Second-1234"}
3101 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3102 resp = conn.getresponse()
3103 if resp.status != 400:
3104 raise Exception("Unexpected HTTP response: %d" % resp.status)
3105
3106 logger.debug("SID mismatch in re-subscription")
3107 headers = {"NT": "upnp:event",
3108 "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
3109 "timeout": "Second-1234"}
3110 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3111 resp = conn.getresponse()
3112 if resp.status != 412:
3113 raise Exception("Unexpected HTTP response: %d" % resp.status)
3114
3115 logger.debug("Valid re-subscription")
3116 headers = {"NT": "upnp:event",
3117 "sid": sid,
3118 "timeout": "Second-1234"}
3119 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3120 resp = conn.getresponse()
3121 if resp.status != 200:
3122 raise Exception("Unexpected HTTP response: %d" % resp.status)
3123 sid2 = resp.getheader("sid")
3124 logger.debug("Subscription SID " + sid2)
3125
3126 if sid != sid2:
3127 raise Exception("Unexpected SID change")
3128
3129 logger.debug("Valid re-subscription")
3130 headers = {"NT": "upnp:event",
3131 "sid": "uuid: \t \t" + sid.split(':')[1],
3132 "timeout": "Second-1234"}
3133 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3134 resp = conn.getresponse()
3135 if resp.status != 200:
3136 raise Exception("Unexpected HTTP response: %d" % resp.status)
3137
3138 logger.debug("Invalid unsubscription")
3139 headers = {"sid": sid}
3140 conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
3141 resp = conn.getresponse()
3142 if resp.status != 412:
3143 raise Exception("Unexpected HTTP response: %d" % resp.status)
3144 headers = {"foo": "bar"}
3145 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3146 resp = conn.getresponse()
3147 if resp.status != 412:
3148 raise Exception("Unexpected HTTP response: %d" % resp.status)
3149
3150 logger.debug("Valid unsubscription")
3151 headers = {"sid": sid}
3152 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3153 resp = conn.getresponse()
3154 if resp.status != 200:
3155 raise Exception("Unexpected HTTP response: %d" % resp.status)
3156
3157 logger.debug("Unsubscription for not existing SID")
3158 headers = {"sid": sid}
3159 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3160 resp = conn.getresponse()
3161 if resp.status != 412:
3162 raise Exception("Unexpected HTTP response: %d" % resp.status)
3163
3164 logger.debug("Invalid unsubscription")
3165 headers = {"sid": " \t \tfoo"}
3166 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3167 resp = conn.getresponse()
3168 if resp.status != 400:
3169 raise Exception("Unexpected HTTP response: %d" % resp.status)
3170
3171 logger.debug("Invalid unsubscription")
3172 headers = {"sid": "uuid:\t \tfoo"}
3173 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3174 resp = conn.getresponse()
3175 if resp.status != 400:
3176 raise Exception("Unexpected HTTP response: %d" % resp.status)
3177
3178 logger.debug("Invalid unsubscription")
3179 headers = {"NT": "upnp:event",
3180 "sid": sid}
3181 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3182 resp = conn.getresponse()
3183 if resp.status != 400:
3184 raise Exception("Unexpected HTTP response: %d" % resp.status)
3185 headers = {"callback": '<http://127.0.0.1:12345/event>',
3186 "sid": sid}
3187 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3188 resp = conn.getresponse()
3189 if resp.status != 400:
3190 raise Exception("Unexpected HTTP response: %d" % resp.status)
3191
3192 logger.debug("Valid subscription with multiple callbacks")
3193 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>',
3194 "NT": "upnp:event",
3195 "timeout": "Second-1234"}
3196 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3197 resp = conn.getresponse()
3198 if resp.status != 200:
3199 raise Exception("Unexpected HTTP response: %d" % resp.status)
3200 sid = resp.getheader("sid")
3201 logger.debug("Subscription SID " + sid)
3202
3203 # Force subscription to be deleted due to errors
3204 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3205 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3206 with alloc_fail(hapd, 1, "event_build_message"):
3207 for i in range(10):
3208 dev[1].dump_monitor()
3209 dev[2].dump_monitor()
3210 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3211 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3212 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3213 dev[1].request("WPS_CANCEL")
3214 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3215 dev[2].request("WPS_CANCEL")
3216 if i % 4 == 1:
3217 time.sleep(1)
3218 else:
3219 time.sleep(0.1)
3220 time.sleep(0.2)
3221
3222 headers = {"sid": sid}
3223 conn.request("UNSUBSCRIBE", eventurl.path, "", headers)
3224 resp = conn.getresponse()
3225 if resp.status != 200 and resp.status != 412:
3226 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3227
3228 headers = {"callback": '<http://127.0.0.1:12345/event>',
3229 "NT": "upnp:event",
3230 "timeout": "Second-1234"}
3231 with alloc_fail(hapd, 1, "http_client_addr;event_send_start"):
3232 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3233 resp = conn.getresponse()
3234 if resp.status != 200:
3235 raise Exception("Unexpected HTTP response for SUBSCRIBE: %d" % resp.status)
3236 sid = resp.getheader("sid")
3237 logger.debug("Subscription SID " + sid)
3238
3239 headers = {"sid": sid}
3240 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3241 resp = conn.getresponse()
3242 if resp.status != 200:
3243 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3244
3245 headers = {"callback": '<http://127.0.0.1:12345/event>',
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 sid = resp.getheader("sid")
3253 logger.debug("Subscription SID " + sid)
3254
3255 with alloc_fail(hapd, 1, "=wps_upnp_event_add"):
3256 for i in range(2):
3257 dev[1].dump_monitor()
3258 dev[2].dump_monitor()
3259 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3260 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3261 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3262 dev[1].request("WPS_CANCEL")
3263 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3264 dev[2].request("WPS_CANCEL")
3265 if i == 0:
3266 time.sleep(1)
3267 else:
3268 time.sleep(0.1)
3269
3270 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3271 resp = conn.getresponse()
3272 if resp.status != 200:
3273 raise Exception("Unexpected HTTP response: %d" % resp.status)
3274
3275 with alloc_fail(hapd, 1, "wpabuf_dup;wps_upnp_event_add"):
3276 dev[1].dump_monitor()
3277 dev[2].dump_monitor()
3278 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3279 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3280 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3281 dev[1].request("WPS_CANCEL")
3282 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3283 dev[2].request("WPS_CANCEL")
3284 time.sleep(0.1)
3285
3286 with fail_test(hapd, 1, "os_get_random;uuid_make;subscription_start"):
3287 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3288 resp = conn.getresponse()
3289 if resp.status != 500:
3290 raise Exception("Unexpected HTTP response: %d" % resp.status)
3291
3292 with alloc_fail(hapd, 1, "=subscription_start"):
3293 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3294 resp = conn.getresponse()
3295 if resp.status != 500:
3296 raise Exception("Unexpected HTTP response: %d" % resp.status)
3297
3298 headers = {"callback": '',
3299 "NT": "upnp:event",
3300 "timeout": "Second-1234"}
3301 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3302 resp = conn.getresponse()
3303 if resp.status != 500:
3304 raise Exception("Unexpected HTTP response: %d" % resp.status)
3305
3306 headers = {"callback": ' <',
3307 "NT": "upnp:event",
3308 "timeout": "Second-1234"}
3309 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3310 resp = conn.getresponse()
3311 if resp.status != 500:
3312 raise Exception("Unexpected HTTP response: %d" % resp.status)
3313
3314 headers = {"callback": '<http://127.0.0.1:12345/event>',
3315 "NT": "upnp:event",
3316 "timeout": "Second-1234"}
3317 with alloc_fail(hapd, 1, "wpabuf_alloc;subscription_first_event"):
3318 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3319 resp = conn.getresponse()
3320 if resp.status != 500:
3321 raise Exception("Unexpected HTTP response: %d" % resp.status)
3322
3323 with alloc_fail(hapd, 1, "wps_upnp_event_add;subscription_first_event"):
3324 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3325 resp = conn.getresponse()
3326 if resp.status != 500:
3327 raise Exception("Unexpected HTTP response: %d" % resp.status)
3328
3329 with alloc_fail(hapd, 1, "subscr_addr_add_url"):
3330 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3331 resp = conn.getresponse()
3332 if resp.status != 500:
3333 raise Exception("Unexpected HTTP response: %d" % resp.status)
3334
3335 with alloc_fail(hapd, 2, "subscr_addr_add_url"):
3336 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3337 resp = conn.getresponse()
3338 if resp.status != 500:
3339 raise Exception("Unexpected HTTP response: %d" % resp.status)
3340
3341 for i in range(6):
3342 headers = {"callback": '<http://127.0.0.1:%d/event>' % (12345 + i),
3343 "NT": "upnp:event",
3344 "timeout": "Second-1234"}
3345 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3346 resp = conn.getresponse()
3347 if resp.status != 200:
3348 raise Exception("Unexpected HTTP response: %d" % resp.status)
3349
3350 with alloc_fail(hapd, 1, "=upnp_wps_device_send_wlan_event"):
3351 dev[1].dump_monitor()
3352 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3353 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3354 dev[1].request("WPS_CANCEL")
3355 time.sleep(0.1)
3356
3357 with alloc_fail(hapd, 1, "wpabuf_alloc;upnp_wps_device_send_event"):
3358 dev[1].dump_monitor()
3359 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3360 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3361 dev[1].request("WPS_CANCEL")
3362 time.sleep(0.1)
3363
3364 with alloc_fail(hapd, 1,
3365 "base64_gen_encode;?base64_encode;upnp_wps_device_send_wlan_event"):
3366 dev[1].dump_monitor()
3367 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3368 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3369 dev[1].request("WPS_CANCEL")
3370 time.sleep(0.1)
3371
3372 hapd.disable()
3373 with alloc_fail(hapd, 1, "get_netif_info"):
3374 if "FAIL" not in hapd.request("ENABLE"):
3375 raise Exception("ENABLE succeeded during OOM")
3376
3377 def test_ap_wps_upnp_subscribe_events(dev, apdev):
3378 """WPS AP and UPnP event subscription and many events"""
3379 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3380 hapd = add_ssdp_ap(apdev[0], ap_uuid)
3381
3382 location = ssdp_get_location(ap_uuid)
3383 urls = upnp_get_urls(location)
3384 eventurl = urlparse(urls['event_sub_url'])
3385
3386 class WPSERHTTPServer(StreamRequestHandler):
3387 def handle(self):
3388 data = self.rfile.readline().strip()
3389 logger.debug(data)
3390 self.wfile.write(gen_wps_event())
3391
3392 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
3393 server.timeout = 1
3394
3395 url = urlparse(location)
3396 conn = HTTPConnection(url.netloc)
3397
3398 headers = {"callback": '<http://127.0.0.1:12345/event>',
3399 "NT": "upnp:event",
3400 "timeout": "Second-1234"}
3401 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3402 resp = conn.getresponse()
3403 if resp.status != 200:
3404 raise Exception("Unexpected HTTP response: %d" % resp.status)
3405 sid = resp.getheader("sid")
3406 logger.debug("Subscription SID " + sid)
3407
3408 # Fetch the first event message
3409 server.handle_request()
3410
3411 # Force subscription event queue to reach the maximum length by generating
3412 # new proxied events without the ER fetching any of the pending events.
3413 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3414 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3415 for i in range(16):
3416 dev[1].dump_monitor()
3417 dev[2].dump_monitor()
3418 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3419 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3420 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3421 dev[1].request("WPS_CANCEL")
3422 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3423 dev[2].request("WPS_CANCEL")
3424 if i % 4 == 1:
3425 time.sleep(1)
3426 else:
3427 time.sleep(0.1)
3428
3429 hapd.request("WPS_PIN any 12345670")
3430 dev[1].dump_monitor()
3431 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3432 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=10)
3433 if ev is None:
3434 raise Exception("WPS success not reported")
3435
3436 # Close the WPS ER HTTP server without fetching all the pending events.
3437 # This tests hostapd code path that clears subscription and the remaining
3438 # event queue when the interface is deinitialized.
3439 server.handle_request()
3440 server.server_close()
3441
3442 dev[1].wait_connected()
3443
3444 def test_ap_wps_upnp_http_proto(dev, apdev):
3445 """WPS AP and UPnP/HTTP protocol testing"""
3446 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3447 add_ssdp_ap(apdev[0], ap_uuid)
3448
3449 location = ssdp_get_location(ap_uuid)
3450
3451 url = urlparse(location)
3452 conn = HTTPConnection(url.netloc, timeout=0.2)
3453 #conn.set_debuglevel(1)
3454
3455 conn.request("HEAD", "hello")
3456 resp = conn.getresponse()
3457 if resp.status != 501:
3458 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3459 conn.close()
3460
3461 for cmd in ["PUT", "DELETE", "TRACE", "CONNECT", "M-SEARCH", "M-POST"]:
3462 try:
3463 conn.request(cmd, "hello")
3464 resp = conn.getresponse()
3465 except Exception as e:
3466 pass
3467 conn.close()
3468
3469 headers = {"Content-Length": 'abc'}
3470 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3471 try:
3472 resp = conn.getresponse()
3473 except Exception as e:
3474 pass
3475 conn.close()
3476
3477 headers = {"Content-Length": '-10'}
3478 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3479 try:
3480 resp = conn.getresponse()
3481 except Exception as e:
3482 pass
3483 conn.close()
3484
3485 headers = {"Content-Length": '10000000000000'}
3486 conn.request("HEAD", "hello", "\r\n\r\nhello", headers)
3487 try:
3488 resp = conn.getresponse()
3489 except Exception as e:
3490 pass
3491 conn.close()
3492
3493 headers = {"Transfer-Encoding": 'abc'}
3494 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3495 resp = conn.getresponse()
3496 if resp.status != 501:
3497 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3498 conn.close()
3499
3500 headers = {"Transfer-Encoding": 'chunked'}
3501 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3502 resp = conn.getresponse()
3503 if resp.status != 501:
3504 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3505 conn.close()
3506
3507 # Too long a header
3508 conn.request("HEAD", 5000 * 'A')
3509 try:
3510 resp = conn.getresponse()
3511 except Exception as e:
3512 pass
3513 conn.close()
3514
3515 # Long URL but within header length limits
3516 conn.request("HEAD", 3000 * 'A')
3517 resp = conn.getresponse()
3518 if resp.status != 501:
3519 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3520 conn.close()
3521
3522 headers = {"Content-Length": '20'}
3523 conn.request("POST", "hello", 10 * 'A' + "\r\n\r\n", headers)
3524 try:
3525 resp = conn.getresponse()
3526 except Exception as e:
3527 pass
3528 conn.close()
3529
3530 conn.request("POST", "hello", 5000 * 'A' + "\r\n\r\n")
3531 resp = conn.getresponse()
3532 if resp.status != 404:
3533 raise Exception("Unexpected HTTP response: %d" % resp.status)
3534 conn.close()
3535
3536 conn.request("POST", "hello", 60000 * 'A' + "\r\n\r\n")
3537 try:
3538 resp = conn.getresponse()
3539 except Exception as e:
3540 pass
3541 conn.close()
3542
3543 def test_ap_wps_upnp_http_proto_chunked(dev, apdev):
3544 """WPS AP and UPnP/HTTP protocol testing for chunked encoding"""
3545 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3546 add_ssdp_ap(apdev[0], ap_uuid)
3547
3548 location = ssdp_get_location(ap_uuid)
3549
3550 url = urlparse(location)
3551 conn = HTTPConnection(url.netloc)
3552 #conn.set_debuglevel(1)
3553
3554 headers = {"Transfer-Encoding": 'chunked'}
3555 conn.request("POST", "hello",
3556 "a\r\nabcdefghij\r\n" + "2\r\nkl\r\n" + "0\r\n\r\n",
3557 headers)
3558 resp = conn.getresponse()
3559 if resp.status != 404:
3560 raise Exception("Unexpected HTTP response: %d" % resp.status)
3561 conn.close()
3562
3563 conn.putrequest("POST", "hello")
3564 conn.putheader('Transfer-Encoding', 'chunked')
3565 conn.endheaders()
3566 conn.send(b"a\r\nabcdefghij\r\n")
3567 time.sleep(0.1)
3568 conn.send(b"2\r\nkl\r\n")
3569 conn.send(b"0\r\n\r\n")
3570 resp = conn.getresponse()
3571 if resp.status != 404:
3572 raise Exception("Unexpected HTTP response: %d" % resp.status)
3573 conn.close()
3574
3575 conn.putrequest("POST", "hello")
3576 conn.putheader('Transfer-Encoding', 'chunked')
3577 conn.endheaders()
3578 completed = False
3579 try:
3580 for i in range(20000):
3581 conn.send(b"1\r\nZ\r\n")
3582 conn.send(b"0\r\n\r\n")
3583 resp = conn.getresponse()
3584 completed = True
3585 except Exception as e:
3586 pass
3587 conn.close()
3588 if completed:
3589 raise Exception("Too long chunked request did not result in connection reset")
3590
3591 headers = {"Transfer-Encoding": 'chunked'}
3592 conn.request("POST", "hello", "80000000\r\na", headers)
3593 try:
3594 resp = conn.getresponse()
3595 except Exception as e:
3596 pass
3597 conn.close()
3598
3599 conn.request("POST", "hello", "10000000\r\na", headers)
3600 try:
3601 resp = conn.getresponse()
3602 except Exception as e:
3603 pass
3604 conn.close()
3605
3606 @remote_compatible
3607 def test_ap_wps_disabled(dev, apdev):
3608 """WPS operations while WPS is disabled"""
3609 ssid = "test-wps-disabled"
3610 hapd = hostapd.add_ap(apdev[0], {"ssid": ssid})
3611 if "FAIL" not in hapd.request("WPS_PBC"):
3612 raise Exception("WPS_PBC succeeded unexpectedly")
3613 if "FAIL" not in hapd.request("WPS_CANCEL"):
3614 raise Exception("WPS_CANCEL succeeded unexpectedly")
3615
3616 def test_ap_wps_mixed_cred(dev, apdev):
3617 """WPS 2.0 STA merging mixed mode WPA/WPA2 credentials"""
3618 ssid = "test-wps-wep"
3619 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3620 "skip_cred_build": "1", "extra_cred": "wps-mixed-cred"}
3621 hapd = hostapd.add_ap(apdev[0], params)
3622 hapd.request("WPS_PBC")
3623 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3624 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3625 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
3626 if ev is None:
3627 raise Exception("WPS-SUCCESS event timed out")
3628 nets = dev[0].list_networks()
3629 if len(nets) != 1:
3630 raise Exception("Unexpected number of network blocks")
3631 id = nets[0]['id']
3632 proto = dev[0].get_network(id, "proto")
3633 if proto != "WPA RSN":
3634 raise Exception("Unexpected merged proto field value: " + proto)
3635 pairwise = dev[0].get_network(id, "pairwise")
3636 p = pairwise.split()
3637 if "CCMP" not in p or "TKIP" not in p:
3638 raise Exception("Unexpected merged pairwise field value: " + pairwise)
3639
3640 @remote_compatible
3641 def test_ap_wps_while_connected(dev, apdev):
3642 """WPS PBC provisioning while connected to another AP"""
3643 ssid = "test-wps-conf"
3644 hapd = hostapd.add_ap(apdev[0],
3645 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3646 "wpa_passphrase": "12345678", "wpa": "2",
3647 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3648
3649 hostapd.add_ap(apdev[1], {"ssid": "open"})
3650 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3651
3652 logger.info("WPS provisioning step")
3653 hapd.request("WPS_PBC")
3654 dev[0].dump_monitor()
3655 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3656 dev[0].wait_connected(timeout=30)
3657 status = dev[0].get_status()
3658 if status['bssid'] != apdev[0]['bssid']:
3659 raise Exception("Unexpected BSSID")
3660
3661 @remote_compatible
3662 def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
3663 """WPS PBC provisioning while connected to another AP and STA_AUTOCONNECT disabled"""
3664 ssid = "test-wps-conf"
3665 hapd = hostapd.add_ap(apdev[0],
3666 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3667 "wpa_passphrase": "12345678", "wpa": "2",
3668 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3669
3670 hostapd.add_ap(apdev[1], {"ssid": "open"})
3671
3672 try:
3673 dev[0].request("STA_AUTOCONNECT 0")
3674 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3675
3676 logger.info("WPS provisioning step")
3677 hapd.request("WPS_PBC")
3678 dev[0].dump_monitor()
3679 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3680 dev[0].wait_connected(timeout=30)
3681 status = dev[0].get_status()
3682 if status['bssid'] != apdev[0]['bssid']:
3683 raise Exception("Unexpected BSSID")
3684 finally:
3685 dev[0].request("STA_AUTOCONNECT 1")
3686
3687 @remote_compatible
3688 def test_ap_wps_from_event(dev, apdev):
3689 """WPS PBC event on AP to enable PBC"""
3690 ssid = "test-wps-conf"
3691 hapd = hostapd.add_ap(apdev[0],
3692 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3693 "wpa_passphrase": "12345678", "wpa": "2",
3694 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3695 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3696 dev[0].dump_monitor()
3697 hapd.dump_monitor()
3698 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3699
3700 ev = hapd.wait_event(['WPS-ENROLLEE-SEEN'], timeout=15)
3701 if ev is None:
3702 raise Exception("No WPS-ENROLLEE-SEEN event on AP")
3703 vals = ev.split(' ')
3704 if vals[1] != dev[0].p2p_interface_addr():
3705 raise Exception("Unexpected enrollee address: " + vals[1])
3706 if vals[5] != '4':
3707 raise Exception("Unexpected Device Password Id: " + vals[5])
3708 hapd.request("WPS_PBC")
3709 dev[0].wait_connected(timeout=30)
3710
3711 def test_ap_wps_ap_scan_2(dev, apdev):
3712 """AP_SCAN 2 for WPS"""
3713 ssid = "test-wps-conf"
3714 hapd = hostapd.add_ap(apdev[0],
3715 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3716 "wpa_passphrase": "12345678", "wpa": "2",
3717 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3718 hapd.request("WPS_PBC")
3719
3720 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
3721 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
3722 wpas.dump_monitor()
3723
3724 if "OK" not in wpas.request("AP_SCAN 2"):
3725 raise Exception("Failed to set AP_SCAN 2")
3726
3727 wpas.flush_scan_cache()
3728 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
3729 wpas.dump_monitor()
3730 wpas.request("WPS_PBC " + apdev[0]['bssid'])
3731 ev = wpas.wait_event(["WPS-SUCCESS"], timeout=15)
3732 if ev is None:
3733 raise Exception("WPS-SUCCESS event timed out")
3734 wpas.wait_connected(timeout=30)
3735 wpas.dump_monitor()
3736 wpas.request("DISCONNECT")
3737 wpas.wait_disconnected()
3738 id = wpas.list_networks()[0]['id']
3739 pairwise = wpas.get_network(id, "pairwise")
3740 if "CCMP" not in pairwise.split():
3741 raise Exception("Unexpected pairwise parameter value: " + pairwise)
3742 group = wpas.get_network(id, "group")
3743 if "CCMP" not in group.split():
3744 raise Exception("Unexpected group parameter value: " + group)
3745 # Need to select a single cipher for ap_scan=2 testing
3746 wpas.set_network(id, "pairwise", "CCMP")
3747 wpas.set_network(id, "group", "CCMP")
3748 wpas.request("BSS_FLUSH 0")
3749 wpas.dump_monitor()
3750 wpas.request("REASSOCIATE")
3751 wpas.wait_connected(timeout=30)
3752 wpas.dump_monitor()
3753 wpas.request("DISCONNECT")
3754 wpas.wait_disconnected()
3755 wpas.flush_scan_cache()
3756
3757 @remote_compatible
3758 def test_ap_wps_eapol_workaround(dev, apdev):
3759 """EAPOL workaround code path for 802.1X header length mismatch"""
3760 ssid = "test-wps"
3761 hapd = hostapd.add_ap(apdev[0],
3762 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
3763 bssid = apdev[0]['bssid']
3764 hapd.request("SET ext_eapol_frame_io 1")
3765 dev[0].request("SET ext_eapol_frame_io 1")
3766 hapd.request("WPS_PBC")
3767 dev[0].request("WPS_PBC")
3768
3769 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3770 if ev is None:
3771 raise Exception("Timeout on EAPOL-TX from hostapd")
3772
3773 res = dev[0].request("EAPOL_RX " + bssid + " 020000040193000501FFFF")
3774 if "OK" not in res:
3775 raise Exception("EAPOL_RX to wpa_supplicant failed")
3776
3777 def test_ap_wps_iteration(dev, apdev):
3778 """WPS PIN and iterate through APs without selected registrar"""
3779 ssid = "test-wps-conf"
3780 hapd = hostapd.add_ap(apdev[0],
3781 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3782 "wpa_passphrase": "12345678", "wpa": "2",
3783 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3784
3785 ssid2 = "test-wps-conf2"
3786 hapd2 = hostapd.add_ap(apdev[1],
3787 {"ssid": ssid2, "eap_server": "1", "wps_state": "2",
3788 "wpa_passphrase": "12345678", "wpa": "2",
3789 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3790
3791 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3792 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
3793 dev[0].dump_monitor()
3794 pin = dev[0].request("WPS_PIN any")
3795
3796 # Wait for iteration through all WPS APs to happen before enabling any
3797 # Registrar.
3798 for i in range(2):
3799 ev = dev[0].wait_event(["Associated with"], timeout=30)
3800 if ev is None:
3801 raise Exception("No association seen")
3802 ev = dev[0].wait_event(["WPS-M2D"], timeout=10)
3803 if ev is None:
3804 raise Exception("No M2D from AP")
3805 dev[0].wait_disconnected()
3806
3807 # Verify that each AP requested PIN
3808 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3809 if ev is None:
3810 raise Exception("No WPS-PIN-NEEDED event from AP")
3811 ev = hapd2.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3812 if ev is None:
3813 raise Exception("No WPS-PIN-NEEDED event from AP2")
3814
3815 # Provide PIN to one of the APs and verify that connection gets formed
3816 hapd.request("WPS_PIN any " + pin)
3817 dev[0].wait_connected(timeout=30)
3818
3819 def test_ap_wps_iteration_error(dev, apdev):
3820 """WPS AP iteration on no Selected Registrar and error case with an AP"""
3821 ssid = "test-wps-conf-pin"
3822 hapd = hostapd.add_ap(apdev[0],
3823 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3824 "wpa_passphrase": "12345678", "wpa": "2",
3825 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3826 "wps_independent": "1"})
3827 hapd.request("SET ext_eapol_frame_io 1")
3828 bssid = apdev[0]['bssid']
3829 pin = dev[0].wps_read_pin()
3830 dev[0].request("WPS_PIN any " + pin)
3831
3832 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3833 if ev is None:
3834 raise Exception("No EAPOL-TX (EAP-Request/Identity) from hostapd")
3835 dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
3836
3837 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3838 if ev is None:
3839 raise Exception("No EAPOL-TX (EAP-WSC/Start) from hostapd")
3840 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=5)
3841 if ev is None:
3842 raise Exception("No CTRL-EVENT-EAP-STARTED")
3843
3844 # Do not forward any more EAPOL frames to test wpa_supplicant behavior for
3845 # a case with an incorrectly behaving WPS AP.
3846
3847 # Start the real target AP and activate registrar on it.
3848 hapd2 = hostapd.add_ap(apdev[1],
3849 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3850 "wpa_passphrase": "12345678", "wpa": "2",
3851 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3852 "wps_independent": "1"})
3853 hapd2.request("WPS_PIN any " + pin)
3854
3855 dev[0].wait_disconnected(timeout=15)
3856 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
3857 if ev is None:
3858 raise Exception("No CTRL-EVENT-EAP-STARTED for the second AP")
3859 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
3860 if ev is None:
3861 raise Exception("No WPS-CRED-RECEIVED for the second AP")
3862 dev[0].wait_connected(timeout=15)
3863
3864 @remote_compatible
3865 def test_ap_wps_priority(dev, apdev):
3866 """WPS PIN provisioning with configured AP and wps_priority"""
3867 ssid = "test-wps-conf-pin"
3868 hapd = hostapd.add_ap(apdev[0],
3869 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3870 "wpa_passphrase": "12345678", "wpa": "2",
3871 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3872 logger.info("WPS provisioning step")
3873 pin = dev[0].wps_read_pin()
3874 hapd.request("WPS_PIN any " + pin)
3875 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3876 dev[0].dump_monitor()
3877 try:
3878 dev[0].request("SET wps_priority 6")
3879 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3880 dev[0].wait_connected(timeout=30)
3881 netw = dev[0].list_networks()
3882 prio = dev[0].get_network(netw[0]['id'], 'priority')
3883 if prio != '6':
3884 raise Exception("Unexpected network priority: " + prio)
3885 finally:
3886 dev[0].request("SET wps_priority 0")
3887
3888 @remote_compatible
3889 def test_ap_wps_and_non_wps(dev, apdev):
3890 """WPS and non-WPS AP in single hostapd process"""
3891 params = {"ssid": "wps", "eap_server": "1", "wps_state": "1"}
3892 hapd = hostapd.add_ap(apdev[0], params)
3893
3894 params = {"ssid": "no wps"}
3895 hapd2 = hostapd.add_ap(apdev[1], params)
3896
3897 appin = hapd.request("WPS_AP_PIN random")
3898 if "FAIL" in appin:
3899 raise Exception("Could not generate random AP PIN")
3900 if appin not in hapd.request("WPS_AP_PIN get"):
3901 raise Exception("Could not fetch current AP PIN")
3902
3903 if "FAIL" in hapd.request("WPS_PBC"):
3904 raise Exception("WPS_PBC failed")
3905 if "FAIL" in hapd.request("WPS_CANCEL"):
3906 raise Exception("WPS_CANCEL failed")
3907
3908 def test_ap_wps_init_oom(dev, apdev):
3909 """Initial AP configuration and OOM during PSK generation"""
3910 ssid = "test-wps"
3911 params = {"ssid": ssid, "eap_server": "1", "wps_state": "1"}
3912 hapd = hostapd.add_ap(apdev[0], params)
3913
3914 with alloc_fail(hapd, 1, "base64_gen_encode;?base64_encode;wps_build_cred"):
3915 pin = dev[0].wps_read_pin()
3916 hapd.request("WPS_PIN any " + pin)
3917 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3918 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3919 dev[0].wait_disconnected()
3920
3921 hapd.request("WPS_PIN any " + pin)
3922 dev[0].wait_connected(timeout=30)
3923
3924 @remote_compatible
3925 def test_ap_wps_er_oom(dev, apdev):
3926 """WPS ER OOM in XML processing"""
3927 try:
3928 _test_ap_wps_er_oom(dev, apdev)
3929 finally:
3930 dev[0].request("WPS_ER_STOP")
3931 dev[1].request("WPS_CANCEL")
3932 dev[0].request("DISCONNECT")
3933
3934 def _test_ap_wps_er_oom(dev, apdev):
3935 ssid = "wps-er-ap-config"
3936 ap_pin = "12345670"
3937 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3938 hostapd.add_ap(apdev[0],
3939 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3940 "wpa_passphrase": "12345678", "wpa": "2",
3941 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3942 "device_name": "Wireless AP", "manufacturer": "Company",
3943 "model_name": "WAP", "model_number": "123",
3944 "serial_number": "12345", "device_type": "6-0050F204-1",
3945 "os_version": "01020300",
3946 "config_methods": "label push_button",
3947 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
3948
3949 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
3950
3951 with alloc_fail(dev[0], 1,
3952 "base64_gen_decode;?base64_decode;xml_get_base64_item"):
3953 dev[0].request("WPS_ER_START ifname=lo")
3954 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=3)
3955 if ev is not None:
3956 raise Exception("Unexpected AP discovery")
3957
3958 dev[0].request("WPS_ER_STOP")
3959 dev[0].request("WPS_ER_START ifname=lo")
3960 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
3961 if ev is None:
3962 raise Exception("AP discovery timed out")
3963
3964 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3965 with alloc_fail(dev[0], 1,
3966 "base64_gen_decode;?base64_decode;xml_get_base64_item"):
3967 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
3968 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
3969 if ev is None:
3970 raise Exception("PBC scan failed")
3971 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
3972 if ev is None:
3973 raise Exception("Enrollee discovery timed out")
3974
3975 @remote_compatible
3976 def test_ap_wps_er_init_oom(dev, apdev):
3977 """WPS ER and OOM during init"""
3978 try:
3979 _test_ap_wps_er_init_oom(dev, apdev)
3980 finally:
3981 dev[0].request("WPS_ER_STOP")
3982
3983 def _test_ap_wps_er_init_oom(dev, apdev):
3984 with alloc_fail(dev[0], 1, "wps_er_init"):
3985 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3986 raise Exception("WPS_ER_START succeeded during OOM")
3987 with alloc_fail(dev[0], 1, "http_server_init"):
3988 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3989 raise Exception("WPS_ER_START succeeded during OOM")
3990 with alloc_fail(dev[0], 2, "http_server_init"):
3991 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3992 raise Exception("WPS_ER_START succeeded during OOM")
3993 with alloc_fail(dev[0], 1, "eloop_sock_table_add_sock;?eloop_register_sock;wps_er_ssdp_init"):
3994 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3995 raise Exception("WPS_ER_START succeeded during OOM")
3996 with fail_test(dev[0], 1, "os_get_random;wps_er_init"):
3997 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3998 raise Exception("WPS_ER_START succeeded during os_get_random failure")
3999
4000 @remote_compatible
4001 def test_ap_wps_er_init_fail(dev, apdev):
4002 """WPS ER init failure"""
4003 if "FAIL" not in dev[0].request("WPS_ER_START ifname=does-not-exist"):
4004 dev[0].request("WPS_ER_STOP")
4005 raise Exception("WPS_ER_START with non-existing ifname succeeded")
4006
4007 def test_ap_wps_wpa_cli_action(dev, apdev, test_params):
4008 """WPS events and wpa_cli action script"""
4009 logdir = os.path.abspath(test_params['logdir'])
4010 pidfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.pid')
4011 logfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.res')
4012 actionfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.action.sh')
4013
4014 with open(actionfile, 'w') as f:
4015 f.write('#!/bin/sh\n')
4016 f.write('echo $* >> %s\n' % logfile)
4017 # Kill the process and wait some time before returning to allow all the
4018 # pending events to be processed with some of this happening after the
4019 # eloop SIGALRM signal has been scheduled.
4020 f.write('if [ $2 = "WPS-SUCCESS" -a -r %s ]; then kill `cat %s`; sleep 1; fi\n' % (pidfile, pidfile))
4021
4022 os.chmod(actionfile, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC |
4023 stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
4024
4025 ssid = "test-wps-conf"
4026 hapd = hostapd.add_ap(apdev[0],
4027 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
4028 "wpa_passphrase": "12345678", "wpa": "2",
4029 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
4030
4031 prg = os.path.join(test_params['logdir'],
4032 'alt-wpa_supplicant/wpa_supplicant/wpa_cli')
4033 if not os.path.exists(prg):
4034 prg = '../../wpa_supplicant/wpa_cli'
4035 arg = [prg, '-P', pidfile, '-B', '-i', dev[0].ifname, '-a', actionfile]
4036 subprocess.call(arg)
4037
4038 arg = ['ps', 'ax']
4039 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
4040 out = cmd.communicate()[0].decode()
4041 cmd.wait()
4042 logger.debug("Processes:\n" + out)
4043 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) not in out:
4044 raise Exception("Did not see wpa_cli running")
4045
4046 hapd.request("WPS_PIN any 12345670")
4047 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4048 dev[0].dump_monitor()
4049 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
4050 dev[0].wait_connected(timeout=30)
4051
4052 for i in range(30):
4053 if not os.path.exists(pidfile):
4054 break
4055 time.sleep(0.1)
4056
4057 if not os.path.exists(logfile):
4058 raise Exception("wpa_cli action results file not found")
4059 with open(logfile, 'r') as f:
4060 res = f.read()
4061 if "WPS-SUCCESS" not in res:
4062 raise Exception("WPS-SUCCESS event not seen in action file")
4063
4064 arg = ['ps', 'ax']
4065 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
4066 out = cmd.communicate()[0].decode()
4067 cmd.wait()
4068 logger.debug("Remaining processes:\n" + out)
4069 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) in out:
4070 raise Exception("wpa_cli still running")
4071
4072 if os.path.exists(pidfile):
4073 raise Exception("PID file not removed")
4074
4075 def test_ap_wps_er_ssdp_proto(dev, apdev):
4076 """WPS ER SSDP protocol testing"""
4077 try:
4078 _test_ap_wps_er_ssdp_proto(dev, apdev)
4079 finally:
4080 dev[0].request("WPS_ER_STOP")
4081
4082 def _test_ap_wps_er_ssdp_proto(dev, apdev):
4083 socket.setdefaulttimeout(1)
4084 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4085 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4086 sock.bind(("239.255.255.250", 1900))
4087 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo foo"):
4088 raise Exception("Invalid filter accepted")
4089 if "OK" not in dev[0].request("WPS_ER_START ifname=lo 1.2.3.4"):
4090 raise Exception("WPS_ER_START with filter failed")
4091 (msg, addr) = sock.recvfrom(1000)
4092 msg = msg.decode()
4093 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4094 if "M-SEARCH" not in msg:
4095 raise Exception("Not an M-SEARCH")
4096 sock.sendto(b"FOO", addr)
4097 time.sleep(0.1)
4098 dev[0].request("WPS_ER_STOP")
4099
4100 dev[0].request("WPS_ER_START ifname=lo")
4101 (msg, addr) = sock.recvfrom(1000)
4102 msg = msg.decode()
4103 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4104 if "M-SEARCH" not in msg:
4105 raise Exception("Not an M-SEARCH")
4106 sock.sendto(b"FOO", addr)
4107 sock.sendto(b"HTTP/1.1 200 OK\r\nFOO\r\n\r\n", addr)
4108 sock.sendto(b"HTTP/1.1 200 OK\r\nNTS:foo\r\n\r\n", addr)
4109 sock.sendto(b"HTTP/1.1 200 OK\r\nNTS:ssdp:byebye\r\n\r\n", addr)
4110 sock.sendto(b"HTTP/1.1 200 OK\r\ncache-control: foo=1\r\n\r\n", addr)
4111 sock.sendto(b"HTTP/1.1 200 OK\r\ncache-control: max-age=1\r\n\r\n", addr)
4112 sock.sendto(b"HTTP/1.1 200 OK\r\nusn:\r\n\r\n", addr)
4113 sock.sendto(b"HTTP/1.1 200 OK\r\nusn:foo\r\n\r\n", addr)
4114 sock.sendto(b"HTTP/1.1 200 OK\r\nusn: uuid:\r\n\r\n", addr)
4115 sock.sendto(b"HTTP/1.1 200 OK\r\nusn: uuid: \r\n\r\n", addr)
4116 sock.sendto(b"HTTP/1.1 200 OK\r\nusn: uuid: foo\r\n\r\n", addr)
4117 sock.sendto(b"HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\n\r\n", addr)
4118 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)
4119 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)
4120 with alloc_fail(dev[0], 1, "wps_er_ap_add"):
4121 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)
4122 time.sleep(0.1)
4123 with alloc_fail(dev[0], 2, "wps_er_ap_add"):
4124 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)
4125 time.sleep(0.1)
4126
4127 # Add an AP with bogus URL
4128 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)
4129 # Update timeout on AP without updating URL
4130 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)
4131 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4132 if ev is None:
4133 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4134
4135 # Add an AP with a valid URL (but no server listing to it)
4136 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)
4137 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4138 if ev is None:
4139 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4140
4141 sock.close()
4142
4143 wps_event_url = None
4144
4145 def gen_upnp_info(eventSubURL='wps_event', controlURL='wps_control',
4146 udn='uuid:27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'):
4147 payload = '''<?xml version="1.0"?>
4148 <root xmlns="urn:schemas-upnp-org:device-1-0">
4149 <specVersion>
4150 <major>1</major>
4151 <minor>0</minor>
4152 </specVersion>
4153 <device>
4154 <deviceType>urn:schemas-wifialliance-org:device:WFADevice:1</deviceType>
4155 <friendlyName>WPS Access Point</friendlyName>
4156 <manufacturer>Company</manufacturer>
4157 <modelName>WAP</modelName>
4158 <modelNumber>123</modelNumber>
4159 <serialNumber>12345</serialNumber>
4160 '''
4161 if udn:
4162 payload += '<UDN>' + udn + '</UDN>'
4163 payload += '''<serviceList>
4164 <service>
4165 <serviceType>urn:schemas-wifialliance-org:service:WFAWLANConfig:1</serviceType>
4166 <serviceId>urn:wifialliance-org:serviceId:WFAWLANConfig1</serviceId>
4167 <SCPDURL>wps_scpd.xml</SCPDURL>
4168 '''
4169 if controlURL:
4170 payload += '<controlURL>' + controlURL + '</controlURL>\n'
4171 if eventSubURL:
4172 payload += '<eventSubURL>' + eventSubURL + '</eventSubURL>\n'
4173 payload += '''</service>
4174 </serviceList>
4175 </device>
4176 </root>
4177 '''
4178 hdr = 'HTTP/1.1 200 OK\r\n' + \
4179 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4180 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4181 'Connection: close\r\n' + \
4182 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4183 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4184 return (hdr + payload).encode()
4185
4186 def gen_wps_control(payload_override=None):
4187 payload = '''<?xml version="1.0"?>
4188 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4189 <s:Body>
4190 <u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4191 <NewDeviceInfo>EEoAARAQIgABBBBHABAn6oAanlxOc72C+Jy80Q1+ECAABgIAAAADABAaABCJZ7DPtbU3Ust9
4192 Z3wJF07WEDIAwH45D3i1OqB7eJGwTzqeapS71h3KyXncK2xJZ+xqScrlorNEg6LijBJzG2Ca
4193 +FZli0iliDJd397yAx/jk4nFXco3q5ylBSvSw9dhJ5u1xBKSnTilKGlUHPhLP75PUqM3fot9
4194 7zwtFZ4bx6x1sBA6oEe2d0aUJmLumQGCiKEIWlnxs44zego/2tAe81bDzdPBM7o5HH/FUhD+
4195 KoGzFXp51atP+1n9Vta6AkI0Vye99JKLcC6Md9dMJltSVBgd4Xc4lRAEAAIAIxAQAAIADRAN
4196 AAEBEAgAAgAEEEQAAQIQIQAHQ29tcGFueRAjAANXQVAQJAADMTIzEEIABTEyMzQ1EFQACAAG
4197 AFDyBAABEBEAC1dpcmVsZXNzIEFQEDwAAQEQAgACAAAQEgACAAAQCQACAAAQLQAEgQIDABBJ
4198 AAYANyoAASA=
4199 </NewDeviceInfo>
4200 </u:GetDeviceInfoResponse>
4201 </s:Body>
4202 </s:Envelope>
4203 '''
4204 if payload_override:
4205 payload = payload_override
4206 hdr = 'HTTP/1.1 200 OK\r\n' + \
4207 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4208 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4209 'Connection: close\r\n' + \
4210 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4211 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4212 return (hdr + payload).encode()
4213
4214 def gen_wps_event(sid='uuid:7eb3342a-8a5f-47fe-a585-0785bfec6d8a'):
4215 payload = ""
4216 hdr = 'HTTP/1.1 200 OK\r\n' + \
4217 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4218 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4219 'Connection: close\r\n' + \
4220 'Content-Length: ' + str(len(payload)) + '\r\n'
4221 if sid:
4222 hdr += 'SID: ' + sid + '\r\n'
4223 hdr += 'Timeout: Second-1801\r\n' + \
4224 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4225 return (hdr + payload).encode()
4226
4227 class WPSAPHTTPServer(StreamRequestHandler):
4228 def handle(self):
4229 data = self.rfile.readline().decode().strip()
4230 logger.info("HTTP server received: " + data)
4231 while True:
4232 hdr = self.rfile.readline().decode().strip()
4233 if len(hdr) == 0:
4234 break
4235 logger.info("HTTP header: " + hdr)
4236 if "CALLBACK:" in hdr:
4237 global wps_event_url
4238 wps_event_url = hdr.split(' ')[1].strip('<>')
4239
4240 if "GET /foo.xml" in data:
4241 self.handle_upnp_info()
4242 elif "POST /wps_control" in data:
4243 self.handle_wps_control()
4244 elif "SUBSCRIBE /wps_event" in data:
4245 self.handle_wps_event()
4246 else:
4247 self.handle_others(data)
4248
4249 def handle_upnp_info(self):
4250 self.wfile.write(gen_upnp_info())
4251
4252 def handle_wps_control(self):
4253 self.wfile.write(gen_wps_control())
4254
4255 def handle_wps_event(self):
4256 self.wfile.write(gen_wps_event())
4257
4258 def handle_others(self, data):
4259 logger.info("Ignore HTTP request: " + data)
4260
4261 class MyTCPServer(TCPServer):
4262 def __init__(self, addr, handler):
4263 self.allow_reuse_address = True
4264 TCPServer.__init__(self, addr, handler)
4265
4266 def wps_er_start(dev, http_server, max_age=1, wait_m_search=False,
4267 location_url=None):
4268 socket.setdefaulttimeout(1)
4269 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4270 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4271 sock.bind(("239.255.255.250", 1900))
4272 dev.request("WPS_ER_START ifname=lo")
4273 for i in range(100):
4274 (msg, addr) = sock.recvfrom(1000)
4275 msg = msg.decode()
4276 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4277 if "M-SEARCH" in msg:
4278 break
4279 if not wait_m_search:
4280 raise Exception("Not an M-SEARCH")
4281 if i == 99:
4282 raise Exception("No M-SEARCH seen")
4283
4284 # Add an AP with a valid URL and server listing to it
4285 server = MyTCPServer(("127.0.0.1", 12345), http_server)
4286 if not location_url:
4287 location_url = 'http://127.0.0.1:12345/foo.xml'
4288 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)
4289 server.timeout = 1
4290 return server, sock
4291
4292 def wps_er_stop(dev, sock, server, on_alloc_fail=False):
4293 sock.close()
4294 server.server_close()
4295
4296 if on_alloc_fail:
4297 done = False
4298 for i in range(50):
4299 res = dev.request("GET_ALLOC_FAIL")
4300 if res.startswith("0:"):
4301 done = True
4302 break
4303 time.sleep(0.1)
4304 if not done:
4305 raise Exception("No allocation failure reported")
4306 else:
4307 ev = dev.wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4308 if ev is None:
4309 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4310 dev.request("WPS_ER_STOP")
4311
4312 def run_wps_er_proto_test(dev, handler, no_event_url=False, location_url=None):
4313 try:
4314 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
4315 server, sock = wps_er_start(dev, handler, location_url=location_url)
4316 global wps_event_url
4317 wps_event_url = None
4318 server.handle_request()
4319 server.handle_request()
4320 server.handle_request()
4321 server.server_close()
4322 if no_event_url:
4323 if wps_event_url:
4324 raise Exception("Received event URL unexpectedly")
4325 return
4326 if wps_event_url is None:
4327 raise Exception("Did not get event URL")
4328 logger.info("Event URL: " + wps_event_url)
4329 finally:
4330 dev.request("WPS_ER_STOP")
4331
4332 def send_wlanevent(url, uuid, data, no_response=False):
4333 conn = HTTPConnection(url.netloc)
4334 payload = '''<?xml version="1.0" encoding="utf-8"?>
4335 <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4336 <e:property><STAStatus>1</STAStatus></e:property>
4337 <e:property><APStatus>1</APStatus></e:property>
4338 <e:property><WLANEvent>'''
4339 payload += base64.b64encode(data).decode()
4340 payload += '</WLANEvent></e:property></e:propertyset>'
4341 headers = {"Content-type": 'text/xml; charset="utf-8"',
4342 "Server": "Unspecified, UPnP/1.0, Unspecified",
4343 "HOST": url.netloc,
4344 "NT": "upnp:event",
4345 "SID": "uuid:" + uuid,
4346 "SEQ": "0",
4347 "Content-Length": str(len(payload))}
4348 conn.request("NOTIFY", url.path, payload, headers)
4349 if no_response:
4350 try:
4351 conn.getresponse()
4352 except Exception as e:
4353 pass
4354 return
4355 resp = conn.getresponse()
4356 if resp.status != 200:
4357 raise Exception("Unexpected HTTP response: %d" % resp.status)
4358
4359 def test_ap_wps_er_http_proto(dev, apdev):
4360 """WPS ER HTTP protocol testing"""
4361 try:
4362 _test_ap_wps_er_http_proto(dev, apdev)
4363 finally:
4364 dev[0].request("WPS_ER_STOP")
4365
4366 def _test_ap_wps_er_http_proto(dev, apdev):
4367 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
4368 server, sock = wps_er_start(dev[0], WPSAPHTTPServer, max_age=15)
4369 global wps_event_url
4370 wps_event_url = None
4371 server.handle_request()
4372 server.handle_request()
4373 server.handle_request()
4374 server.server_close()
4375 if wps_event_url is None:
4376 raise Exception("Did not get event URL")
4377 logger.info("Event URL: " + wps_event_url)
4378
4379 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
4380 if ev is None:
4381 raise Exception("No WPS-ER-AP-ADD event")
4382 if uuid not in ev:
4383 raise Exception("UUID mismatch")
4384
4385 sock.close()
4386
4387 logger.info("Valid Probe Request notification")
4388 url = urlparse(wps_event_url)
4389 conn = HTTPConnection(url.netloc)
4390 payload = '''<?xml version="1.0" encoding="utf-8"?>
4391 <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4392 <e:property><STAStatus>1</STAStatus></e:property>
4393 <e:property><APStatus>1</APStatus></e:property>
4394 <e:property><WLANEvent>ATAyOjAwOjAwOjAwOjAwOjAwEEoAARAQOgABAhAIAAIxSBBHABA2LbR7pTpRkYj7VFi5hrLk
4395 EFQACAAAAAAAAAAAEDwAAQMQAgACAAAQCQACAAAQEgACAAAQIQABIBAjAAEgECQAASAQEQAI
4396 RGV2aWNlIEEQSQAGADcqAAEg
4397 </WLANEvent></e:property>
4398 </e:propertyset>
4399 '''
4400 headers = {"Content-type": 'text/xml; charset="utf-8"',
4401 "Server": "Unspecified, UPnP/1.0, Unspecified",
4402 "HOST": url.netloc,
4403 "NT": "upnp:event",
4404 "SID": "uuid:" + uuid,
4405 "SEQ": "0",
4406 "Content-Length": str(len(payload))}
4407 conn.request("NOTIFY", url.path, payload, headers)
4408 resp = conn.getresponse()
4409 if resp.status != 200:
4410 raise Exception("Unexpected HTTP response: %d" % resp.status)
4411
4412 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=5)
4413 if ev is None:
4414 raise Exception("No WPS-ER-ENROLLEE-ADD event")
4415 if "362db47b-a53a-5191-88fb-5458b986b2e4" not in ev:
4416 raise Exception("No Enrollee UUID match")
4417
4418 logger.info("Incorrect event URL AP id")
4419 conn = HTTPConnection(url.netloc)
4420 conn.request("NOTIFY", url.path + '123', payload, headers)
4421 resp = conn.getresponse()
4422 if resp.status != 404:
4423 raise Exception("Unexpected HTTP response: %d" % resp.status)
4424
4425 logger.info("Missing AP id")
4426 conn = HTTPConnection(url.netloc)
4427 conn.request("NOTIFY", '/event/' + url.path.split('/')[2],
4428 payload, headers)
4429 time.sleep(0.1)
4430
4431 logger.info("Incorrect event URL event id")
4432 conn = HTTPConnection(url.netloc)
4433 conn.request("NOTIFY", '/event/123456789/123', payload, headers)
4434 time.sleep(0.1)
4435
4436 logger.info("Incorrect event URL prefix")
4437 conn = HTTPConnection(url.netloc)
4438 conn.request("NOTIFY", '/foobar/123456789/123', payload, headers)
4439 resp = conn.getresponse()
4440 if resp.status != 404:
4441 raise Exception("Unexpected HTTP response: %d" % resp.status)
4442
4443 logger.info("Unsupported request")
4444 conn = HTTPConnection(url.netloc)
4445 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4446 resp = conn.getresponse()
4447 if resp.status != 501:
4448 raise Exception("Unexpected HTTP response: %d" % resp.status)
4449
4450 logger.info("Unsupported request and OOM")
4451 with alloc_fail(dev[0], 1, "wps_er_http_req"):
4452 conn = HTTPConnection(url.netloc)
4453 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4454 time.sleep(0.5)
4455
4456 logger.info("Too short WLANEvent")
4457 data = b'\x00'
4458 send_wlanevent(url, uuid, data)
4459
4460 logger.info("Invalid WLANEventMAC")
4461 data = b'\x00qwertyuiopasdfghjklzxcvbnm'
4462 send_wlanevent(url, uuid, data)
4463
4464 logger.info("Unknown WLANEventType")
4465 data = b'\xff02:00:00:00:00:00'
4466 send_wlanevent(url, uuid, data)
4467
4468 logger.info("Probe Request notification without any attributes")
4469 data = b'\x0102:00:00:00:00:00'
4470 send_wlanevent(url, uuid, data)
4471
4472 logger.info("Probe Request notification with invalid attribute")
4473 data = b'\x0102:00:00:00:00:00\xff'
4474 send_wlanevent(url, uuid, data)
4475
4476 logger.info("EAP message without any attributes")
4477 data = b'\x0202:00:00:00:00:00'
4478 send_wlanevent(url, uuid, data)
4479
4480 logger.info("EAP message with invalid attribute")
4481 data = b'\x0202:00:00:00:00:00\xff'
4482 send_wlanevent(url, uuid, data)
4483
4484 logger.info("EAP message from new STA and not M1")
4485 data = b'\x0202:ff:ff:ff:ff:ff' + b'\x10\x22\x00\x01\x05'
4486 send_wlanevent(url, uuid, data)
4487
4488 logger.info("EAP message: M1")
4489 data = b'\x0202:00:00:00:00:00'
4490 data += b'\x10\x22\x00\x01\x04'
4491 data += b'\x10\x47\x00\x10' + 16 * b'\x00'
4492 data += b'\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4493 data += b'\x10\x1a\x00\x10' + 16 * b'\x00'
4494 data += b'\x10\x32\x00\xc0' + 192 * b'\x00'
4495 data += b'\x10\x04\x00\x02\x00\x00'
4496 data += b'\x10\x10\x00\x02\x00\x00'
4497 data += b'\x10\x0d\x00\x01\x00'
4498 data += b'\x10\x08\x00\x02\x00\x00'
4499 data += b'\x10\x44\x00\x01\x00'
4500 data += b'\x10\x21\x00\x00'
4501 data += b'\x10\x23\x00\x00'
4502 data += b'\x10\x24\x00\x00'
4503 data += b'\x10\x42\x00\x00'
4504 data += b'\x10\x54\x00\x08' + 8 * b'\x00'
4505 data += b'\x10\x11\x00\x00'
4506 data += b'\x10\x3c\x00\x01\x00'
4507 data += b'\x10\x02\x00\x02\x00\x00'
4508 data += b'\x10\x12\x00\x02\x00\x00'
4509 data += b'\x10\x09\x00\x02\x00\x00'
4510 data += b'\x10\x2d\x00\x04\x00\x00\x00\x00'
4511 m1 = data
4512 send_wlanevent(url, uuid, data)
4513
4514 logger.info("EAP message: WSC_ACK")
4515 data = b'\x0202:00:00:00:00:00' + b'\x10\x22\x00\x01\x0d'
4516 send_wlanevent(url, uuid, data)
4517
4518 logger.info("EAP message: M1")
4519 send_wlanevent(url, uuid, m1)
4520
4521 logger.info("EAP message: WSC_NACK")
4522 data = b'\x0202:00:00:00:00:00' + b'\x10\x22\x00\x01\x0e'
4523 send_wlanevent(url, uuid, data)
4524
4525 logger.info("EAP message: M1 - Too long attribute values")
4526 data = b'\x0202:00:00:00:00:00'
4527 data += b'\x10\x11\x00\x21' + 33 * b'\x00'
4528 data += b'\x10\x45\x00\x21' + 33 * b'\x00'
4529 data += b'\x10\x42\x00\x21' + 33 * b'\x00'
4530 data += b'\x10\x24\x00\x21' + 33 * b'\x00'
4531 data += b'\x10\x23\x00\x21' + 33 * b'\x00'
4532 data += b'\x10\x21\x00\x41' + 65 * b'\x00'
4533 data += b'\x10\x49\x00\x09\x00\x37\x2a\x05\x02\x00\x00\x05\x00'
4534 send_wlanevent(url, uuid, data)
4535
4536 logger.info("EAP message: M1 missing UUID-E")
4537 data = b'\x0202:00:00:00:00:00'
4538 data += b'\x10\x22\x00\x01\x04'
4539 send_wlanevent(url, uuid, data)
4540
4541 logger.info("EAP message: M1 missing MAC Address")
4542 data += b'\x10\x47\x00\x10' + 16 * b'\x00'
4543 send_wlanevent(url, uuid, data)
4544
4545 logger.info("EAP message: M1 missing Enrollee Nonce")
4546 data += b'\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4547 send_wlanevent(url, uuid, data)
4548
4549 logger.info("EAP message: M1 missing Public Key")
4550 data += b'\x10\x1a\x00\x10' + 16 * b'\x00'
4551 send_wlanevent(url, uuid, data)
4552
4553 logger.info("EAP message: M1 missing Authentication Type flags")
4554 data += b'\x10\x32\x00\xc0' + 192 * b'\x00'
4555 send_wlanevent(url, uuid, data)
4556
4557 logger.info("EAP message: M1 missing Encryption Type Flags")
4558 data += b'\x10\x04\x00\x02\x00\x00'
4559 send_wlanevent(url, uuid, data)
4560
4561 logger.info("EAP message: M1 missing Connection Type flags")
4562 data += b'\x10\x10\x00\x02\x00\x00'
4563 send_wlanevent(url, uuid, data)
4564
4565 logger.info("EAP message: M1 missing Config Methods")
4566 data += b'\x10\x0d\x00\x01\x00'
4567 send_wlanevent(url, uuid, data)
4568
4569 logger.info("EAP message: M1 missing Wi-Fi Protected Setup State")
4570 data += b'\x10\x08\x00\x02\x00\x00'
4571 send_wlanevent(url, uuid, data)
4572
4573 logger.info("EAP message: M1 missing Manufacturer")
4574 data += b'\x10\x44\x00\x01\x00'
4575 send_wlanevent(url, uuid, data)
4576
4577 logger.info("EAP message: M1 missing Model Name")
4578 data += b'\x10\x21\x00\x00'
4579 send_wlanevent(url, uuid, data)
4580
4581 logger.info("EAP message: M1 missing Model Number")
4582 data += b'\x10\x23\x00\x00'
4583 send_wlanevent(url, uuid, data)
4584
4585 logger.info("EAP message: M1 missing Serial Number")
4586 data += b'\x10\x24\x00\x00'
4587 send_wlanevent(url, uuid, data)
4588
4589 logger.info("EAP message: M1 missing Primary Device Type")
4590 data += b'\x10\x42\x00\x00'
4591 send_wlanevent(url, uuid, data)
4592
4593 logger.info("EAP message: M1 missing Device Name")
4594 data += b'\x10\x54\x00\x08' + 8 * b'\x00'
4595 send_wlanevent(url, uuid, data)
4596
4597 logger.info("EAP message: M1 missing RF Bands")
4598 data += b'\x10\x11\x00\x00'
4599 send_wlanevent(url, uuid, data)
4600
4601 logger.info("EAP message: M1 missing Association State")
4602 data += b'\x10\x3c\x00\x01\x00'
4603 send_wlanevent(url, uuid, data)
4604
4605 logger.info("EAP message: M1 missing Device Password ID")
4606 data += b'\x10\x02\x00\x02\x00\x00'
4607 send_wlanevent(url, uuid, data)
4608
4609 logger.info("EAP message: M1 missing Configuration Error")
4610 data += b'\x10\x12\x00\x02\x00\x00'
4611 send_wlanevent(url, uuid, data)
4612
4613 logger.info("EAP message: M1 missing OS Version")
4614 data += b'\x10\x09\x00\x02\x00\x00'
4615 send_wlanevent(url, uuid, data)
4616
4617 logger.info("Check max concurrent requests")
4618 addr = (url.hostname, url.port)
4619 socks = {}
4620 for i in range(20):
4621 socks[i] = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4622 socket.IPPROTO_TCP)
4623 socks[i].settimeout(10)
4624 socks[i].connect(addr)
4625 for i in range(20):
4626 socks[i].send(b"GET / HTTP/1.1\r\n\r\n")
4627 count = 0
4628 for i in range(20):
4629 try:
4630 res = socks[i].recv(100).decode()
4631 if "HTTP/1" in res:
4632 count += 1
4633 else:
4634 logger.info("recv[%d]: len=%d" % (i, len(res)))
4635 except:
4636 pass
4637 socks[i].close()
4638 logger.info("%d concurrent HTTP GET operations returned response" % count)
4639 if count < 8:
4640 raise Exception("Too few concurrent HTTP connections accepted")
4641
4642 logger.info("OOM in HTTP server")
4643 for func in ["http_request_init", "httpread_create",
4644 "eloop_register_timeout;httpread_create",
4645 "eloop_sock_table_add_sock;?eloop_register_sock;httpread_create",
4646 "httpread_hdr_analyze"]:
4647 with alloc_fail(dev[0], 1, func):
4648 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4649 socket.IPPROTO_TCP)
4650 sock.connect(addr)
4651 sock.send(b"GET / HTTP/1.1\r\n\r\n")
4652 try:
4653 sock.recv(100)
4654 except:
4655 pass
4656 sock.close()
4657
4658 logger.info("Invalid HTTP header")
4659 for req in [" GET / HTTP/1.1\r\n\r\n",
4660 "HTTP/1.1 200 OK\r\n\r\n",
4661 "HTTP/\r\n\r\n",
4662 "GET %%a%aa% HTTP/1.1\r\n\r\n",
4663 "GET / HTTP/1.1\r\n FOO\r\n\r\n",
4664 "NOTIFY / HTTP/1.1\r\n" + 4097*'a' + '\r\n\r\n',
4665 "NOTIFY / HTTP/1.1\r\n\r\n" + 8193*'a',
4666 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n foo\r\n",
4667 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n1\r\nfoo\r\n",
4668 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\n",
4669 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\naa\ra\r\n\ra"]:
4670 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4671 socket.IPPROTO_TCP)
4672 sock.settimeout(0.1)
4673 sock.connect(addr)
4674 sock.send(req.encode())
4675 try:
4676 sock.recv(100)
4677 except:
4678 pass
4679 sock.close()
4680
4681 with alloc_fail(dev[0], 2, "httpread_read_handler"):
4682 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4683 socket.IPPROTO_TCP)
4684 sock.connect(addr)
4685 sock.send(b"NOTIFY / HTTP/1.1\r\n\r\n" + 4500 * b'a')
4686 try:
4687 sock.recv(100)
4688 except:
4689 pass
4690 sock.close()
4691
4692 conn = HTTPConnection(url.netloc)
4693 payload = '<foo'
4694 headers = {"Content-type": 'text/xml; charset="utf-8"',
4695 "Server": "Unspecified, UPnP/1.0, Unspecified",
4696 "HOST": url.netloc,
4697 "NT": "upnp:event",
4698 "SID": "uuid:" + uuid,
4699 "SEQ": "0",
4700 "Content-Length": str(len(payload))}
4701 conn.request("NOTIFY", url.path, payload, headers)
4702 resp = conn.getresponse()
4703 if resp.status != 200:
4704 raise Exception("Unexpected HTTP response: %d" % resp.status)
4705
4706 conn = HTTPConnection(url.netloc)
4707 payload = '<WLANEvent foo></WLANEvent>'
4708 headers = {"Content-type": 'text/xml; charset="utf-8"',
4709 "Server": "Unspecified, UPnP/1.0, Unspecified",
4710 "HOST": url.netloc,
4711 "NT": "upnp:event",
4712 "SID": "uuid:" + uuid,
4713 "SEQ": "0",
4714 "Content-Length": str(len(payload))}
4715 conn.request("NOTIFY", url.path, payload, headers)
4716 resp = conn.getresponse()
4717 if resp.status != 200:
4718 raise Exception("Unexpected HTTP response: %d" % resp.status)
4719
4720 with alloc_fail(dev[0], 1, "xml_get_first_item"):
4721 send_wlanevent(url, uuid, b'')
4722
4723 with alloc_fail(dev[0], 1, "wpabuf_alloc_ext_data;xml_get_base64_item"):
4724 send_wlanevent(url, uuid, b'foo')
4725
4726 for func in ["wps_init",
4727 "wps_process_manufacturer",
4728 "wps_process_model_name",
4729 "wps_process_model_number",
4730 "wps_process_serial_number",
4731 "wps_process_dev_name"]:
4732 with alloc_fail(dev[0], 1, func):
4733 send_wlanevent(url, uuid, m1)
4734
4735 with alloc_fail(dev[0], 1, "wps_er_http_resp_ok"):
4736 send_wlanevent(url, uuid, m1, no_response=True)
4737
4738 with alloc_fail(dev[0], 1, "wps_er_http_resp_not_found"):
4739 url2 = urlparse(wps_event_url.replace('/event/', '/notfound/'))
4740 send_wlanevent(url2, uuid, m1, no_response=True)
4741
4742 logger.info("EAP message: M1")
4743 data = b'\x0202:11:22:00:00:00'
4744 data += b'\x10\x22\x00\x01\x04'
4745 data += b'\x10\x47\x00\x10' + 16 * b'\x00'
4746 data += b'\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4747 data += b'\x10\x1a\x00\x10' + 16 * b'\x00'
4748 data += b'\x10\x32\x00\xc0' + 192 * b'\x00'
4749 data += b'\x10\x04\x00\x02\x00\x00'
4750 data += b'\x10\x10\x00\x02\x00\x00'
4751 data += b'\x10\x0d\x00\x01\x00'
4752 data += b'\x10\x08\x00\x02\x00\x00'
4753 data += b'\x10\x44\x00\x01\x00'
4754 data += b'\x10\x21\x00\x00'
4755 data += b'\x10\x23\x00\x00'
4756 data += b'\x10\x24\x00\x00'
4757 data += b'\x10\x42\x00\x00'
4758 data += b'\x10\x54\x00\x08' + 8 * b'\x00'
4759 data += b'\x10\x11\x00\x00'
4760 data += b'\x10\x3c\x00\x01\x00'
4761 data += b'\x10\x02\x00\x02\x00\x00'
4762 data += b'\x10\x12\x00\x02\x00\x00'
4763 data += b'\x10\x09\x00\x02\x00\x00'
4764 data += b'\x10\x2d\x00\x04\x00\x00\x00\x00'
4765 dev[0].dump_monitor()
4766 with alloc_fail(dev[0], 1, "wps_er_add_sta_data"):
4767 send_wlanevent(url, uuid, data)
4768 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=0.1)
4769 if ev is not None:
4770 raise Exception("Unexpected enrollee add event")
4771 send_wlanevent(url, uuid, data)
4772 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=2)
4773 if ev is None:
4774 raise Exception("Enrollee add event not seen")
4775
4776 with alloc_fail(dev[0], 1,
4777 "base64_gen_encode;?base64_encode;wps_er_soap_hdr"):
4778 send_wlanevent(url, uuid, data)
4779
4780 with alloc_fail(dev[0], 1, "wpabuf_alloc;wps_er_soap_hdr"):
4781 send_wlanevent(url, uuid, data)
4782
4783 with alloc_fail(dev[0], 1, "http_client_url_parse;wps_er_sta_send_msg"):
4784 send_wlanevent(url, uuid, data)
4785
4786 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_sta_send_msg"):
4787 send_wlanevent(url, uuid, data)
4788
4789 def test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
4790 """WPS ER HTTP protocol testing - no eventSubURL"""
4791 class WPSAPHTTPServer_no_event_sub_url(WPSAPHTTPServer):
4792 def handle_upnp_info(self):
4793 self.wfile.write(gen_upnp_info(eventSubURL=None))
4794 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_event_sub_url,
4795 no_event_url=True)
4796
4797 def test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev):
4798 """WPS ER HTTP protocol testing - DNS name in eventSubURL"""
4799 class WPSAPHTTPServer_event_sub_url_dns(WPSAPHTTPServer):
4800 def handle_upnp_info(self):
4801 self.wfile.write(gen_upnp_info(eventSubURL='http://example.com/wps_event'))
4802 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_event_sub_url_dns,
4803 no_event_url=True)
4804
4805 def test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4806 """WPS ER HTTP protocol testing - subscribe OOM"""
4807 try:
4808 _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev)
4809 finally:
4810 dev[0].request("WPS_ER_STOP")
4811
4812 def _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4813 tests = [(1, "http_client_url_parse"),
4814 (1, "wpabuf_alloc;wps_er_subscribe"),
4815 (1, "http_client_addr"),
4816 (1, "eloop_sock_table_add_sock;?eloop_register_sock;http_client_addr"),
4817 (1, "eloop_register_timeout;http_client_addr")]
4818 for count, func in tests:
4819 with alloc_fail(dev[0], count, func):
4820 server, sock = wps_er_start(dev[0], WPSAPHTTPServer)
4821 server.handle_request()
4822 server.handle_request()
4823 wps_er_stop(dev[0], sock, server, on_alloc_fail=True)
4824
4825 def test_ap_wps_er_http_proto_no_sid(dev, apdev):
4826 """WPS ER HTTP protocol testing - no SID"""
4827 class WPSAPHTTPServer_no_sid(WPSAPHTTPServer):
4828 def handle_wps_event(self):
4829 self.wfile.write(gen_wps_event(sid=None))
4830 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_sid)
4831
4832 def test_ap_wps_er_http_proto_invalid_sid_no_uuid(dev, apdev):
4833 """WPS ER HTTP protocol testing - invalid SID - no UUID"""
4834 class WPSAPHTTPServer_invalid_sid_no_uuid(WPSAPHTTPServer):
4835 def handle_wps_event(self):
4836 self.wfile.write(gen_wps_event(sid='FOO'))
4837 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_no_uuid)
4838
4839 def test_ap_wps_er_http_proto_invalid_sid_uuid(dev, apdev):
4840 """WPS ER HTTP protocol testing - invalid SID UUID"""
4841 class WPSAPHTTPServer_invalid_sid_uuid(WPSAPHTTPServer):
4842 def handle_wps_event(self):
4843 self.wfile.write(gen_wps_event(sid='uuid:FOO'))
4844 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_uuid)
4845
4846 def test_ap_wps_er_http_proto_subscribe_failing(dev, apdev):
4847 """WPS ER HTTP protocol testing - SUBSCRIBE failing"""
4848 class WPSAPHTTPServer_fail_subscribe(WPSAPHTTPServer):
4849 def handle_wps_event(self):
4850 payload = ""
4851 hdr = 'HTTP/1.1 404 Not Found\r\n' + \
4852 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4853 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4854 'Connection: close\r\n' + \
4855 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4856 'Timeout: Second-1801\r\n' + \
4857 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4858 self.wfile.write((hdr + payload).encode())
4859 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_fail_subscribe)
4860
4861 def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4862 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4863 class WPSAPHTTPServer_subscribe_invalid_response(WPSAPHTTPServer):
4864 def handle_wps_event(self):
4865 payload = ""
4866 hdr = 'HTTP/1.1 FOO\r\n' + \
4867 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4868 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4869 'Connection: close\r\n' + \
4870 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4871 'Timeout: Second-1801\r\n' + \
4872 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4873 self.wfile.write((hdr + payload).encode())
4874 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_subscribe_invalid_response)
4875
4876 def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4877 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4878 class WPSAPHTTPServer_invalid_m1(WPSAPHTTPServer):
4879 def handle_wps_control(self):
4880 payload = '''<?xml version="1.0"?>
4881 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4882 <s:Body>
4883 <u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4884 <NewDeviceInfo>Rk9P</NewDeviceInfo>
4885 </u:GetDeviceInfoResponse>
4886 </s:Body>
4887 </s:Envelope>
4888 '''
4889 self.wfile.write(gen_wps_control(payload_override=payload))
4890 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_m1, no_event_url=True)
4891
4892 def test_ap_wps_er_http_proto_upnp_info_no_device(dev, apdev):
4893 """WPS ER HTTP protocol testing - No device in UPnP info"""
4894 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4895 def handle_upnp_info(self):
4896 payload = '''<?xml version="1.0"?>
4897 <root xmlns="urn:schemas-upnp-org:device-1-0">
4898 <specVersion>
4899 <major>1</major>
4900 <minor>0</minor>
4901 </specVersion>
4902 </root>
4903 '''
4904 hdr = 'HTTP/1.1 200 OK\r\n' + \
4905 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4906 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4907 'Connection: close\r\n' + \
4908 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4909 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4910 self.wfile.write((hdr + payload).encode())
4911 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4912
4913 def test_ap_wps_er_http_proto_upnp_info_no_device_type(dev, apdev):
4914 """WPS ER HTTP protocol testing - No deviceType in UPnP info"""
4915 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4916 def handle_upnp_info(self):
4917 payload = '''<?xml version="1.0"?>
4918 <root xmlns="urn:schemas-upnp-org:device-1-0">
4919 <specVersion>
4920 <major>1</major>
4921 <minor>0</minor>
4922 </specVersion>
4923 <device>
4924 </device>
4925 </root>
4926 '''
4927 hdr = 'HTTP/1.1 200 OK\r\n' + \
4928 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4929 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4930 'Connection: close\r\n' + \
4931 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4932 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4933 self.wfile.write((hdr + payload).encode())
4934 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4935
4936 def test_ap_wps_er_http_proto_upnp_info_invalid_udn_uuid(dev, apdev):
4937 """WPS ER HTTP protocol testing - Invalid UDN UUID"""
4938 class WPSAPHTTPServer_invalid_udn_uuid(WPSAPHTTPServer):
4939 def handle_upnp_info(self):
4940 self.wfile.write(gen_upnp_info(udn='uuid:foo'))
4941 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_udn_uuid)
4942
4943 def test_ap_wps_er_http_proto_no_control_url(dev, apdev):
4944 """WPS ER HTTP protocol testing - no controlURL"""
4945 class WPSAPHTTPServer_no_control_url(WPSAPHTTPServer):
4946 def handle_upnp_info(self):
4947 self.wfile.write(gen_upnp_info(controlURL=None))
4948 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_control_url,
4949 no_event_url=True)
4950
4951 def test_ap_wps_er_http_proto_control_url_dns(dev, apdev):
4952 """WPS ER HTTP protocol testing - DNS name in controlURL"""
4953 class WPSAPHTTPServer_control_url_dns(WPSAPHTTPServer):
4954 def handle_upnp_info(self):
4955 self.wfile.write(gen_upnp_info(controlURL='http://example.com/wps_control'))
4956 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_control_url_dns,
4957 no_event_url=True)
4958
4959 def test_ap_wps_http_timeout(dev, apdev):
4960 """WPS AP/ER and HTTP timeout"""
4961 try:
4962 _test_ap_wps_http_timeout(dev, apdev)
4963 finally:
4964 dev[0].request("WPS_ER_STOP")
4965
4966 def _test_ap_wps_http_timeout(dev, apdev):
4967 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
4968 add_ssdp_ap(apdev[0], ap_uuid)
4969
4970 location = ssdp_get_location(ap_uuid)
4971 url = urlparse(location)
4972 addr = (url.hostname, url.port)
4973 logger.debug("Open HTTP connection to hostapd, but do not complete request")
4974 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4975 socket.IPPROTO_TCP)
4976 sock.connect(addr)
4977 sock.send(b"G")
4978
4979 class DummyServer(StreamRequestHandler):
4980 def handle(self):
4981 logger.debug("DummyServer - start 31 sec wait")
4982 time.sleep(31)
4983 logger.debug("DummyServer - wait done")
4984
4985 logger.debug("Start WPS ER")
4986 server, sock2 = wps_er_start(dev[0], DummyServer, max_age=40,
4987 wait_m_search=True)
4988
4989 logger.debug("Start server to accept, but not complete, HTTP connection from WPS ER")
4990 # This will wait for 31 seconds..
4991 server.handle_request()
4992
4993 logger.debug("Complete HTTP connection with hostapd (that should have already closed the connection)")
4994 try:
4995 sock.send("ET / HTTP/1.1\r\n\r\n")
4996 res = sock.recv(100)
4997 sock.close()
4998 except:
4999 pass
5000
5001 def test_ap_wps_er_url_parse(dev, apdev):
5002 """WPS ER and URL parsing special cases"""
5003 try:
5004 _test_ap_wps_er_url_parse(dev, apdev)
5005 finally:
5006 dev[0].request("WPS_ER_STOP")
5007
5008 def _test_ap_wps_er_url_parse(dev, apdev):
5009 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
5010 sock.settimeout(1)
5011 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
5012 sock.bind(("239.255.255.250", 1900))
5013 dev[0].request("WPS_ER_START ifname=lo")
5014 (msg, addr) = sock.recvfrom(1000)
5015 msg = msg.decode()
5016 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
5017 if "M-SEARCH" not in msg:
5018 raise Exception("Not an M-SEARCH")
5019 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)
5020 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
5021 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)
5022 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
5023 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)
5024 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
5025
5026 sock.close()
5027
5028 def test_ap_wps_er_link_update(dev, apdev):
5029 """WPS ER and link update special cases"""
5030 class WPSAPHTTPServer_link_update(WPSAPHTTPServer):
5031 def handle_upnp_info(self):
5032 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
5033 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update)
5034
5035 class WPSAPHTTPServer_link_update2(WPSAPHTTPServer):
5036 def handle_others(self, data):
5037 if "GET / " in data:
5038 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
5039 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update2,
5040 location_url='http://127.0.0.1:12345')
5041
5042 def test_ap_wps_er_http_client(dev, apdev):
5043 """WPS ER and HTTP client special cases"""
5044 with alloc_fail(dev[0], 1, "http_link_update"):
5045 run_wps_er_proto_test(dev[0], WPSAPHTTPServer)
5046
5047 with alloc_fail(dev[0], 1, "wpabuf_alloc;http_client_url"):
5048 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
5049
5050 with alloc_fail(dev[0], 1, "httpread_create;http_client_tx_ready"):
5051 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
5052
5053 class WPSAPHTTPServer_req_as_resp(WPSAPHTTPServer):
5054 def handle_upnp_info(self):
5055 self.wfile.write(b"GET / HTTP/1.1\r\n\r\n")
5056 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_req_as_resp,
5057 no_event_url=True)
5058
5059 def test_ap_wps_init_oom(dev, apdev):
5060 """wps_init OOM cases"""
5061 ssid = "test-wps"
5062 appin = "12345670"
5063 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5064 "ap_pin": appin}
5065 hapd = hostapd.add_ap(apdev[0], params)
5066 pin = dev[0].wps_read_pin()
5067
5068 with alloc_fail(hapd, 1, "wps_init"):
5069 hapd.request("WPS_PIN any " + pin)
5070 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5071 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5072 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5073 if ev is None:
5074 raise Exception("No EAP failure reported")
5075 dev[0].request("WPS_CANCEL")
5076
5077 with alloc_fail(dev[0], 2, "wps_init"):
5078 hapd.request("WPS_PIN any " + pin)
5079 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5080 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5081 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5082 if ev is None:
5083 raise Exception("No EAP failure reported")
5084 dev[0].request("WPS_CANCEL")
5085
5086 with alloc_fail(dev[0], 2, "wps_init"):
5087 hapd.request("WPS_PBC")
5088 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5089 dev[0].request("WPS_PBC %s" % (apdev[0]['bssid']))
5090 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5091 if ev is None:
5092 raise Exception("No EAP failure reported")
5093 dev[0].request("WPS_CANCEL")
5094
5095 dev[0].dump_monitor()
5096 new_ssid = "wps-new-ssid"
5097 new_passphrase = "1234567890"
5098 with alloc_fail(dev[0], 3, "wps_init"):
5099 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
5100 new_passphrase, no_wait=True)
5101 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5102 if ev is None:
5103 raise Exception("No EAP failure reported")
5104
5105 dev[0].flush_scan_cache()
5106
5107 @remote_compatible
5108 def test_ap_wps_invalid_assoc_req_elem(dev, apdev):
5109 """WPS and invalid IE in Association Request frame"""
5110 ssid = "test-wps"
5111 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
5112 hapd = hostapd.add_ap(apdev[0], params)
5113 pin = "12345670"
5114 hapd.request("WPS_PIN any " + pin)
5115 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5116 try:
5117 dev[0].request("VENDOR_ELEM_ADD 13 dd050050f20410")
5118 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5119 for i in range(5):
5120 ev = hapd.wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=10)
5121 if ev and "vendor=14122" in ev:
5122 break
5123 if ev is None or "vendor=14122" not in ev:
5124 raise Exception("EAP-WSC not started")
5125 dev[0].request("WPS_CANCEL")
5126 finally:
5127 dev[0].request("VENDOR_ELEM_REMOVE 13 *")
5128
5129 def test_ap_wps_pbc_pin_mismatch(dev, apdev):
5130 """WPS PBC/PIN mismatch"""
5131 ssid = "test-wps"
5132 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
5133 hapd = hostapd.add_ap(apdev[0], params)
5134 hapd.request("SET wps_version_number 0x10")
5135 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5136 hapd.request("WPS_PBC")
5137 pin = dev[0].wps_read_pin()
5138 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5139 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5140 if ev is None:
5141 raise Exception("Scan did not complete")
5142 dev[0].request("WPS_CANCEL")
5143
5144 hapd.request("WPS_CANCEL")
5145 dev[0].flush_scan_cache()
5146
5147 @remote_compatible
5148 def test_ap_wps_ie_invalid(dev, apdev):
5149 """WPS PIN attempt with AP that has invalid WSC IE"""
5150 ssid = "test-wps"
5151 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5152 "vendor_elements": "dd050050f20410"}
5153 hapd = hostapd.add_ap(apdev[0], params)
5154 params = {'ssid': "another", "vendor_elements": "dd050050f20410"}
5155 hostapd.add_ap(apdev[1], params)
5156 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5157 pin = dev[0].wps_read_pin()
5158 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5159 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5160 if ev is None:
5161 raise Exception("Scan did not complete")
5162 dev[0].request("WPS_CANCEL")
5163
5164 @remote_compatible
5165 def test_ap_wps_scan_prio_order(dev, apdev):
5166 """WPS scan priority ordering"""
5167 ssid = "test-wps"
5168 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
5169 hapd = hostapd.add_ap(apdev[0], params)
5170 params = {'ssid': "another", "vendor_elements": "dd050050f20410"}
5171 hostapd.add_ap(apdev[1], params)
5172 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5173 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
5174 pin = dev[0].wps_read_pin()
5175 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5176 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5177 if ev is None:
5178 raise Exception("Scan did not complete")
5179 dev[0].request("WPS_CANCEL")
5180
5181 def test_ap_wps_probe_req_ie_oom(dev, apdev):
5182 """WPS ProbeReq IE OOM"""
5183 ssid = "test-wps"
5184 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
5185 hapd = hostapd.add_ap(apdev[0], params)
5186 pin = dev[0].wps_read_pin()
5187 hapd.request("WPS_PIN any " + pin)
5188 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5189 with alloc_fail(dev[0], 1, "wps_build_probe_req_ie"):
5190 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5191 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5192 if ev is None:
5193 raise Exception("Association not seen")
5194 dev[0].request("WPS_CANCEL")
5195 dev[0].wait_disconnected()
5196
5197 with alloc_fail(dev[0], 1, "wps_ie_encapsulate"):
5198 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5199 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5200 if ev is None:
5201 raise Exception("Association not seen")
5202 dev[0].request("WPS_CANCEL")
5203 hapd.disable()
5204 dev[0].request("REMOVE_NETWORK all")
5205 dev[0].wait_disconnected()
5206 time.sleep(0.2)
5207 dev[0].flush_scan_cache()
5208
5209 def test_ap_wps_assoc_req_ie_oom(dev, apdev):
5210 """WPS AssocReq IE OOM"""
5211 ssid = "test-wps"
5212 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
5213 hapd = hostapd.add_ap(apdev[0], params)
5214 pin = dev[0].wps_read_pin()
5215 hapd.request("WPS_PIN any " + pin)
5216 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5217 with alloc_fail(dev[0], 1, "wps_build_assoc_req_ie"):
5218 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5219 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5220 if ev is None:
5221 raise Exception("Association not seen")
5222 dev[0].request("WPS_CANCEL")
5223
5224 def test_ap_wps_assoc_resp_ie_oom(dev, apdev):
5225 """WPS AssocResp IE OOM"""
5226 ssid = "test-wps"
5227 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
5228 hapd = hostapd.add_ap(apdev[0], params)
5229 pin = dev[0].wps_read_pin()
5230 hapd.request("WPS_PIN any " + pin)
5231 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5232 with alloc_fail(hapd, 1, "wps_build_assoc_resp_ie"):
5233 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5234 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5235 if ev is None:
5236 raise Exception("Association not seen")
5237 dev[0].request("WPS_CANCEL")
5238
5239 @remote_compatible
5240 def test_ap_wps_bss_info_errors(dev, apdev):
5241 """WPS BSS info errors"""
5242 params = {"ssid": "1",
5243 "vendor_elements": "dd0e0050f20410440001ff101100010a"}
5244 hostapd.add_ap(apdev[0], params)
5245 params = {'ssid': "2", "vendor_elements": "dd050050f20410"}
5246 hostapd.add_ap(apdev[1], params)
5247 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5248 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
5249 bss = dev[0].get_bss(apdev[0]['bssid'])
5250 logger.info("BSS: " + str(bss))
5251 if "wps_state" in bss:
5252 raise Exception("Unexpected wps_state in BSS info")
5253 if 'wps_device_name' not in bss:
5254 raise Exception("No wps_device_name in BSS info")
5255 if bss['wps_device_name'] != '_':
5256 raise Exception("Unexpected wps_device_name value")
5257 bss = dev[0].get_bss(apdev[1]['bssid'])
5258 logger.info("BSS: " + str(bss))
5259
5260 with alloc_fail(dev[0], 1, "=wps_attr_text"):
5261 bss = dev[0].get_bss(apdev[0]['bssid'])
5262 logger.info("BSS(OOM): " + str(bss))
5263
5264 def wps_run_pbc_fail_ap(apdev, dev, hapd):
5265 hapd.request("WPS_PBC")
5266 dev.scan_for_bss(apdev['bssid'], freq="2412")
5267 dev.request("WPS_PBC " + apdev['bssid'])
5268 ev = dev.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5269 if ev is None:
5270 raise Exception("No EAP failure reported")
5271 dev.request("WPS_CANCEL")
5272 dev.wait_disconnected()
5273 for i in range(5):
5274 try:
5275 dev.flush_scan_cache()
5276 break
5277 except Exception as e:
5278 if str(e).startswith("Failed to trigger scan"):
5279 # Try again
5280 time.sleep(1)
5281 else:
5282 raise
5283
5284 def wps_run_pbc_fail(apdev, dev):
5285 hapd = wps_start_ap(apdev)
5286 wps_run_pbc_fail_ap(apdev, dev, hapd)
5287
5288 @remote_compatible
5289 def test_ap_wps_pk_oom(dev, apdev):
5290 """WPS and public key OOM"""
5291 with alloc_fail(dev[0], 1, "wps_build_public_key"):
5292 wps_run_pbc_fail(apdev[0], dev[0])
5293
5294 @remote_compatible
5295 def test_ap_wps_pk_oom_ap(dev, apdev):
5296 """WPS and public key OOM on AP"""
5297 hapd = wps_start_ap(apdev[0])
5298 with alloc_fail(hapd, 1, "wps_build_public_key"):
5299 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5300
5301 @remote_compatible
5302 def test_ap_wps_encr_oom_ap(dev, apdev):
5303 """WPS and encrypted settings decryption OOM on AP"""
5304 hapd = wps_start_ap(apdev[0])
5305 pin = dev[0].wps_read_pin()
5306 hapd.request("WPS_PIN any " + pin)
5307 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5308 with alloc_fail(hapd, 1, "wps_decrypt_encr_settings"):
5309 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
5310 ev = hapd.wait_event(["WPS-FAIL"], timeout=10)
5311 if ev is None:
5312 raise Exception("No WPS-FAIL reported")
5313 dev[0].request("WPS_CANCEL")
5314 dev[0].wait_disconnected()
5315
5316 @remote_compatible
5317 def test_ap_wps_encr_no_random_ap(dev, apdev):
5318 """WPS and no random data available for encryption on AP"""
5319 hapd = wps_start_ap(apdev[0])
5320 with fail_test(hapd, 1, "os_get_random;wps_build_encr_settings"):
5321 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5322
5323 @remote_compatible
5324 def test_ap_wps_e_hash_no_random_sta(dev, apdev):
5325 """WPS and no random data available for e-hash on STA"""
5326 with fail_test(dev[0], 1, "os_get_random;wps_build_e_hash"):
5327 wps_run_pbc_fail(apdev[0], dev[0])
5328
5329 @remote_compatible
5330 def test_ap_wps_m1_no_random(dev, apdev):
5331 """WPS and no random for M1 on STA"""
5332 with fail_test(dev[0], 1, "os_get_random;wps_build_m1"):
5333 wps_run_pbc_fail(apdev[0], dev[0])
5334
5335 @remote_compatible
5336 def test_ap_wps_m1_oom(dev, apdev):
5337 """WPS and OOM for M1 on STA"""
5338 with alloc_fail(dev[0], 1, "wps_build_m1"):
5339 wps_run_pbc_fail(apdev[0], dev[0])
5340
5341 @remote_compatible
5342 def test_ap_wps_m3_oom(dev, apdev):
5343 """WPS and OOM for M3 on STA"""
5344 with alloc_fail(dev[0], 1, "wps_build_m3"):
5345 wps_run_pbc_fail(apdev[0], dev[0])
5346
5347 @remote_compatible
5348 def test_ap_wps_m5_oom(dev, apdev):
5349 """WPS and OOM for M5 on STA"""
5350 hapd = wps_start_ap(apdev[0])
5351 hapd.request("WPS_PBC")
5352 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5353 for i in range(1, 3):
5354 with alloc_fail(dev[0], i, "wps_build_m5"):
5355 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5356 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5357 if ev is None:
5358 raise Exception("No EAP failure reported")
5359 dev[0].request("WPS_CANCEL")
5360 dev[0].wait_disconnected()
5361 dev[0].flush_scan_cache()
5362
5363 @remote_compatible
5364 def test_ap_wps_m5_no_random(dev, apdev):
5365 """WPS and no random for M5 on STA"""
5366 with fail_test(dev[0], 1,
5367 "os_get_random;wps_build_encr_settings;wps_build_m5"):
5368 wps_run_pbc_fail(apdev[0], dev[0])
5369
5370 @remote_compatible
5371 def test_ap_wps_m7_oom(dev, apdev):
5372 """WPS and OOM for M7 on STA"""
5373 hapd = wps_start_ap(apdev[0])
5374 hapd.request("WPS_PBC")
5375 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5376 for i in range(1, 3):
5377 with alloc_fail(dev[0], i, "wps_build_m7"):
5378 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5379 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5380 if ev is None:
5381 raise Exception("No EAP failure reported")
5382 dev[0].request("WPS_CANCEL")
5383 dev[0].wait_disconnected()
5384 dev[0].flush_scan_cache()
5385
5386 @remote_compatible
5387 def test_ap_wps_m7_no_random(dev, apdev):
5388 """WPS and no random for M7 on STA"""
5389 with fail_test(dev[0], 1,
5390 "os_get_random;wps_build_encr_settings;wps_build_m7"):
5391 wps_run_pbc_fail(apdev[0], dev[0])
5392
5393 @remote_compatible
5394 def test_ap_wps_wsc_done_oom(dev, apdev):
5395 """WPS and OOM for WSC_Done on STA"""
5396 with alloc_fail(dev[0], 1, "wps_build_wsc_done"):
5397 wps_run_pbc_fail(apdev[0], dev[0])
5398
5399 def test_ap_wps_random_psk_fail(dev, apdev):
5400 """WPS and no random for PSK on AP"""
5401 ssid = "test-wps"
5402 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
5403 appin = "12345670"
5404 try:
5405 os.remove(pskfile)
5406 except:
5407 pass
5408
5409 try:
5410 with open(pskfile, "w") as f:
5411 f.write("# WPA PSKs\n")
5412
5413 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5414 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
5415 "rsn_pairwise": "CCMP", "ap_pin": appin,
5416 "wpa_psk_file": pskfile}
5417 hapd = hostapd.add_ap(apdev[0], params)
5418
5419 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5420 with fail_test(hapd, 1, "os_get_random;wps_build_cred_network_key"):
5421 dev[0].request("WPS_REG " + apdev[0]['bssid'] + " " + appin)
5422 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5423 if ev is None:
5424 raise Exception("No EAP failure reported")
5425 dev[0].request("WPS_CANCEL")
5426 dev[0].wait_disconnected()
5427
5428 with fail_test(hapd, 1, "os_get_random;wps_build_cred"):
5429 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5430
5431 with alloc_fail(hapd, 1, "wps_build_cred"):
5432 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5433
5434 with alloc_fail(hapd, 2, "wps_build_cred"):
5435 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5436 finally:
5437 os.remove(pskfile)
5438
5439 def wps_ext_eap_identity_req(dev, hapd, bssid):
5440 logger.debug("EAP-Identity/Request")
5441 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5442 if ev is None:
5443 raise Exception("Timeout on EAPOL-TX from hostapd")
5444 res = dev.request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
5445 if "OK" not in res:
5446 raise Exception("EAPOL_RX to wpa_supplicant failed")
5447
5448 def wps_ext_eap_identity_resp(hapd, dev, addr):
5449 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
5450 if ev is None:
5451 raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
5452 res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
5453 if "OK" not in res:
5454 raise Exception("EAPOL_RX to hostapd failed")
5455
5456 def wps_ext_eap_wsc(dst, src, src_addr, msg):
5457 logger.debug(msg)
5458 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5459 if ev is None:
5460 raise Exception("Timeout on EAPOL-TX")
5461 res = dst.request("EAPOL_RX " + src_addr + " " + ev.split(' ')[2])
5462 if "OK" not in res:
5463 raise Exception("EAPOL_RX failed")
5464
5465 def wps_start_ext(apdev, dev, pbc=False, pin=None):
5466 addr = dev.own_addr()
5467 bssid = apdev['bssid']
5468 ssid = "test-wps-conf"
5469 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5470 "wpa_passphrase": "12345678", "wpa": "2",
5471 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
5472 hapd = hostapd.add_ap(apdev, params)
5473
5474 if pbc:
5475 hapd.request("WPS_PBC")
5476 else:
5477 if pin is None:
5478 pin = dev.wps_read_pin()
5479 hapd.request("WPS_PIN any " + pin)
5480 dev.scan_for_bss(bssid, freq="2412")
5481 hapd.request("SET ext_eapol_frame_io 1")
5482 dev.request("SET ext_eapol_frame_io 1")
5483
5484 if pbc:
5485 dev.request("WPS_PBC " + bssid)
5486 else:
5487 dev.request("WPS_PIN " + bssid + " " + pin)
5488 return addr, bssid, hapd
5489
5490 def wps_auth_corrupt(dst, src, addr):
5491 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5492 if ev is None:
5493 raise Exception("Timeout on EAPOL-TX")
5494 src.request("SET ext_eapol_frame_io 0")
5495 dst.request("SET ext_eapol_frame_io 0")
5496 msg = ev.split(' ')[2]
5497 if msg[-24:-16] != '10050008':
5498 raise Exception("Could not find Authenticator attribute")
5499 # Corrupt Authenticator value
5500 msg = msg[:-1] + '%x' % ((int(msg[-1], 16) + 1) % 16)
5501 res = dst.request("EAPOL_RX " + addr + " " + msg)
5502 if "OK" not in res:
5503 raise Exception("EAPOL_RX failed")
5504
5505 def wps_fail_finish(hapd, dev, fail_str):
5506 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5507 if ev is None:
5508 raise Exception("WPS-FAIL not indicated")
5509 if fail_str not in ev:
5510 raise Exception("Unexpected WPS-FAIL value: " + ev)
5511 dev.request("WPS_CANCEL")
5512 dev.wait_disconnected()
5513
5514 def wps_auth_corrupt_from_ap(dev, hapd, bssid, fail_str):
5515 wps_auth_corrupt(dev, hapd, bssid)
5516 wps_fail_finish(hapd, dev, fail_str)
5517
5518 def wps_auth_corrupt_to_ap(dev, hapd, addr, fail_str):
5519 wps_auth_corrupt(hapd, dev, addr)
5520 wps_fail_finish(hapd, dev, fail_str)
5521
5522 def test_ap_wps_authenticator_mismatch_m2(dev, apdev):
5523 """WPS and Authenticator attribute mismatch in M2"""
5524 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5525 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5526 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5527 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5528 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5529 logger.debug("M2")
5530 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=5")
5531
5532 def test_ap_wps_authenticator_mismatch_m3(dev, apdev):
5533 """WPS and Authenticator attribute mismatch in M3"""
5534 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5535 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5536 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5537 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5538 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5539 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5540 logger.debug("M3")
5541 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=7")
5542
5543 def test_ap_wps_authenticator_mismatch_m4(dev, apdev):
5544 """WPS and Authenticator attribute mismatch in M4"""
5545 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5546 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5547 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5548 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5549 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5550 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5551 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5552 logger.debug("M4")
5553 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=8")
5554
5555 def test_ap_wps_authenticator_mismatch_m5(dev, apdev):
5556 """WPS and Authenticator attribute mismatch in M5"""
5557 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5558 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5559 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5560 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5561 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5562 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5563 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5564 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5565 logger.debug("M5")
5566 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=9")
5567
5568 def test_ap_wps_authenticator_mismatch_m6(dev, apdev):
5569 """WPS and Authenticator attribute mismatch in M6"""
5570 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5571 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5572 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5573 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5574 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5575 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5576 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5577 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5578 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5579 logger.debug("M6")
5580 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=10")
5581
5582 def test_ap_wps_authenticator_mismatch_m7(dev, apdev):
5583 """WPS and Authenticator attribute mismatch in M7"""
5584 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5585 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5586 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5587 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5588 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5589 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5590 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5591 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5592 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5593 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5594 logger.debug("M7")
5595 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=11")
5596
5597 def test_ap_wps_authenticator_mismatch_m8(dev, apdev):
5598 """WPS and Authenticator attribute mismatch in M8"""
5599 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5600 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5601 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5602 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5603 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5604 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5605 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5606 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5607 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5608 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5609 wps_ext_eap_wsc(hapd, dev[0], addr, "M7")
5610 logger.debug("M8")
5611 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=12")
5612
5613 def test_ap_wps_authenticator_missing_m2(dev, apdev):
5614 """WPS and Authenticator attribute missing from M2"""
5615 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5616 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5617 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5618 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5619 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5620 logger.debug("M2")
5621 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5622 if ev is None:
5623 raise Exception("Timeout on EAPOL-TX")
5624 hapd.request("SET ext_eapol_frame_io 0")
5625 dev[0].request("SET ext_eapol_frame_io 0")
5626 msg = ev.split(' ')[2]
5627 if msg[-24:-16] != '10050008':
5628 raise Exception("Could not find Authenticator attribute")
5629 # Remove Authenticator value
5630 msg = msg[:-24]
5631 mlen = "%04x" % (int(msg[4:8], 16) - 12)
5632 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:]
5633 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5634 if "OK" not in res:
5635 raise Exception("EAPOL_RX failed")
5636 wps_fail_finish(hapd, dev[0], "msg=5")
5637
5638 def test_ap_wps_m2_dev_passwd_id_p2p(dev, apdev):
5639 """WPS and M2 with different Device Password ID (P2P)"""
5640 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5641 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5642 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5643 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5644 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5645 logger.debug("M2")
5646 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5647 if ev is None:
5648 raise Exception("Timeout on EAPOL-TX")
5649 hapd.request("SET ext_eapol_frame_io 0")
5650 dev[0].request("SET ext_eapol_frame_io 0")
5651 msg = ev.split(' ')[2]
5652 if msg[722:730] != '10120002':
5653 raise Exception("Could not find Device Password ID attribute")
5654 # Replace Device Password ID value. This will fail Authenticator check, but
5655 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5656 # log.
5657 msg = msg[0:730] + "0005" + msg[734:]
5658 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5659 if "OK" not in res:
5660 raise Exception("EAPOL_RX failed")
5661 wps_fail_finish(hapd, dev[0], "msg=5")
5662
5663 def test_ap_wps_m2_dev_passwd_id_change_pin_to_pbc(dev, apdev):
5664 """WPS and M2 with different Device Password ID (PIN to PBC)"""
5665 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5666 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5667 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5668 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5669 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5670 logger.debug("M2")
5671 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5672 if ev is None:
5673 raise Exception("Timeout on EAPOL-TX")
5674 hapd.request("SET ext_eapol_frame_io 0")
5675 dev[0].request("SET ext_eapol_frame_io 0")
5676 msg = ev.split(' ')[2]
5677 if msg[722:730] != '10120002':
5678 raise Exception("Could not find Device Password ID attribute")
5679 # Replace Device Password ID value (PIN --> PBC). This will be rejected.
5680 msg = msg[0:730] + "0004" + msg[734:]
5681 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5682 if "OK" not in res:
5683 raise Exception("EAPOL_RX failed")
5684 wps_fail_finish(hapd, dev[0], "msg=5")
5685
5686 def test_ap_wps_m2_dev_passwd_id_change_pbc_to_pin(dev, apdev):
5687 """WPS and M2 with different Device Password ID (PBC to PIN)"""
5688 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5689 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5690 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5691 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5692 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5693 logger.debug("M2")
5694 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5695 if ev is None:
5696 raise Exception("Timeout on EAPOL-TX")
5697 hapd.request("SET ext_eapol_frame_io 0")
5698 dev[0].request("SET ext_eapol_frame_io 0")
5699 msg = ev.split(' ')[2]
5700 if msg[722:730] != '10120002':
5701 raise Exception("Could not find Device Password ID attribute")
5702 # Replace Device Password ID value. This will fail Authenticator check, but
5703 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5704 # log.
5705 msg = msg[0:730] + "0000" + msg[734:]
5706 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5707 if "OK" not in res:
5708 raise Exception("EAPOL_RX failed")
5709 wps_fail_finish(hapd, dev[0], "msg=5")
5710 dev[0].flush_scan_cache()
5711
5712 def test_ap_wps_m2_missing_dev_passwd_id(dev, apdev):
5713 """WPS and M2 without Device Password ID"""
5714 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5715 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5716 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5717 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5718 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5719 logger.debug("M2")
5720 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5721 if ev is None:
5722 raise Exception("Timeout on EAPOL-TX")
5723 hapd.request("SET ext_eapol_frame_io 0")
5724 dev[0].request("SET ext_eapol_frame_io 0")
5725 msg = ev.split(' ')[2]
5726 if msg[722:730] != '10120002':
5727 raise Exception("Could not find Device Password ID attribute")
5728 # Remove Device Password ID value. This will fail Authenticator check, but
5729 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5730 # log.
5731 mlen = "%04x" % (int(msg[4:8], 16) - 6)
5732 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:722] + msg[734:]
5733 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5734 if "OK" not in res:
5735 raise Exception("EAPOL_RX failed")
5736 wps_fail_finish(hapd, dev[0], "msg=5")
5737
5738 def test_ap_wps_m2_missing_registrar_nonce(dev, apdev):
5739 """WPS and M2 without Registrar Nonce"""
5740 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5741 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5742 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5743 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5744 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5745 logger.debug("M2")
5746 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5747 if ev is None:
5748 raise Exception("Timeout on EAPOL-TX")
5749 hapd.request("SET ext_eapol_frame_io 0")
5750 dev[0].request("SET ext_eapol_frame_io 0")
5751 msg = ev.split(' ')[2]
5752 if msg[96:104] != '10390010':
5753 raise Exception("Could not find Registrar Nonce attribute")
5754 # Remove Registrar Nonce. This will fail Authenticator check, but
5755 # allows the code path in wps_process_registrar_nonce() to be checked from
5756 # the debug log.
5757 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5758 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:96] + msg[136:]
5759 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5760 if "OK" not in res:
5761 raise Exception("EAPOL_RX failed")
5762 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5763 if ev is None:
5764 raise Exception("Disconnect event not seen")
5765 dev[0].request("WPS_CANCEL")
5766 dev[0].flush_scan_cache()
5767
5768 def test_ap_wps_m2_missing_enrollee_nonce(dev, apdev):
5769 """WPS and M2 without Enrollee Nonce"""
5770 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5771 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5772 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5773 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5774 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5775 logger.debug("M2")
5776 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5777 if ev is None:
5778 raise Exception("Timeout on EAPOL-TX")
5779 hapd.request("SET ext_eapol_frame_io 0")
5780 dev[0].request("SET ext_eapol_frame_io 0")
5781 msg = ev.split(' ')[2]
5782 if msg[56:64] != '101a0010':
5783 raise Exception("Could not find enrollee Nonce attribute")
5784 # Remove Enrollee Nonce. This will fail Authenticator check, but
5785 # allows the code path in wps_process_enrollee_nonce() to be checked from
5786 # the debug log.
5787 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5788 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:56] + msg[96:]
5789 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5790 if "OK" not in res:
5791 raise Exception("EAPOL_RX failed")
5792 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5793 if ev is None:
5794 raise Exception("Disconnect event not seen")
5795 dev[0].request("WPS_CANCEL")
5796 dev[0].flush_scan_cache()
5797
5798 def test_ap_wps_m2_missing_uuid_r(dev, apdev):
5799 """WPS and M2 without UUID-R"""
5800 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5801 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5802 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5803 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5804 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5805 logger.debug("M2")
5806 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5807 if ev is None:
5808 raise Exception("Timeout on EAPOL-TX")
5809 hapd.request("SET ext_eapol_frame_io 0")
5810 dev[0].request("SET ext_eapol_frame_io 0")
5811 msg = ev.split(' ')[2]
5812 if msg[136:144] != '10480010':
5813 raise Exception("Could not find enrollee Nonce attribute")
5814 # Remove UUID-R. This will fail Authenticator check, but allows the code
5815 # path in wps_process_uuid_r() to be checked from the debug log.
5816 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5817 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:136] + msg[176:]
5818 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5819 if "OK" not in res:
5820 raise Exception("EAPOL_RX failed")
5821 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5822 if ev is None:
5823 raise Exception("Disconnect event not seen")
5824 dev[0].request("WPS_CANCEL")
5825 dev[0].flush_scan_cache()
5826
5827 def test_ap_wps_m2_invalid(dev, apdev):
5828 """WPS and M2 parsing failure"""
5829 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5830 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5831 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5832 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5833 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5834 logger.debug("M2")
5835 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5836 if ev is None:
5837 raise Exception("Timeout on EAPOL-TX")
5838 hapd.request("SET ext_eapol_frame_io 0")
5839 dev[0].request("SET ext_eapol_frame_io 0")
5840 msg = ev.split(' ')[2]
5841 if msg[136:144] != '10480010':
5842 raise Exception("Could not find enrollee Nonce attribute")
5843 # Remove UUID-R. This will fail Authenticator check, but allows the code
5844 # path in wps_process_uuid_r() to be checked from the debug log.
5845 mlen = "%04x" % (int(msg[4:8], 16) - 1)
5846 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:-2]
5847 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5848 if "OK" not in res:
5849 raise Exception("EAPOL_RX failed")
5850 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5851 if ev is None:
5852 raise Exception("Disconnect event not seen")
5853 dev[0].request("WPS_CANCEL")
5854 dev[0].flush_scan_cache()
5855
5856 def test_ap_wps_m2_missing_msg_type(dev, apdev):
5857 """WPS and M2 without Message Type"""
5858 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5859 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5860 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5861 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5862 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5863 logger.debug("M2")
5864 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5865 if ev is None:
5866 raise Exception("Timeout on EAPOL-TX")
5867 hapd.request("SET ext_eapol_frame_io 0")
5868 dev[0].request("SET ext_eapol_frame_io 0")
5869 msg = ev.split(' ')[2]
5870 if msg[46:54] != '10220001':
5871 raise Exception("Could not find Message Type attribute")
5872 # Remove Message Type. This will fail Authenticator check, but allows the
5873 # code path in wps_process_wsc_msg() to be checked from the debug log.
5874 mlen = "%04x" % (int(msg[4:8], 16) - 5)
5875 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:46] + msg[56:]
5876 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5877 if "OK" not in res:
5878 raise Exception("EAPOL_RX failed")
5879 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5880 if ev is None:
5881 raise Exception("Disconnect event not seen")
5882 dev[0].request("WPS_CANCEL")
5883 dev[0].flush_scan_cache()
5884
5885 def test_ap_wps_m2_unknown_msg_type(dev, apdev):
5886 """WPS and M2 but unknown Message Type"""
5887 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5888 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5889 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5890 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5891 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5892 logger.debug("M2")
5893 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5894 if ev is None:
5895 raise Exception("Timeout on EAPOL-TX")
5896 hapd.request("SET ext_eapol_frame_io 0")
5897 dev[0].request("SET ext_eapol_frame_io 0")
5898 msg = ev.split(' ')[2]
5899 if msg[46:54] != '10220001':
5900 raise Exception("Could not find Message Type attribute")
5901 # Replace Message Type value. This will be rejected.
5902 msg = msg[0:54] + "00" + msg[56:]
5903 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5904 if "OK" not in res:
5905 raise Exception("EAPOL_RX failed")
5906 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5907 if ev is None:
5908 raise Exception("Disconnect event not seen")
5909 dev[0].request("WPS_CANCEL")
5910 dev[0].flush_scan_cache()
5911
5912 def test_ap_wps_m2_unknown_opcode(dev, apdev):
5913 """WPS and M2 but unknown opcode"""
5914 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5915 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5916 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5917 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5918 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5919 logger.debug("M2")
5920 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5921 if ev is None:
5922 raise Exception("Timeout on EAPOL-TX")
5923 hapd.request("SET ext_eapol_frame_io 0")
5924 dev[0].request("SET ext_eapol_frame_io 0")
5925 msg = ev.split(' ')[2]
5926 # Replace opcode. This will be discarded in EAP-WSC processing.
5927 msg = msg[0:32] + "00" + msg[34:]
5928 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5929 if "OK" not in res:
5930 raise Exception("EAPOL_RX failed")
5931 dev[0].request("WPS_CANCEL")
5932 dev[0].wait_disconnected()
5933 dev[0].flush_scan_cache()
5934
5935 def test_ap_wps_m2_unknown_opcode2(dev, apdev):
5936 """WPS and M2 but unknown opcode (WSC_Start)"""
5937 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5938 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5939 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5940 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5941 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5942 logger.debug("M2")
5943 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5944 if ev is None:
5945 raise Exception("Timeout on EAPOL-TX")
5946 hapd.request("SET ext_eapol_frame_io 0")
5947 dev[0].request("SET ext_eapol_frame_io 0")
5948 msg = ev.split(' ')[2]
5949 # Replace opcode. This will be discarded in EAP-WSC processing.
5950 msg = msg[0:32] + "01" + msg[34:]
5951 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5952 if "OK" not in res:
5953 raise Exception("EAPOL_RX failed")
5954 dev[0].request("WPS_CANCEL")
5955 dev[0].wait_disconnected()
5956 dev[0].flush_scan_cache()
5957
5958 def test_ap_wps_m2_unknown_opcode3(dev, apdev):
5959 """WPS and M2 but unknown opcode (WSC_Done)"""
5960 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5961 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5962 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5963 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5964 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5965 logger.debug("M2")
5966 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5967 if ev is None:
5968 raise Exception("Timeout on EAPOL-TX")
5969 hapd.request("SET ext_eapol_frame_io 0")
5970 dev[0].request("SET ext_eapol_frame_io 0")
5971 msg = ev.split(' ')[2]
5972 # Replace opcode. This will be discarded in WPS Enrollee processing.
5973 msg = msg[0:32] + "05" + msg[34:]
5974 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5975 if "OK" not in res:
5976 raise Exception("EAPOL_RX failed")
5977 dev[0].request("WPS_CANCEL")
5978 dev[0].wait_disconnected()
5979 dev[0].flush_scan_cache()
5980
5981 def wps_m2_but_other(dev, apdev, title, msgtype):
5982 addr, bssid, hapd = wps_start_ext(apdev, dev)
5983 wps_ext_eap_identity_req(dev, hapd, bssid)
5984 wps_ext_eap_identity_resp(hapd, dev, addr)
5985 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5986 wps_ext_eap_wsc(hapd, dev, addr, "M1")
5987 logger.debug(title)
5988 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5989 if ev is None:
5990 raise Exception("Timeout on EAPOL-TX")
5991 hapd.request("SET ext_eapol_frame_io 0")
5992 dev.request("SET ext_eapol_frame_io 0")
5993 msg = ev.split(' ')[2]
5994 if msg[46:54] != '10220001':
5995 raise Exception("Could not find Message Type attribute")
5996 # Replace Message Type value. This will be rejected.
5997 msg = msg[0:54] + msgtype + msg[56:]
5998 res = dev.request("EAPOL_RX " + bssid + " " + msg)
5999 if "OK" not in res:
6000 raise Exception("EAPOL_RX failed")
6001 ev = dev.wait_event(["WPS-FAIL"], timeout=5)
6002 if ev is None:
6003 raise Exception("WPS-FAIL event not seen")
6004 dev.request("WPS_CANCEL")
6005 dev.wait_disconnected()
6006
6007 def wps_m4_but_other(dev, apdev, title, msgtype):
6008 addr, bssid, hapd = wps_start_ext(apdev, dev)
6009 wps_ext_eap_identity_req(dev, hapd, bssid)
6010 wps_ext_eap_identity_resp(hapd, dev, addr)
6011 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
6012 wps_ext_eap_wsc(hapd, dev, addr, "M1")
6013 wps_ext_eap_wsc(dev, hapd, bssid, "M2")
6014 wps_ext_eap_wsc(hapd, dev, addr, "M3")
6015 logger.debug(title)
6016 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
6017 if ev is None:
6018 raise Exception("Timeout on EAPOL-TX")
6019 hapd.request("SET ext_eapol_frame_io 0")
6020 dev.request("SET ext_eapol_frame_io 0")
6021 msg = ev.split(' ')[2]
6022 if msg[46:54] != '10220001':
6023 raise Exception("Could not find Message Type attribute")
6024 # Replace Message Type value. This will be rejected.
6025 msg = msg[0:54] + msgtype + msg[56:]
6026 res = dev.request("EAPOL_RX " + bssid + " " + msg)
6027 if "OK" not in res:
6028 raise Exception("EAPOL_RX failed")
6029 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
6030 if ev is None:
6031 raise Exception("WPS-FAIL event not seen")
6032 dev.request("WPS_CANCEL")
6033 dev.wait_disconnected()
6034
6035 def test_ap_wps_m2_msg_type_m4(dev, apdev):
6036 """WPS and M2 but Message Type M4"""
6037 wps_m2_but_other(dev[0], apdev[0], "M2/M4", "08")
6038
6039 def test_ap_wps_m2_msg_type_m6(dev, apdev):
6040 """WPS and M2 but Message Type M6"""
6041 wps_m2_but_other(dev[0], apdev[0], "M2/M6", "0a")
6042
6043 def test_ap_wps_m2_msg_type_m8(dev, apdev):
6044 """WPS and M2 but Message Type M8"""
6045 wps_m2_but_other(dev[0], apdev[0], "M2/M8", "0c")
6046
6047 def test_ap_wps_m4_msg_type_m2(dev, apdev):
6048 """WPS and M4 but Message Type M2"""
6049 wps_m4_but_other(dev[0], apdev[0], "M4/M2", "05")
6050
6051 def test_ap_wps_m4_msg_type_m2d(dev, apdev):
6052 """WPS and M4 but Message Type M2D"""
6053 wps_m4_but_other(dev[0], apdev[0], "M4/M2D", "06")
6054
6055 @remote_compatible
6056 def test_ap_wps_config_methods(dev, apdev):
6057 """WPS configuration method parsing"""
6058 ssid = "test-wps-conf"
6059 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
6060 "wpa_passphrase": "12345678", "wpa": "2",
6061 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
6062 "config_methods": "ethernet display ext_nfc_token int_nfc_token physical_display physical_push_button"}
6063 hapd = hostapd.add_ap(apdev[0], params)
6064 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
6065 "wpa_passphrase": "12345678", "wpa": "2",
6066 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
6067 "config_methods": "display push_button"}
6068 hapd2 = hostapd.add_ap(apdev[1], params)
6069
6070 def test_ap_wps_set_selected_registrar_proto(dev, apdev):
6071 """WPS UPnP SetSelectedRegistrar protocol testing"""
6072 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
6073 hapd = add_ssdp_ap(apdev[0], ap_uuid)
6074
6075 location = ssdp_get_location(ap_uuid)
6076 urls = upnp_get_urls(location)
6077 eventurl = urlparse(urls['event_sub_url'])
6078 ctrlurl = urlparse(urls['control_url'])
6079 url = urlparse(location)
6080 conn = HTTPConnection(url.netloc)
6081
6082 class WPSERHTTPServer(StreamRequestHandler):
6083 def handle(self):
6084 data = self.rfile.readline().strip()
6085 logger.debug(data)
6086 self.wfile.write(gen_wps_event())
6087
6088 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
6089 server.timeout = 1
6090
6091 headers = {"callback": '<http://127.0.0.1:12345/event>',
6092 "NT": "upnp:event",
6093 "timeout": "Second-1234"}
6094 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
6095 resp = conn.getresponse()
6096 if resp.status != 200:
6097 raise Exception("Unexpected HTTP response: %d" % resp.status)
6098 sid = resp.getheader("sid")
6099 logger.debug("Subscription SID " + sid)
6100 server.handle_request()
6101
6102 tests = [(500, "10"),
6103 (200, "104a000110" + "1041000101" + "101200020000" +
6104 "105300023148" +
6105 "1049002c00372a0001200124111111111111222222222222333333333333444444444444555555555555666666666666" +
6106 "10480010362db47ba53a519188fb5458b986b2e4"),
6107 (200, "104a000110" + "1041000100" + "101200020000" +
6108 "105300020000"),
6109 (200, "104a000110" + "1041000100"),
6110 (200, "104a000110")]
6111 for status, test in tests:
6112 tlvs = binascii.unhexlify(test)
6113 newmsg = base64.b64encode(tlvs).decode()
6114 msg = '<?xml version="1.0"?>\n'
6115 msg += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
6116 msg += '<s:Body>'
6117 msg += '<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">'
6118 msg += '<NewMessage>'
6119 msg += newmsg
6120 msg += "</NewMessage></u:SetSelectedRegistrar></s:Body></s:Envelope>"
6121 headers = {"Content-type": 'text/xml; charset="utf-8"'}
6122 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
6123 conn.request("POST", ctrlurl.path, msg, headers)
6124 resp = conn.getresponse()
6125 if resp.status != status:
6126 raise Exception("Unexpected HTTP response: %d (expected %d)" % (resp.status, status))
6127
6128 def test_ap_wps_adv_oom(dev, apdev):
6129 """WPS AP and advertisement OOM"""
6130 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
6131 hapd = add_ssdp_ap(apdev[0], ap_uuid)
6132
6133 with alloc_fail(hapd, 1, "=msearchreply_state_machine_start"):
6134 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
6135 no_recv=True)
6136 time.sleep(0.2)
6137
6138 with alloc_fail(hapd, 1, "eloop_register_timeout;msearchreply_state_machine_start"):
6139 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
6140 no_recv=True)
6141 time.sleep(0.2)
6142
6143 with alloc_fail(hapd, 1,
6144 "next_advertisement;advertisement_state_machine_stop"):
6145 hapd.disable()
6146
6147 with alloc_fail(hapd, 1, "ssdp_listener_start"):
6148 if "FAIL" not in hapd.request("ENABLE"):
6149 raise Exception("ENABLE succeeded during OOM")
6150
6151 def test_wps_config_methods(dev):
6152 """WPS config method update"""
6153 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
6154 wpas.interface_add("wlan5")
6155 if "OK" not in wpas.request("SET config_methods display label"):
6156 raise Exception("Failed to set config_methods")
6157 if wpas.request("GET config_methods").strip() != "display label":
6158 raise Exception("config_methods were not updated")
6159 if "OK" not in wpas.request("SET config_methods "):
6160 raise Exception("Failed to clear config_methods")
6161 if wpas.request("GET config_methods").strip() != "":
6162 raise Exception("config_methods were not cleared")
6163
6164 WPS_VENDOR_ID_WFA = 14122
6165 WPS_VENDOR_TYPE = 1
6166
6167 # EAP-WSC Op-Code values
6168 WSC_Start = 0x01
6169 WSC_ACK = 0x02
6170 WSC_NACK = 0x03
6171 WSC_MSG = 0x04
6172 WSC_Done = 0x05
6173 WSC_FRAG_ACK = 0x06
6174
6175 ATTR_AP_CHANNEL = 0x1001
6176 ATTR_ASSOC_STATE = 0x1002
6177 ATTR_AUTH_TYPE = 0x1003
6178 ATTR_AUTH_TYPE_FLAGS = 0x1004
6179 ATTR_AUTHENTICATOR = 0x1005
6180 ATTR_CONFIG_METHODS = 0x1008
6181 ATTR_CONFIG_ERROR = 0x1009
6182 ATTR_CONFIRM_URL4 = 0x100a
6183 ATTR_CONFIRM_URL6 = 0x100b
6184 ATTR_CONN_TYPE = 0x100c
6185 ATTR_CONN_TYPE_FLAGS = 0x100d
6186 ATTR_CRED = 0x100e
6187 ATTR_ENCR_TYPE = 0x100f
6188 ATTR_ENCR_TYPE_FLAGS = 0x1010
6189 ATTR_DEV_NAME = 0x1011
6190 ATTR_DEV_PASSWORD_ID = 0x1012
6191 ATTR_E_HASH1 = 0x1014
6192 ATTR_E_HASH2 = 0x1015
6193 ATTR_E_SNONCE1 = 0x1016
6194 ATTR_E_SNONCE2 = 0x1017
6195 ATTR_ENCR_SETTINGS = 0x1018
6196 ATTR_ENROLLEE_NONCE = 0x101a
6197 ATTR_FEATURE_ID = 0x101b
6198 ATTR_IDENTITY = 0x101c
6199 ATTR_IDENTITY_PROOF = 0x101d
6200 ATTR_KEY_WRAP_AUTH = 0x101e
6201 ATTR_KEY_ID = 0x101f
6202 ATTR_MAC_ADDR = 0x1020
6203 ATTR_MANUFACTURER = 0x1021
6204 ATTR_MSG_TYPE = 0x1022
6205 ATTR_MODEL_NAME = 0x1023
6206 ATTR_MODEL_NUMBER = 0x1024
6207 ATTR_NETWORK_INDEX = 0x1026
6208 ATTR_NETWORK_KEY = 0x1027
6209 ATTR_NETWORK_KEY_INDEX = 0x1028
6210 ATTR_NEW_DEVICE_NAME = 0x1029
6211 ATTR_NEW_PASSWORD = 0x102a
6212 ATTR_OOB_DEVICE_PASSWORD = 0x102c
6213 ATTR_OS_VERSION = 0x102d
6214 ATTR_POWER_LEVEL = 0x102f
6215 ATTR_PSK_CURRENT = 0x1030
6216 ATTR_PSK_MAX = 0x1031
6217 ATTR_PUBLIC_KEY = 0x1032
6218 ATTR_RADIO_ENABLE = 0x1033
6219 ATTR_REBOOT = 0x1034
6220 ATTR_REGISTRAR_CURRENT = 0x1035
6221 ATTR_REGISTRAR_ESTABLISHED = 0x1036
6222 ATTR_REGISTRAR_LIST = 0x1037
6223 ATTR_REGISTRAR_MAX = 0x1038
6224 ATTR_REGISTRAR_NONCE = 0x1039
6225 ATTR_REQUEST_TYPE = 0x103a
6226 ATTR_RESPONSE_TYPE = 0x103b
6227 ATTR_RF_BANDS = 0x103c
6228 ATTR_R_HASH1 = 0x103d
6229 ATTR_R_HASH2 = 0x103e
6230 ATTR_R_SNONCE1 = 0x103f
6231 ATTR_R_SNONCE2 = 0x1040
6232 ATTR_SELECTED_REGISTRAR = 0x1041
6233 ATTR_SERIAL_NUMBER = 0x1042
6234 ATTR_WPS_STATE = 0x1044
6235 ATTR_SSID = 0x1045
6236 ATTR_TOTAL_NETWORKS = 0x1046
6237 ATTR_UUID_E = 0x1047
6238 ATTR_UUID_R = 0x1048
6239 ATTR_VENDOR_EXT = 0x1049
6240 ATTR_VERSION = 0x104a
6241 ATTR_X509_CERT_REQ = 0x104b
6242 ATTR_X509_CERT = 0x104c
6243 ATTR_EAP_IDENTITY = 0x104d
6244 ATTR_MSG_COUNTER = 0x104e
6245 ATTR_PUBKEY_HASH = 0x104f
6246 ATTR_REKEY_KEY = 0x1050
6247 ATTR_KEY_LIFETIME = 0x1051
6248 ATTR_PERMITTED_CFG_METHODS = 0x1052
6249 ATTR_SELECTED_REGISTRAR_CONFIG_METHODS = 0x1053
6250 ATTR_PRIMARY_DEV_TYPE = 0x1054
6251 ATTR_SECONDARY_DEV_TYPE_LIST = 0x1055
6252 ATTR_PORTABLE_DEV = 0x1056
6253 ATTR_AP_SETUP_LOCKED = 0x1057
6254 ATTR_APPLICATION_EXT = 0x1058
6255 ATTR_EAP_TYPE = 0x1059
6256 ATTR_IV = 0x1060
6257 ATTR_KEY_PROVIDED_AUTO = 0x1061
6258 ATTR_802_1X_ENABLED = 0x1062
6259 ATTR_APPSESSIONKEY = 0x1063
6260 ATTR_WEPTRANSMITKEY = 0x1064
6261 ATTR_REQUESTED_DEV_TYPE = 0x106a
6262
6263 # Message Type
6264 WPS_Beacon = 0x01
6265 WPS_ProbeRequest = 0x02
6266 WPS_ProbeResponse = 0x03
6267 WPS_M1 = 0x04
6268 WPS_M2 = 0x05
6269 WPS_M2D = 0x06
6270 WPS_M3 = 0x07
6271 WPS_M4 = 0x08
6272 WPS_M5 = 0x09
6273 WPS_M6 = 0x0a
6274 WPS_M7 = 0x0b
6275 WPS_M8 = 0x0c
6276 WPS_WSC_ACK = 0x0d
6277 WPS_WSC_NACK = 0x0e
6278 WPS_WSC_DONE = 0x0f
6279
6280 def get_wsc_msg(dev):
6281 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
6282 if ev is None:
6283 raise Exception("Timeout on EAPOL-TX")
6284 data = binascii.unhexlify(ev.split(' ')[2])
6285 msg = {}
6286
6287 # Parse EAPOL header
6288 if len(data) < 4:
6289 raise Exception("No room for EAPOL header")
6290 version, type, length = struct.unpack('>BBH', data[0:4])
6291 msg['eapol_version'] = version
6292 msg['eapol_type'] = type
6293 msg['eapol_length'] = length
6294 data = data[4:]
6295 if length != len(data):
6296 raise Exception("EAPOL header length mismatch (%d != %d)" % (length, len(data)))
6297 if type != 0:
6298 raise Exception("Unexpected EAPOL header type: %d" % type)
6299
6300 # Parse EAP header
6301 if len(data) < 4:
6302 raise Exception("No room for EAP header")
6303 code, identifier, length = struct.unpack('>BBH', data[0:4])
6304 msg['eap_code'] = code
6305 msg['eap_identifier'] = identifier
6306 msg['eap_length'] = length
6307 data = data[4:]
6308 if msg['eapol_length'] != msg['eap_length']:
6309 raise Exception("EAP header length mismatch (%d != %d)" % (msg['eapol_length'], length))
6310
6311 # Parse EAP expanded header
6312 if len(data) < 1:
6313 raise Exception("No EAP type included")
6314 msg['eap_type'], = struct.unpack('B', data[0:1])
6315 data = data[1:]
6316
6317 if msg['eap_type'] == 254:
6318 if len(data) < 3 + 4:
6319 raise Exception("Truncated EAP expanded header")
6320 msg['eap_vendor_id'], msg['eap_vendor_type'] = struct.unpack('>LL', b'\x00' + data[0:7])
6321 data = data[7:]
6322 else:
6323 raise Exception("Unexpected EAP type")
6324
6325 if msg['eap_vendor_id'] != WPS_VENDOR_ID_WFA:
6326 raise Exception("Unexpected Vendor-Id")
6327 if msg['eap_vendor_type'] != WPS_VENDOR_TYPE:
6328 raise Exception("Unexpected Vendor-Type")
6329
6330 # Parse EAP-WSC header
6331 if len(data) < 2:
6332 raise Exception("Truncated EAP-WSC header")
6333 msg['wsc_opcode'], msg['wsc_flags'] = struct.unpack('BB', data[0:2])
6334 data = data[2:]
6335
6336 # Parse WSC attributes
6337 msg['raw_attrs'] = data
6338 attrs = {}
6339 while len(data) > 0:
6340 if len(data) < 4:
6341 raise Exception("Truncated attribute header")
6342 attr, length = struct.unpack('>HH', data[0:4])
6343 data = data[4:]
6344 if length > len(data):
6345 raise Exception("Truncated attribute 0x%04x" % attr)
6346 attrs[attr] = data[0:length]
6347 data = data[length:]
6348 msg['wsc_attrs'] = attrs
6349
6350 if ATTR_MSG_TYPE in attrs:
6351 msg['wsc_msg_type'], = struct.unpack('B', attrs[ATTR_MSG_TYPE])
6352
6353 return msg
6354
6355 def recv_wsc_msg(dev, opcode, msg_type):
6356 msg = get_wsc_msg(dev)
6357 if msg['wsc_opcode'] != opcode or msg['wsc_msg_type'] != msg_type:
6358 raise Exception("Unexpected Op-Code/MsgType")
6359 return msg, msg['wsc_attrs'], msg['raw_attrs']
6360
6361 def build_wsc_attr(attr, payload):
6362 _payload = payload if type(payload) == bytes else payload.encode()
6363 return struct.pack('>HH', attr, len(_payload)) + _payload
6364
6365 def build_attr_msg_type(msg_type):
6366 return build_wsc_attr(ATTR_MSG_TYPE, struct.pack('B', msg_type))
6367
6368 def build_eap_wsc(eap_code, eap_id, payload, opcode=WSC_MSG):
6369 length = 4 + 8 + 2 + len(payload)
6370 # EAPOL header
6371 msg = struct.pack('>BBH', 2, 0, length)
6372 # EAP header
6373 msg += struct.pack('>BBH', eap_code, eap_id, length)
6374 # EAP expanded header for EAP-WSC
6375 msg += struct.pack('B', 254)
6376 msg += struct.pack('>L', WPS_VENDOR_ID_WFA)[1:4]
6377 msg += struct.pack('>L', WPS_VENDOR_TYPE)
6378 # EAP-WSC header
6379 msg += struct.pack('BB', opcode, 0)
6380 # WSC attributes
6381 msg += payload
6382 return msg
6383
6384 def build_eap_success(eap_id):
6385 length = 4
6386 # EAPOL header
6387 msg = struct.pack('>BBH', 2, 0, length)
6388 # EAP header
6389 msg += struct.pack('>BBH', 3, eap_id, length)
6390 return msg
6391
6392 def build_eap_failure(eap_id):
6393 length = 4
6394 # EAPOL header
6395 msg = struct.pack('>BBH', 2, 0, length)
6396 # EAP header
6397 msg += struct.pack('>BBH', 4, eap_id, length)
6398 return msg
6399
6400 def send_wsc_msg(dev, src, msg):
6401 res = dev.request("EAPOL_RX " + src + " " + binascii.hexlify(msg).decode())
6402 if "OK" not in res:
6403 raise Exception("EAPOL_RX failed")
6404
6405 group_5_prime = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF
6406 group_5_generator = 2
6407
6408 def wsc_kdf(key, label, bits):
6409 result = b''
6410 i = 1
6411 while len(result) * 8 < bits:
6412 data = struct.pack('>L', i) + label.encode() + struct.pack('>L', bits)
6413 m = hmac.new(key, data, hashlib.sha256)
6414 result += m.digest()
6415 i += 1
6416 return result[0:bits // 8]
6417
6418 def wsc_keys(kdk):
6419 keys = wsc_kdf(kdk, "Wi-Fi Easy and Secure Key Derivation", 640)
6420 authkey = keys[0:32]
6421 keywrapkey = keys[32:48]
6422 emsk = keys[48:80]
6423 return authkey, keywrapkey, emsk
6424
6425 def wsc_dev_pw_half_psk(authkey, dev_pw):
6426 m = hmac.new(authkey, dev_pw.encode(), hashlib.sha256)
6427 return m.digest()[0:16]
6428
6429 def wsc_dev_pw_psk(authkey, dev_pw):
6430 dev_pw_1 = dev_pw[0:len(dev_pw) // 2]
6431 dev_pw_2 = dev_pw[len(dev_pw) // 2:]
6432 psk1 = wsc_dev_pw_half_psk(authkey, dev_pw_1)
6433 psk2 = wsc_dev_pw_half_psk(authkey, dev_pw_2)
6434 return psk1, psk2
6435
6436 def build_attr_authenticator(authkey, prev_msg, curr_msg):
6437 m = hmac.new(authkey, prev_msg + curr_msg, hashlib.sha256)
6438 auth = m.digest()[0:8]
6439 return build_wsc_attr(ATTR_AUTHENTICATOR, auth)
6440
6441 def build_attr_encr_settings(authkey, keywrapkey, data):
6442 m = hmac.new(authkey, data, hashlib.sha256)
6443 kwa = m.digest()[0:8]
6444 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6445 iv = 16*b'\x99'
6446 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6447 pad_len = 16 - len(data) % 16
6448 ps = pad_len * struct.pack('B', pad_len)
6449 data += ps
6450 wrapped = aes.encrypt(data)
6451 return build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6452
6453 def decrypt_attr_encr_settings(authkey, keywrapkey, data):
6454 if len(data) < 32 or len(data) % 16 != 0:
6455 raise Exception("Unexpected Encrypted Settings length: %d" % len(data))
6456 iv = data[0:16]
6457 encr = data[16:]
6458 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6459 decrypted = aes.decrypt(encr)
6460 pad_len, = struct.unpack('B', decrypted[-1:])
6461 if pad_len > len(decrypted):
6462 raise Exception("Invalid padding in Encrypted Settings")
6463 for i in range(-pad_len, -1):
6464 if decrypted[i] != decrypted[-1]:
6465 raise Exception("Invalid PS value in Encrypted Settings")
6466
6467 decrypted = decrypted[0:len(decrypted) - pad_len]
6468 if len(decrypted) < 12:
6469 raise Exception("Truncated Encrypted Settings plaintext")
6470 kwa = decrypted[-12:]
6471 attr, length = struct.unpack(">HH", kwa[0:4])
6472 if attr != ATTR_KEY_WRAP_AUTH or length != 8:
6473 raise Exception("Invalid KWA header")
6474 kwa = kwa[4:]
6475 decrypted = decrypted[0:len(decrypted) - 12]
6476
6477 m = hmac.new(authkey, decrypted, hashlib.sha256)
6478 calc_kwa = m.digest()[0:8]
6479 if kwa != calc_kwa:
6480 raise Exception("KWA mismatch")
6481
6482 return decrypted
6483
6484 def zeropad_str(val, pad_len):
6485 while len(val) < pad_len * 2:
6486 val = '0' + val
6487 return val
6488
6489 def wsc_dh_init():
6490 # For now, use a hardcoded private key. In theory, this is supposed to be
6491 # randomly selected.
6492 own_private = 0x123456789
6493 own_public = pow(group_5_generator, own_private, group_5_prime)
6494 pk = binascii.unhexlify(zeropad_str(format(own_public, '02x'), 192))
6495 return own_private, pk
6496
6497 def wsc_dh_kdf(peer_pk, own_private, mac_addr, e_nonce, r_nonce):
6498 peer_public = int(binascii.hexlify(peer_pk), 16)
6499 if peer_public < 2 or peer_public >= group_5_prime:
6500 raise Exception("Invalid peer public key")
6501 if pow(peer_public, (group_5_prime - 1) // 2, group_5_prime) != 1:
6502 raise Exception("Unexpected Legendre symbol for peer public key")
6503
6504 shared_secret = pow(peer_public, own_private, group_5_prime)
6505 ss = zeropad_str(format(shared_secret, "02x"), 192)
6506 logger.debug("DH shared secret: " + ss)
6507
6508 dhkey = hashlib.sha256(binascii.unhexlify(ss)).digest()
6509 logger.debug("DHKey: " + binascii.hexlify(dhkey).decode())
6510
6511 m = hmac.new(dhkey, e_nonce + mac_addr + r_nonce, hashlib.sha256)
6512 kdk = m.digest()
6513 logger.debug("KDK: " + binascii.hexlify(kdk).decode())
6514 authkey, keywrapkey, emsk = wsc_keys(kdk)
6515 logger.debug("AuthKey: " + binascii.hexlify(authkey).decode())
6516 logger.debug("KeyWrapKey: " + binascii.hexlify(keywrapkey).decode())
6517 logger.debug("EMSK: " + binascii.hexlify(emsk).decode())
6518 return authkey, keywrapkey
6519
6520 def wsc_dev_pw_hash(authkey, dev_pw, e_pk, r_pk):
6521 psk1, psk2 = wsc_dev_pw_psk(authkey, dev_pw)
6522 logger.debug("PSK1: " + binascii.hexlify(psk1).decode())
6523 logger.debug("PSK2: " + binascii.hexlify(psk2).decode())
6524
6525 # Note: Secret values are supposed to be random, but hardcoded values are
6526 # fine for testing.
6527 s1 = 16*b'\x77'
6528 m = hmac.new(authkey, s1 + psk1 + e_pk + r_pk, hashlib.sha256)
6529 hash1 = m.digest()
6530 logger.debug("Hash1: " + binascii.hexlify(hash1).decode())
6531
6532 s2 = 16*b'\x88'
6533 m = hmac.new(authkey, s2 + psk2 + e_pk + r_pk, hashlib.sha256)
6534 hash2 = m.digest()
6535 logger.debug("Hash2: " + binascii.hexlify(hash2).decode())
6536 return s1, s2, hash1, hash2
6537
6538 def build_m1(eap_id, uuid_e, mac_addr, e_nonce, e_pk,
6539 manufacturer='', model_name='', config_methods='\x00\x00'):
6540 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6541 attrs += build_attr_msg_type(WPS_M1)
6542 attrs += build_wsc_attr(ATTR_UUID_E, uuid_e)
6543 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6544 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6545 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, e_pk)
6546 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6547 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6548 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6549 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, config_methods)
6550 attrs += build_wsc_attr(ATTR_WPS_STATE, '\x00')
6551 attrs += build_wsc_attr(ATTR_MANUFACTURER, manufacturer)
6552 attrs += build_wsc_attr(ATTR_MODEL_NAME, model_name)
6553 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6554 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6555 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6556 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6557 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6558 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6559 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, '\x00\x00')
6560 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6561 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6562 m1 = build_eap_wsc(2, eap_id, attrs)
6563 return m1, attrs
6564
6565 def build_m2(authkey, m1, eap_id, e_nonce, r_nonce, uuid_r, r_pk,
6566 dev_pw_id='\x00\x00', eap_code=1):
6567 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6568 attrs += build_attr_msg_type(WPS_M2)
6569 if e_nonce:
6570 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6571 if r_nonce:
6572 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6573 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6574 if r_pk:
6575 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, r_pk)
6576 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6577 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6578 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6579 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6580 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6581 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6582 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6583 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6584 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6585 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6586 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6587 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6588 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6589 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6590 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6591 attrs += build_attr_authenticator(authkey, m1, attrs)
6592 m2 = build_eap_wsc(eap_code, eap_id, attrs)
6593 return m2, attrs
6594
6595 def build_m2d(m1, eap_id, e_nonce, r_nonce, uuid_r, dev_pw_id=None, eap_code=1):
6596 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6597 attrs += build_attr_msg_type(WPS_M2D)
6598 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6599 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6600 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6601 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6602 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6603 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6604 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6605 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6606 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6607 #attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6608 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6609 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6610 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6611 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6612 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6613 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6614 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6615 if dev_pw_id:
6616 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6617 m2d = build_eap_wsc(eap_code, eap_id, attrs)
6618 return m2d, attrs
6619
6620 def build_ack(eap_id, e_nonce, r_nonce, msg_type=WPS_WSC_ACK, eap_code=1):
6621 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6622 if msg_type is not None:
6623 attrs += build_attr_msg_type(msg_type)
6624 if e_nonce:
6625 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6626 if r_nonce:
6627 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6628 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_ACK)
6629 return msg, attrs
6630
6631 def build_nack(eap_id, e_nonce, r_nonce, config_error='\x00\x00',
6632 msg_type=WPS_WSC_NACK, eap_code=1):
6633 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6634 if msg_type is not None:
6635 attrs += build_attr_msg_type(msg_type)
6636 if e_nonce:
6637 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6638 if r_nonce:
6639 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6640 if config_error:
6641 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, config_error)
6642 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_NACK)
6643 return msg, attrs
6644
6645 def test_wps_ext(dev, apdev):
6646 """WPS against external implementation"""
6647 pin = "12345670"
6648 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6649 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6650 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6651
6652 logger.debug("Receive WSC/Start from AP")
6653 msg = get_wsc_msg(hapd)
6654 if msg['wsc_opcode'] != WSC_Start:
6655 raise Exception("Unexpected Op-Code for WSC/Start")
6656 wsc_start_id = msg['eap_identifier']
6657
6658 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6659 uuid_e = 16*b'\x11'
6660 e_nonce = 16*b'\x22'
6661 own_private, e_pk = wsc_dh_init()
6662
6663 logger.debug("Send M1 to AP")
6664 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
6665 e_nonce, e_pk)
6666 send_wsc_msg(hapd, addr, m1)
6667
6668 logger.debug("Receive M2 from AP")
6669 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
6670
6671 authkey, keywrapkey = wsc_dh_kdf(m2_attrs[ATTR_PUBLIC_KEY], own_private,
6672 mac_addr, e_nonce,
6673 m2_attrs[ATTR_REGISTRAR_NONCE])
6674 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk,
6675 m2_attrs[ATTR_PUBLIC_KEY])
6676
6677 logger.debug("Send M3 to AP")
6678 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6679 attrs += build_attr_msg_type(WPS_M3)
6680 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6681 m2_attrs[ATTR_REGISTRAR_NONCE])
6682 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
6683 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
6684 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
6685 raw_m3_attrs = attrs
6686 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6687 send_wsc_msg(hapd, addr, m3)
6688
6689 logger.debug("Receive M4 from AP")
6690 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
6691
6692 logger.debug("Send M5 to AP")
6693 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6694 attrs += build_attr_msg_type(WPS_M5)
6695 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6696 m2_attrs[ATTR_REGISTRAR_NONCE])
6697 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
6698 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6699 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
6700 raw_m5_attrs = attrs
6701 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6702 send_wsc_msg(hapd, addr, m5)
6703
6704 logger.debug("Receive M6 from AP")
6705 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
6706
6707 logger.debug("Send M7 to AP")
6708 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6709 attrs += build_attr_msg_type(WPS_M7)
6710 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6711 m2_attrs[ATTR_REGISTRAR_NONCE])
6712 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
6713 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6714 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
6715 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6716 raw_m7_attrs = attrs
6717 send_wsc_msg(hapd, addr, m7)
6718
6719 logger.debug("Receive M8 from AP")
6720 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
6721 m8_cred = decrypt_attr_encr_settings(authkey, keywrapkey,
6722 m8_attrs[ATTR_ENCR_SETTINGS])
6723 logger.debug("M8 Credential: " + binascii.hexlify(m8_cred).decode())
6724
6725 logger.debug("Prepare WSC_Done")
6726 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6727 attrs += build_attr_msg_type(WPS_WSC_DONE)
6728 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6729 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6730 m2_attrs[ATTR_REGISTRAR_NONCE])
6731 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
6732 # Do not send WSC_Done yet to allow exchangw with STA complete before the
6733 # AP disconnects.
6734
6735 uuid_r = 16*b'\x33'
6736 r_nonce = 16*b'\x44'
6737
6738 eap_id = wsc_start_id
6739 logger.debug("Send WSC/Start to STA")
6740 wsc_start = build_eap_wsc(1, eap_id, b'', opcode=WSC_Start)
6741 send_wsc_msg(dev[0], bssid, wsc_start)
6742 eap_id = (eap_id + 1) % 256
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
6747 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6748 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6749 r_nonce)
6750 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
6751 m1_attrs[ATTR_PUBLIC_KEY],
6752 e_pk)
6753
6754 logger.debug("Send M2 to STA")
6755 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6756 m1_attrs[ATTR_ENROLLEE_NONCE],
6757 r_nonce, uuid_r, e_pk)
6758 send_wsc_msg(dev[0], bssid, m2)
6759 eap_id = (eap_id + 1) % 256
6760
6761 logger.debug("Receive M3 from STA")
6762 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6763
6764 logger.debug("Send M4 to STA")
6765 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6766 attrs += build_attr_msg_type(WPS_M4)
6767 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6768 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6769 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6770 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6771 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6772 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6773 raw_m4_attrs = attrs
6774 m4 = build_eap_wsc(1, eap_id, attrs)
6775 send_wsc_msg(dev[0], bssid, m4)
6776 eap_id = (eap_id + 1) % 256
6777
6778 logger.debug("Receive M5 from STA")
6779 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6780
6781 logger.debug("Send M6 to STA")
6782 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6783 attrs += build_attr_msg_type(WPS_M6)
6784 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6785 m1_attrs[ATTR_ENROLLEE_NONCE])
6786 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6787 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6788 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6789 raw_m6_attrs = attrs
6790 m6 = build_eap_wsc(1, eap_id, attrs)
6791 send_wsc_msg(dev[0], bssid, m6)
6792 eap_id = (eap_id + 1) % 256
6793
6794 logger.debug("Receive M7 from STA")
6795 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6796
6797 logger.debug("Send M8 to STA")
6798 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6799 attrs += build_attr_msg_type(WPS_M8)
6800 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6801 m1_attrs[ATTR_ENROLLEE_NONCE])
6802 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6803 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6804 raw_m8_attrs = attrs
6805 m8 = build_eap_wsc(1, eap_id, attrs)
6806 send_wsc_msg(dev[0], bssid, m8)
6807 eap_id = (eap_id + 1) % 256
6808
6809 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=5)
6810 if ev is None:
6811 raise Exception("wpa_supplicant did not report credential")
6812
6813 logger.debug("Receive WSC_Done from STA")
6814 msg = get_wsc_msg(dev[0])
6815 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6816 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6817
6818 logger.debug("Send WSC_Done to AP")
6819 hapd.request("SET ext_eapol_frame_io 0")
6820 dev[0].request("SET ext_eapol_frame_io 0")
6821 send_wsc_msg(hapd, addr, wsc_done)
6822
6823 ev = hapd.wait_event(["WPS-REG-SUCCESS"], timeout=5)
6824 if ev is None:
6825 raise Exception("hostapd did not report WPS success")
6826
6827 dev[0].wait_connected()
6828
6829 def wps_start_kwa(dev, apdev):
6830 pin = "12345670"
6831 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6832 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6833 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6834 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6835
6836 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6837 uuid_r = 16*b'\x33'
6838 r_nonce = 16*b'\x44'
6839 own_private, e_pk = wsc_dh_init()
6840
6841 logger.debug("Receive M1 from STA")
6842 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6843 eap_id = (msg['eap_identifier'] + 1) % 256
6844
6845 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6846 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6847 r_nonce)
6848 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
6849 m1_attrs[ATTR_PUBLIC_KEY],
6850 e_pk)
6851
6852 logger.debug("Send M2 to STA")
6853 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6854 m1_attrs[ATTR_ENROLLEE_NONCE],
6855 r_nonce, uuid_r, e_pk)
6856 send_wsc_msg(dev[0], bssid, m2)
6857 eap_id = (eap_id + 1) % 256
6858
6859 logger.debug("Receive M3 from STA")
6860 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6861
6862 logger.debug("Send M4 to STA")
6863 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6864 attrs += build_attr_msg_type(WPS_M4)
6865 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6866 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6867 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6868
6869 return r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs
6870
6871 def wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id):
6872 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6873 m4 = build_eap_wsc(1, eap_id, attrs)
6874 send_wsc_msg(dev[0], bssid, m4)
6875 eap_id = (eap_id + 1) % 256
6876
6877 logger.debug("Receive M5 from STA")
6878 msg = get_wsc_msg(dev[0])
6879 if msg['wsc_opcode'] != WSC_NACK:
6880 raise Exception("Unexpected message - expected WSC_Nack")
6881
6882 dev[0].request("WPS_CANCEL")
6883 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6884 dev[0].wait_disconnected()
6885
6886 def test_wps_ext_kwa_proto_no_kwa(dev, apdev):
6887 """WPS and KWA error: No KWA attribute"""
6888 r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs = wps_start_kwa(dev, apdev)
6889 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6890 # Encrypted Settings without KWA
6891 iv = 16*b'\x99'
6892 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6893 pad_len = 16 - len(data) % 16
6894 ps = pad_len * struct.pack('B', pad_len)
6895 data += ps
6896 wrapped = aes.encrypt(data)
6897 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6898 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6899
6900 def test_wps_ext_kwa_proto_data_after_kwa(dev, apdev):
6901 """WPS and KWA error: Data after KWA"""
6902 r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs = wps_start_kwa(dev, apdev)
6903 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6904 # Encrypted Settings and data after KWA
6905 m = hmac.new(authkey, data, hashlib.sha256)
6906 kwa = m.digest()[0:8]
6907 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6908 data += build_wsc_attr(ATTR_VENDOR_EXT, "1234567890")
6909 iv = 16*b'\x99'
6910 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6911 pad_len = 16 - len(data) % 16
6912 ps = pad_len * struct.pack('B', pad_len)
6913 data += ps
6914 wrapped = aes.encrypt(data)
6915 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6916 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6917
6918 def test_wps_ext_kwa_proto_kwa_mismatch(dev, apdev):
6919 """WPS and KWA error: KWA mismatch"""
6920 r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs = wps_start_kwa(dev, apdev)
6921 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6922 # Encrypted Settings and KWA with incorrect value
6923 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, 8*'\x00')
6924 iv = 16*b'\x99'
6925 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6926 pad_len = 16 - len(data) % 16
6927 ps = pad_len * struct.pack('B', pad_len)
6928 data += ps
6929 wrapped = aes.encrypt(data)
6930 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6931 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6932
6933 def wps_run_cred_proto(dev, apdev, m8_cred, connect=False, no_connect=False):
6934 pin = "12345670"
6935 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6936 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6937 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6938 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6939
6940 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6941 uuid_r = 16*b'\x33'
6942 r_nonce = 16*b'\x44'
6943 own_private, e_pk = wsc_dh_init()
6944
6945 logger.debug("Receive M1 from STA")
6946 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6947 eap_id = (msg['eap_identifier'] + 1) % 256
6948
6949 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6950 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6951 r_nonce)
6952 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
6953 m1_attrs[ATTR_PUBLIC_KEY],
6954 e_pk)
6955
6956 logger.debug("Send M2 to STA")
6957 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6958 m1_attrs[ATTR_ENROLLEE_NONCE],
6959 r_nonce, uuid_r, e_pk)
6960 send_wsc_msg(dev[0], bssid, m2)
6961 eap_id = (eap_id + 1) % 256
6962
6963 logger.debug("Receive M3 from STA")
6964 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6965
6966 logger.debug("Send M4 to STA")
6967 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6968 attrs += build_attr_msg_type(WPS_M4)
6969 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6970 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6971 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6972 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6973 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6974 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6975 raw_m4_attrs = attrs
6976 m4 = build_eap_wsc(1, eap_id, attrs)
6977 send_wsc_msg(dev[0], bssid, m4)
6978 eap_id = (eap_id + 1) % 256
6979
6980 logger.debug("Receive M5 from STA")
6981 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6982
6983 logger.debug("Send M6 to STA")
6984 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6985 attrs += build_attr_msg_type(WPS_M6)
6986 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6987 m1_attrs[ATTR_ENROLLEE_NONCE])
6988 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6989 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6990 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6991 raw_m6_attrs = attrs
6992 m6 = build_eap_wsc(1, eap_id, attrs)
6993 send_wsc_msg(dev[0], bssid, m6)
6994 eap_id = (eap_id + 1) % 256
6995
6996 logger.debug("Receive M7 from STA")
6997 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6998
6999 logger.debug("Send M8 to STA")
7000 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7001 attrs += build_attr_msg_type(WPS_M8)
7002 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
7003 m1_attrs[ATTR_ENROLLEE_NONCE])
7004 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
7005 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7006 raw_m8_attrs = attrs
7007 m8 = build_eap_wsc(1, eap_id, attrs)
7008 send_wsc_msg(dev[0], bssid, m8)
7009 eap_id = (eap_id + 1) % 256
7010
7011 if no_connect:
7012 logger.debug("Receive WSC_Done from STA")
7013 msg = get_wsc_msg(dev[0])
7014 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
7015 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
7016
7017 hapd.request("SET ext_eapol_frame_io 0")
7018 dev[0].request("SET ext_eapol_frame_io 0")
7019
7020 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7021
7022 dev[0].wait_disconnected()
7023 dev[0].request("REMOVE_NETWORK all")
7024 elif connect:
7025 logger.debug("Receive WSC_Done from STA")
7026 msg = get_wsc_msg(dev[0])
7027 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
7028 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
7029
7030 hapd.request("SET ext_eapol_frame_io 0")
7031 dev[0].request("SET ext_eapol_frame_io 0")
7032
7033 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7034
7035 dev[0].wait_connected()
7036 else:
7037 # Verify STA NACK's the credential
7038 msg = get_wsc_msg(dev[0])
7039 if msg['wsc_opcode'] != WSC_NACK:
7040 raise Exception("Unexpected message - expected WSC_Nack")
7041 dev[0].request("WPS_CANCEL")
7042 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7043 dev[0].wait_disconnected()
7044
7045 def build_cred(nw_idx='\x01', ssid='test-wps-conf', auth_type='\x00\x20',
7046 encr_type='\x00\x08', nw_key="12345678",
7047 mac_addr='\x00\x00\x00\x00\x00\x00'):
7048 attrs = b''
7049 if nw_idx is not None:
7050 attrs += build_wsc_attr(ATTR_NETWORK_INDEX, nw_idx)
7051 if ssid is not None:
7052 attrs += build_wsc_attr(ATTR_SSID, ssid)
7053 if auth_type is not None:
7054 attrs += build_wsc_attr(ATTR_AUTH_TYPE, auth_type)
7055 if encr_type is not None:
7056 attrs += build_wsc_attr(ATTR_ENCR_TYPE, encr_type)
7057 if nw_key is not None:
7058 attrs += build_wsc_attr(ATTR_NETWORK_KEY, nw_key)
7059 if mac_addr is not None:
7060 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
7061 return build_wsc_attr(ATTR_CRED, attrs)
7062
7063 def test_wps_ext_cred_proto_success(dev, apdev):
7064 """WPS and Credential: success"""
7065 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7066 m8_cred = build_cred(mac_addr=mac_addr)
7067 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
7068
7069 def test_wps_ext_cred_proto_mac_addr_mismatch(dev, apdev):
7070 """WPS and Credential: MAC Address mismatch"""
7071 m8_cred = build_cred()
7072 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
7073
7074 def test_wps_ext_cred_proto_zero_padding(dev, apdev):
7075 """WPS and Credential: zeropadded attributes"""
7076 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7077 m8_cred = build_cred(mac_addr=mac_addr, ssid='test-wps-conf\x00',
7078 nw_key="12345678\x00")
7079 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
7080
7081 def test_wps_ext_cred_proto_ssid_missing(dev, apdev):
7082 """WPS and Credential: SSID missing"""
7083 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7084 m8_cred = build_cred(mac_addr=mac_addr, ssid=None)
7085 wps_run_cred_proto(dev, apdev, m8_cred)
7086
7087 def test_wps_ext_cred_proto_ssid_zero_len(dev, apdev):
7088 """WPS and Credential: Zero-length SSID"""
7089 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7090 m8_cred = build_cred(mac_addr=mac_addr, ssid="")
7091 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
7092
7093 def test_wps_ext_cred_proto_auth_type_missing(dev, apdev):
7094 """WPS and Credential: Auth Type missing"""
7095 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7096 m8_cred = build_cred(mac_addr=mac_addr, auth_type=None)
7097 wps_run_cred_proto(dev, apdev, m8_cred)
7098
7099 def test_wps_ext_cred_proto_encr_type_missing(dev, apdev):
7100 """WPS and Credential: Encr Type missing"""
7101 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7102 m8_cred = build_cred(mac_addr=mac_addr, encr_type=None)
7103 wps_run_cred_proto(dev, apdev, m8_cred)
7104
7105 def test_wps_ext_cred_proto_network_key_missing(dev, apdev):
7106 """WPS and Credential: Network Key missing"""
7107 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7108 m8_cred = build_cred(mac_addr=mac_addr, nw_key=None)
7109 wps_run_cred_proto(dev, apdev, m8_cred)
7110
7111 def test_wps_ext_cred_proto_network_key_missing_open(dev, apdev):
7112 """WPS and Credential: Network Key missing (open)"""
7113 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7114 m8_cred = build_cred(mac_addr=mac_addr, auth_type='\x00\x01',
7115 encr_type='\x00\x01', nw_key=None, ssid="foo")
7116 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
7117
7118 def test_wps_ext_cred_proto_mac_addr_missing(dev, apdev):
7119 """WPS and Credential: MAC Address missing"""
7120 m8_cred = build_cred(mac_addr=None)
7121 wps_run_cred_proto(dev, apdev, m8_cred)
7122
7123 def test_wps_ext_cred_proto_invalid_encr_type(dev, apdev):
7124 """WPS and Credential: Invalid Encr Type"""
7125 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7126 m8_cred = build_cred(mac_addr=mac_addr, encr_type='\x00\x00')
7127 wps_run_cred_proto(dev, apdev, m8_cred)
7128
7129 def test_wps_ext_cred_proto_missing_cred(dev, apdev):
7130 """WPS and Credential: Missing Credential"""
7131 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7132 m8_cred = b''
7133 wps_run_cred_proto(dev, apdev, m8_cred)
7134
7135 def test_wps_ext_proto_m2_no_public_key(dev, apdev):
7136 """WPS and no Public Key in M2"""
7137 pin = "12345670"
7138 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7139 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7140 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7141 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7142
7143 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7144 uuid_r = 16*b'\x33'
7145 r_nonce = 16*b'\x44'
7146 own_private, e_pk = wsc_dh_init()
7147
7148 logger.debug("Receive M1 from STA")
7149 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7150 eap_id = (msg['eap_identifier'] + 1) % 256
7151
7152 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7153 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7154 r_nonce)
7155 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7156 m1_attrs[ATTR_PUBLIC_KEY],
7157 e_pk)
7158
7159 logger.debug("Send M2 to STA")
7160 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7161 m1_attrs[ATTR_ENROLLEE_NONCE],
7162 r_nonce, uuid_r, None)
7163 send_wsc_msg(dev[0], bssid, m2)
7164 eap_id = (eap_id + 1) % 256
7165
7166 # Verify STA NACK's the credential
7167 msg = get_wsc_msg(dev[0])
7168 if msg['wsc_opcode'] != WSC_NACK:
7169 raise Exception("Unexpected message - expected WSC_Nack")
7170 dev[0].request("WPS_CANCEL")
7171 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7172 dev[0].wait_disconnected()
7173
7174 def test_wps_ext_proto_m2_invalid_public_key(dev, apdev):
7175 """WPS and invalid Public Key in M2"""
7176 pin = "12345670"
7177 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7178 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7179 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7180 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7181
7182 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7183 uuid_r = 16*b'\x33'
7184 r_nonce = 16*b'\x44'
7185 own_private, e_pk = wsc_dh_init()
7186
7187 logger.debug("Receive M1 from STA")
7188 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7189 eap_id = (msg['eap_identifier'] + 1) % 256
7190
7191 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7192 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7193 r_nonce)
7194 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7195 m1_attrs[ATTR_PUBLIC_KEY],
7196 e_pk)
7197
7198 logger.debug("Send M2 to STA")
7199 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7200 m1_attrs[ATTR_ENROLLEE_NONCE],
7201 r_nonce, uuid_r, 192*b'\xff')
7202 send_wsc_msg(dev[0], bssid, m2)
7203 eap_id = (eap_id + 1) % 256
7204
7205 # Verify STA NACK's the credential
7206 msg = get_wsc_msg(dev[0])
7207 if msg['wsc_opcode'] != WSC_NACK:
7208 raise Exception("Unexpected message - expected WSC_Nack")
7209 dev[0].request("WPS_CANCEL")
7210 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7211 dev[0].wait_disconnected()
7212
7213 def test_wps_ext_proto_m2_public_key_oom(dev, apdev):
7214 """WPS and Public Key OOM in M2"""
7215 pin = "12345670"
7216 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7217 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7218 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7219 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7220
7221 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7222 uuid_r = 16*b'\x33'
7223 r_nonce = 16*b'\x44'
7224 own_private, e_pk = wsc_dh_init()
7225
7226 logger.debug("Receive M1 from STA")
7227 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7228 eap_id = (msg['eap_identifier'] + 1) % 256
7229
7230 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7231 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7232 r_nonce)
7233 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7234 m1_attrs[ATTR_PUBLIC_KEY],
7235 e_pk)
7236
7237 logger.debug("Send M2 to STA")
7238 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7239 m1_attrs[ATTR_ENROLLEE_NONCE],
7240 r_nonce, uuid_r, e_pk)
7241 with alloc_fail(dev[0], 1, "wpabuf_alloc_copy;wps_process_pubkey"):
7242 send_wsc_msg(dev[0], bssid, m2)
7243 eap_id = (eap_id + 1) % 256
7244
7245 # Verify STA NACK's the credential
7246 msg = get_wsc_msg(dev[0])
7247 if msg['wsc_opcode'] != WSC_NACK:
7248 raise Exception("Unexpected message - expected WSC_Nack")
7249 dev[0].request("WPS_CANCEL")
7250 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7251 dev[0].wait_disconnected()
7252
7253 def test_wps_ext_proto_nack_m3(dev, apdev):
7254 """WPS and NACK M3"""
7255 pin = "12345670"
7256 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7257 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7258 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7259 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7260
7261 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7262 uuid_r = 16*b'\x33'
7263 r_nonce = 16*b'\x44'
7264 own_private, e_pk = wsc_dh_init()
7265
7266 logger.debug("Receive M1 from STA")
7267 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7268 eap_id = (msg['eap_identifier'] + 1) % 256
7269
7270 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7271 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7272 r_nonce)
7273 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7274 m1_attrs[ATTR_PUBLIC_KEY],
7275 e_pk)
7276
7277 logger.debug("Send M2 to STA")
7278 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7279 m1_attrs[ATTR_ENROLLEE_NONCE],
7280 r_nonce, uuid_r, e_pk)
7281 send_wsc_msg(dev[0], bssid, m2)
7282 eap_id = (eap_id + 1) % 256
7283
7284 logger.debug("Receive M3 from STA")
7285 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7286
7287 logger.debug("Send NACK to STA")
7288 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7289 r_nonce, config_error='\x01\x23')
7290 send_wsc_msg(dev[0], bssid, msg)
7291 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7292 if ev is None:
7293 raise Exception("Failure not reported")
7294 if "msg=7 config_error=291" not in ev:
7295 raise Exception("Unexpected failure reason: " + ev)
7296
7297 def test_wps_ext_proto_nack_m5(dev, apdev):
7298 """WPS and NACK M5"""
7299 pin = "12345670"
7300 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7301 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7302 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7303 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7304
7305 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7306 uuid_r = 16*b'\x33'
7307 r_nonce = 16*b'\x44'
7308 own_private, e_pk = wsc_dh_init()
7309
7310 logger.debug("Receive M1 from STA")
7311 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7312 eap_id = (msg['eap_identifier'] + 1) % 256
7313
7314 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7315 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7316 r_nonce)
7317 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7318 m1_attrs[ATTR_PUBLIC_KEY],
7319 e_pk)
7320
7321 logger.debug("Send M2 to STA")
7322 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7323 m1_attrs[ATTR_ENROLLEE_NONCE],
7324 r_nonce, uuid_r, e_pk)
7325 send_wsc_msg(dev[0], bssid, m2)
7326 eap_id = (eap_id + 1) % 256
7327
7328 logger.debug("Receive M3 from STA")
7329 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7330
7331 logger.debug("Send M4 to STA")
7332 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7333 attrs += build_attr_msg_type(WPS_M4)
7334 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7335 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7336 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7337 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7338 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7339 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7340 raw_m4_attrs = attrs
7341 m4 = build_eap_wsc(1, eap_id, attrs)
7342 send_wsc_msg(dev[0], bssid, m4)
7343 eap_id = (eap_id + 1) % 256
7344
7345 logger.debug("Receive M5 from STA")
7346 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7347
7348 logger.debug("Send NACK to STA")
7349 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7350 r_nonce, config_error='\x01\x24')
7351 send_wsc_msg(dev[0], bssid, msg)
7352 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7353 if ev is None:
7354 raise Exception("Failure not reported")
7355 if "msg=9 config_error=292" not in ev:
7356 raise Exception("Unexpected failure reason: " + ev)
7357
7358 def wps_nack_m3(dev, apdev):
7359 pin = "00000000"
7360 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
7361 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7362 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7363 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7364
7365 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7366 uuid_r = 16*b'\x33'
7367 r_nonce = 16*b'\x44'
7368 own_private, e_pk = wsc_dh_init()
7369
7370 logger.debug("Receive M1 from STA")
7371 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7372 eap_id = (msg['eap_identifier'] + 1) % 256
7373
7374 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7375 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7376 r_nonce)
7377 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7378 m1_attrs[ATTR_PUBLIC_KEY],
7379 e_pk)
7380
7381 logger.debug("Send M2 to STA")
7382 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7383 m1_attrs[ATTR_ENROLLEE_NONCE],
7384 r_nonce, uuid_r, e_pk, dev_pw_id='\x00\x04')
7385 send_wsc_msg(dev[0], bssid, m2)
7386 eap_id = (eap_id + 1) % 256
7387
7388 logger.debug("Receive M3 from STA")
7389 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7390 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid
7391
7392 def test_wps_ext_proto_nack_m3_no_config_error(dev, apdev):
7393 """WPS and NACK M3 missing Config Error"""
7394 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7395 logger.debug("Send NACK to STA")
7396 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, config_error=None)
7397 send_wsc_msg(dev[0], bssid, msg)
7398 dev[0].request("WPS_CANCEL")
7399 dev[0].wait_disconnected()
7400 dev[0].flush_scan_cache()
7401
7402 def test_wps_ext_proto_nack_m3_no_e_nonce(dev, apdev):
7403 """WPS and NACK M3 missing E-Nonce"""
7404 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7405 logger.debug("Send NACK to STA")
7406 msg, attrs = build_nack(eap_id, None, r_nonce)
7407 send_wsc_msg(dev[0], bssid, msg)
7408 dev[0].request("WPS_CANCEL")
7409 dev[0].wait_disconnected()
7410 dev[0].flush_scan_cache()
7411
7412 def test_wps_ext_proto_nack_m3_e_nonce_mismatch(dev, apdev):
7413 """WPS and NACK M3 E-Nonce mismatch"""
7414 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7415 logger.debug("Send NACK to STA")
7416 msg, attrs = build_nack(eap_id, 16*'\x00', r_nonce)
7417 send_wsc_msg(dev[0], bssid, msg)
7418 dev[0].request("WPS_CANCEL")
7419 dev[0].wait_disconnected()
7420 dev[0].flush_scan_cache()
7421
7422 def test_wps_ext_proto_nack_m3_no_r_nonce(dev, apdev):
7423 """WPS and NACK M3 missing R-Nonce"""
7424 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7425 logger.debug("Send NACK to STA")
7426 msg, attrs = build_nack(eap_id, e_nonce, None)
7427 send_wsc_msg(dev[0], bssid, msg)
7428 dev[0].request("WPS_CANCEL")
7429 dev[0].wait_disconnected()
7430 dev[0].flush_scan_cache()
7431
7432 def test_wps_ext_proto_nack_m3_r_nonce_mismatch(dev, apdev):
7433 """WPS and NACK M3 R-Nonce mismatch"""
7434 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7435 logger.debug("Send NACK to STA")
7436 msg, attrs = build_nack(eap_id, e_nonce, 16*'\x00')
7437 send_wsc_msg(dev[0], bssid, msg)
7438 dev[0].request("WPS_CANCEL")
7439 dev[0].wait_disconnected()
7440 dev[0].flush_scan_cache()
7441
7442 def test_wps_ext_proto_nack_m3_no_msg_type(dev, apdev):
7443 """WPS and NACK M3 no Message Type"""
7444 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7445 logger.debug("Send NACK to STA")
7446 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=None)
7447 send_wsc_msg(dev[0], bssid, msg)
7448 dev[0].request("WPS_CANCEL")
7449 dev[0].wait_disconnected()
7450 dev[0].flush_scan_cache()
7451
7452 def test_wps_ext_proto_nack_m3_invalid_msg_type(dev, apdev):
7453 """WPS and NACK M3 invalid Message Type"""
7454 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7455 logger.debug("Send NACK to STA")
7456 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=123)
7457 send_wsc_msg(dev[0], bssid, msg)
7458 dev[0].request("WPS_CANCEL")
7459 dev[0].wait_disconnected()
7460 dev[0].flush_scan_cache()
7461
7462 def test_wps_ext_proto_nack_m3_invalid_attr(dev, apdev):
7463 """WPS and NACK M3 invalid attribute"""
7464 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7465 logger.debug("Send NACK to STA")
7466 attrs = b'\x10\x10\x00'
7467 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_NACK)
7468 send_wsc_msg(dev[0], bssid, msg)
7469 dev[0].request("WPS_CANCEL")
7470 dev[0].wait_disconnected()
7471 dev[0].flush_scan_cache()
7472
7473 def test_wps_ext_proto_ack_m3_no_e_nonce(dev, apdev):
7474 """WPS and ACK M3 missing E-Nonce"""
7475 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7476 logger.debug("Send NACK to STA")
7477 msg, attrs = build_ack(eap_id, None, r_nonce)
7478 send_wsc_msg(dev[0], bssid, msg)
7479 dev[0].request("WPS_CANCEL")
7480 dev[0].wait_disconnected()
7481 dev[0].flush_scan_cache()
7482
7483 def test_wps_ext_proto_ack_m3_e_nonce_mismatch(dev, apdev):
7484 """WPS and ACK M3 E-Nonce mismatch"""
7485 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7486 logger.debug("Send NACK to STA")
7487 msg, attrs = build_ack(eap_id, 16*'\x00', r_nonce)
7488 send_wsc_msg(dev[0], bssid, msg)
7489 dev[0].request("WPS_CANCEL")
7490 dev[0].wait_disconnected()
7491 dev[0].flush_scan_cache()
7492
7493 def test_wps_ext_proto_ack_m3_no_r_nonce(dev, apdev):
7494 """WPS and ACK M3 missing R-Nonce"""
7495 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7496 logger.debug("Send NACK to STA")
7497 msg, attrs = build_ack(eap_id, e_nonce, None)
7498 send_wsc_msg(dev[0], bssid, msg)
7499 dev[0].request("WPS_CANCEL")
7500 dev[0].wait_disconnected()
7501 dev[0].flush_scan_cache()
7502
7503 def test_wps_ext_proto_ack_m3_r_nonce_mismatch(dev, apdev):
7504 """WPS and ACK M3 R-Nonce mismatch"""
7505 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7506 logger.debug("Send NACK to STA")
7507 msg, attrs = build_ack(eap_id, e_nonce, 16*'\x00')
7508 send_wsc_msg(dev[0], bssid, msg)
7509 dev[0].request("WPS_CANCEL")
7510 dev[0].wait_disconnected()
7511 dev[0].flush_scan_cache()
7512
7513 def test_wps_ext_proto_ack_m3_no_msg_type(dev, apdev):
7514 """WPS and ACK M3 no Message Type"""
7515 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7516 logger.debug("Send NACK to STA")
7517 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=None)
7518 send_wsc_msg(dev[0], bssid, msg)
7519 dev[0].request("WPS_CANCEL")
7520 dev[0].wait_disconnected()
7521 dev[0].flush_scan_cache()
7522
7523 def test_wps_ext_proto_ack_m3_invalid_msg_type(dev, apdev):
7524 """WPS and ACK M3 invalid Message Type"""
7525 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7526 logger.debug("Send NACK to STA")
7527 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=123)
7528 send_wsc_msg(dev[0], bssid, msg)
7529 dev[0].request("WPS_CANCEL")
7530 dev[0].wait_disconnected()
7531 dev[0].flush_scan_cache()
7532
7533 def test_wps_ext_proto_ack_m3_invalid_attr(dev, apdev):
7534 """WPS and ACK M3 invalid attribute"""
7535 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7536 logger.debug("Send ACK to STA")
7537 attrs = b'\x10\x10\x00'
7538 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_ACK)
7539 send_wsc_msg(dev[0], bssid, msg)
7540 dev[0].request("WPS_CANCEL")
7541 dev[0].wait_disconnected()
7542 dev[0].flush_scan_cache()
7543
7544 def test_wps_ext_proto_ack_m3(dev, apdev):
7545 """WPS and ACK M3"""
7546 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7547 logger.debug("Send ACK to STA")
7548 msg, attrs = build_ack(eap_id, e_nonce, r_nonce)
7549 send_wsc_msg(dev[0], bssid, msg)
7550 dev[0].request("WPS_CANCEL")
7551 dev[0].wait_disconnected()
7552 dev[0].flush_scan_cache()
7553
7554 def wps_to_m3_helper(dev, apdev):
7555 pin = "12345670"
7556 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7557 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7558 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7559 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7560
7561 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7562 uuid_r = 16*b'\x33'
7563 r_nonce = 16*b'\x44'
7564 own_private, e_pk = wsc_dh_init()
7565
7566 logger.debug("Receive M1 from STA")
7567 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7568 eap_id = (msg['eap_identifier'] + 1) % 256
7569
7570 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7571 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7572 r_nonce)
7573 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7574 m1_attrs[ATTR_PUBLIC_KEY],
7575 e_pk)
7576
7577 logger.debug("Send M2 to STA")
7578 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7579 m1_attrs[ATTR_ENROLLEE_NONCE],
7580 r_nonce, uuid_r, e_pk)
7581 send_wsc_msg(dev[0], bssid, m2)
7582 eap_id = (eap_id + 1) % 256
7583
7584 logger.debug("Receive M3 from STA")
7585 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7586 return eap_id, m1_attrs, r_nonce, bssid, r_hash1, r_hash2, r_s1, r_s2, raw_m3_attrs, authkey, keywrapkey
7587
7588 def wps_to_m3(dev, apdev):
7589 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)
7590 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s1, raw_m3_attrs, authkey, keywrapkey
7591
7592 def wps_to_m5(dev, apdev):
7593 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)
7594
7595 logger.debug("Send M4 to STA")
7596 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7597 attrs += build_attr_msg_type(WPS_M4)
7598 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7599 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7600 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7601 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7602 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7603 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7604 raw_m4_attrs = attrs
7605 m4 = build_eap_wsc(1, eap_id, attrs)
7606 send_wsc_msg(dev[0], bssid, m4)
7607 eap_id = (eap_id + 1) % 256
7608
7609 logger.debug("Receive M5 from STA")
7610 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7611
7612 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s2, raw_m5_attrs, authkey, keywrapkey
7613
7614 def test_wps_ext_proto_m4_missing_r_hash1(dev, apdev):
7615 """WPS and no R-Hash1 in M4"""
7616 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7617
7618 logger.debug("Send M4 to STA")
7619 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7620 attrs += build_attr_msg_type(WPS_M4)
7621 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7622 #attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7623 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7624 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7625 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7626 attrs += build_attr_authenticator(authkey, m3, attrs)
7627 m4 = build_eap_wsc(1, eap_id, attrs)
7628 send_wsc_msg(dev[0], bssid, m4)
7629 eap_id = (eap_id + 1) % 256
7630
7631 logger.debug("Receive M5 (NACK) from STA")
7632 msg = get_wsc_msg(dev[0])
7633 if msg['wsc_opcode'] != WSC_NACK:
7634 raise Exception("Unexpected message - expected WSC_Nack")
7635
7636 dev[0].request("WPS_CANCEL")
7637 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7638 dev[0].wait_disconnected()
7639
7640 def test_wps_ext_proto_m4_missing_r_hash2(dev, apdev):
7641 """WPS and no R-Hash2 in M4"""
7642 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7643
7644 logger.debug("Send M4 to STA")
7645 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7646 attrs += build_attr_msg_type(WPS_M4)
7647 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7648 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7649 #attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7650 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7651 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7652 attrs += build_attr_authenticator(authkey, m3, attrs)
7653 m4 = build_eap_wsc(1, eap_id, attrs)
7654 send_wsc_msg(dev[0], bssid, m4)
7655 eap_id = (eap_id + 1) % 256
7656
7657 logger.debug("Receive M5 (NACK) from STA")
7658 msg = get_wsc_msg(dev[0])
7659 if msg['wsc_opcode'] != WSC_NACK:
7660 raise Exception("Unexpected message - expected WSC_Nack")
7661
7662 dev[0].request("WPS_CANCEL")
7663 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7664 dev[0].wait_disconnected()
7665
7666 def test_wps_ext_proto_m4_missing_r_snonce1(dev, apdev):
7667 """WPS and no R-SNonce1 in M4"""
7668 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7669
7670 logger.debug("Send M4 to STA")
7671 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7672 attrs += build_attr_msg_type(WPS_M4)
7673 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7674 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7675 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7676 #data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7677 data = b''
7678 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7679 attrs += build_attr_authenticator(authkey, m3, attrs)
7680 m4 = build_eap_wsc(1, eap_id, attrs)
7681 send_wsc_msg(dev[0], bssid, m4)
7682 eap_id = (eap_id + 1) % 256
7683
7684 logger.debug("Receive M5 (NACK) from STA")
7685 msg = get_wsc_msg(dev[0])
7686 if msg['wsc_opcode'] != WSC_NACK:
7687 raise Exception("Unexpected message - expected WSC_Nack")
7688
7689 dev[0].request("WPS_CANCEL")
7690 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7691 dev[0].wait_disconnected()
7692
7693 def test_wps_ext_proto_m4_invalid_pad_string(dev, apdev):
7694 """WPS and invalid pad string in M4"""
7695 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7696
7697 logger.debug("Send M4 to STA")
7698 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7699 attrs += build_attr_msg_type(WPS_M4)
7700 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7701 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7702 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7703 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7704
7705 m = hmac.new(authkey, data, hashlib.sha256)
7706 kwa = m.digest()[0:8]
7707 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7708 iv = 16*b'\x99'
7709 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7710 pad_len = 16 - len(data) % 16
7711 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', pad_len - 1)
7712 data += ps
7713 wrapped = aes.encrypt(data)
7714 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7715
7716 attrs += build_attr_authenticator(authkey, m3, attrs)
7717 m4 = build_eap_wsc(1, eap_id, attrs)
7718 send_wsc_msg(dev[0], bssid, m4)
7719 eap_id = (eap_id + 1) % 256
7720
7721 logger.debug("Receive M5 (NACK) from STA")
7722 msg = get_wsc_msg(dev[0])
7723 if msg['wsc_opcode'] != WSC_NACK:
7724 raise Exception("Unexpected message - expected WSC_Nack")
7725
7726 dev[0].request("WPS_CANCEL")
7727 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7728 dev[0].wait_disconnected()
7729
7730 def test_wps_ext_proto_m4_invalid_pad_value(dev, apdev):
7731 """WPS and invalid pad value in M4"""
7732 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7733
7734 logger.debug("Send M4 to STA")
7735 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7736 attrs += build_attr_msg_type(WPS_M4)
7737 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7738 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7739 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7740 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7741
7742 m = hmac.new(authkey, data, hashlib.sha256)
7743 kwa = m.digest()[0:8]
7744 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7745 iv = 16*b'\x99'
7746 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7747 pad_len = 16 - len(data) % 16
7748 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', 255)
7749 data += ps
7750 wrapped = aes.encrypt(data)
7751 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7752
7753 attrs += build_attr_authenticator(authkey, m3, attrs)
7754 m4 = build_eap_wsc(1, eap_id, attrs)
7755 send_wsc_msg(dev[0], bssid, m4)
7756 eap_id = (eap_id + 1) % 256
7757
7758 logger.debug("Receive M5 (NACK) from STA")
7759 msg = get_wsc_msg(dev[0])
7760 if msg['wsc_opcode'] != WSC_NACK:
7761 raise Exception("Unexpected message - expected WSC_Nack")
7762
7763 dev[0].request("WPS_CANCEL")
7764 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7765 dev[0].wait_disconnected()
7766
7767 def test_wps_ext_proto_m4_no_encr_settings(dev, apdev):
7768 """WPS and no Encr Settings in M4"""
7769 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7770
7771 logger.debug("Send M4 to STA")
7772 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7773 attrs += build_attr_msg_type(WPS_M4)
7774 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7775 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7776 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7777 attrs += build_attr_authenticator(authkey, m3, attrs)
7778 m4 = build_eap_wsc(1, eap_id, attrs)
7779 send_wsc_msg(dev[0], bssid, m4)
7780 eap_id = (eap_id + 1) % 256
7781
7782 logger.debug("Receive M5 (NACK) from STA")
7783 msg = get_wsc_msg(dev[0])
7784 if msg['wsc_opcode'] != WSC_NACK:
7785 raise Exception("Unexpected message - expected WSC_Nack")
7786
7787 dev[0].request("WPS_CANCEL")
7788 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7789 dev[0].wait_disconnected()
7790
7791 def test_wps_ext_proto_m6_missing_r_snonce2(dev, apdev):
7792 """WPS and no R-SNonce2 in M6"""
7793 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7794
7795 logger.debug("Send M6 to STA")
7796 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7797 attrs += build_attr_msg_type(WPS_M6)
7798 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7799 #data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7800 data = b''
7801 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7802 attrs += build_attr_authenticator(authkey, m5, attrs)
7803 m6 = build_eap_wsc(1, eap_id, attrs)
7804 send_wsc_msg(dev[0], bssid, m6)
7805 eap_id = (eap_id + 1) % 256
7806
7807 logger.debug("Receive M7 (NACK) from STA")
7808 msg = get_wsc_msg(dev[0])
7809 if msg['wsc_opcode'] != WSC_NACK:
7810 raise Exception("Unexpected message - expected WSC_Nack")
7811
7812 dev[0].request("WPS_CANCEL")
7813 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7814 dev[0].wait_disconnected()
7815
7816 def test_wps_ext_proto_m6_no_encr_settings(dev, apdev):
7817 """WPS and no Encr Settings in M6"""
7818 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7819
7820 logger.debug("Send M6 to STA")
7821 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7822 attrs += build_attr_msg_type(WPS_M6)
7823 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7824 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7825 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7826 attrs += build_attr_authenticator(authkey, m5, attrs)
7827 m6 = build_eap_wsc(1, eap_id, attrs)
7828 send_wsc_msg(dev[0], bssid, m6)
7829 eap_id = (eap_id + 1) % 256
7830
7831 logger.debug("Receive M7 (NACK) from STA")
7832 msg = get_wsc_msg(dev[0])
7833 if msg['wsc_opcode'] != WSC_NACK:
7834 raise Exception("Unexpected message - expected WSC_Nack")
7835
7836 dev[0].request("WPS_CANCEL")
7837 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7838 dev[0].wait_disconnected()
7839
7840 def test_wps_ext_proto_m8_no_encr_settings(dev, apdev):
7841 """WPS and no Encr Settings in M6"""
7842 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7843
7844 logger.debug("Send M6 to STA")
7845 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7846 attrs += build_attr_msg_type(WPS_M6)
7847 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7848 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7849 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7850 attrs += build_attr_authenticator(authkey, m5, attrs)
7851 raw_m6_attrs = attrs
7852 m6 = build_eap_wsc(1, eap_id, attrs)
7853 send_wsc_msg(dev[0], bssid, m6)
7854 eap_id = (eap_id + 1) % 256
7855
7856 logger.debug("Receive M7 from STA")
7857 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
7858
7859 logger.debug("Send M8 to STA")
7860 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7861 attrs += build_attr_msg_type(WPS_M8)
7862 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7863 #attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
7864 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7865 raw_m8_attrs = attrs
7866 m8 = build_eap_wsc(1, eap_id, attrs)
7867 send_wsc_msg(dev[0], bssid, m8)
7868
7869 logger.debug("Receive WSC_Done (NACK) from STA")
7870 msg = get_wsc_msg(dev[0])
7871 if msg['wsc_opcode'] != WSC_NACK:
7872 raise Exception("Unexpected message - expected WSC_Nack")
7873
7874 dev[0].request("WPS_CANCEL")
7875 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7876 dev[0].wait_disconnected()
7877
7878 def wps_start_ext_reg(apdev, dev):
7879 addr = dev.own_addr()
7880 bssid = apdev['bssid']
7881 ssid = "test-wps-conf"
7882 appin = "12345670"
7883 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
7884 "wpa_passphrase": "12345678", "wpa": "2",
7885 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
7886 "ap_pin": appin}
7887 hapd = hostapd.add_ap(apdev, params)
7888
7889 dev.scan_for_bss(bssid, freq="2412")
7890 hapd.request("SET ext_eapol_frame_io 1")
7891 dev.request("SET ext_eapol_frame_io 1")
7892
7893 dev.request("WPS_REG " + bssid + " " + appin)
7894
7895 return addr, bssid, hapd
7896
7897 def wps_run_ap_settings_proto(dev, apdev, ap_settings, success):
7898 addr, bssid, hapd = wps_start_ext_reg(apdev[0], dev[0])
7899 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7900 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7901
7902 logger.debug("Receive M1 from AP")
7903 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7904 mac_addr = m1_attrs[ATTR_MAC_ADDR]
7905 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7906 e_pk = m1_attrs[ATTR_PUBLIC_KEY]
7907
7908 appin = '12345670'
7909 uuid_r = 16*b'\x33'
7910 r_nonce = 16*b'\x44'
7911 own_private, r_pk = wsc_dh_init()
7912 authkey, keywrapkey = wsc_dh_kdf(e_pk, own_private, mac_addr, e_nonce,
7913 r_nonce)
7914 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, appin, e_pk, r_pk)
7915
7916 logger.debug("Send M2 to AP")
7917 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, msg['eap_identifier'],
7918 e_nonce, r_nonce, uuid_r, r_pk, eap_code=2)
7919 send_wsc_msg(hapd, addr, m2)
7920
7921 logger.debug("Receive M3 from AP")
7922 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M3)
7923
7924 logger.debug("Send M4 to AP")
7925 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7926 attrs += build_attr_msg_type(WPS_M4)
7927 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7928 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7929 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7930 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7931 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7932 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7933 raw_m4_attrs = attrs
7934 m4 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7935 send_wsc_msg(hapd, addr, m4)
7936
7937 logger.debug("Receive M5 from AP")
7938 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M5)
7939
7940 logger.debug("Send M6 to STA")
7941 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7942 attrs += build_attr_msg_type(WPS_M6)
7943 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7944 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7945 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7946 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
7947 raw_m6_attrs = attrs
7948 m6 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7949 send_wsc_msg(hapd, addr, m6)
7950
7951 logger.debug("Receive M7 from AP")
7952 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M7)
7953
7954 logger.debug("Send M8 to STA")
7955 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7956 attrs += build_attr_msg_type(WPS_M8)
7957 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7958 if ap_settings:
7959 attrs += build_attr_encr_settings(authkey, keywrapkey, ap_settings)
7960 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7961 raw_m8_attrs = attrs
7962 m8 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7963 send_wsc_msg(hapd, addr, m8)
7964
7965 if success:
7966 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
7967 if ev is None:
7968 raise Exception("New AP settings not reported")
7969 logger.debug("Receive WSC_Done from AP")
7970 msg = get_wsc_msg(hapd)
7971 if msg['wsc_opcode'] != WSC_Done:
7972 raise Exception("Unexpected message - expected WSC_Done")
7973
7974 logger.debug("Send WSC_ACK to AP")
7975 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
7976 eap_code=2)
7977 send_wsc_msg(hapd, addr, ack)
7978 dev[0].wait_disconnected()
7979 else:
7980 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
7981 if ev is None:
7982 raise Exception("WPS failure not reported")
7983 logger.debug("Receive WSC_NACK from AP")
7984 msg = get_wsc_msg(hapd)
7985 if msg['wsc_opcode'] != WSC_NACK:
7986 raise Exception("Unexpected message - expected WSC_NACK")
7987
7988 logger.debug("Send WSC_NACK to AP")
7989 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7990 eap_code=2)
7991 send_wsc_msg(hapd, addr, nack)
7992 dev[0].wait_disconnected()
7993
7994 def test_wps_ext_ap_settings_success(dev, apdev):
7995 """WPS and AP Settings: success"""
7996 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7997 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7998 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7999 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
8000 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
8001 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
8002 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
8003
8004 @remote_compatible
8005 def test_wps_ext_ap_settings_missing(dev, apdev):
8006 """WPS and AP Settings: missing"""
8007 wps_run_ap_settings_proto(dev, apdev, None, False)
8008
8009 @remote_compatible
8010 def test_wps_ext_ap_settings_mac_addr_mismatch(dev, apdev):
8011 """WPS and AP Settings: MAC Address mismatch"""
8012 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
8013 ap_settings += build_wsc_attr(ATTR_SSID, "test")
8014 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
8015 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
8016 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
8017 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, '\x00\x00\x00\x00\x00\x00')
8018 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
8019
8020 @remote_compatible
8021 def test_wps_ext_ap_settings_mac_addr_missing(dev, apdev):
8022 """WPS and AP Settings: missing MAC Address"""
8023 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
8024 ap_settings += build_wsc_attr(ATTR_SSID, "test")
8025 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
8026 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
8027 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
8028 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
8029
8030 @remote_compatible
8031 def test_wps_ext_ap_settings_reject_encr_type(dev, apdev):
8032 """WPS and AP Settings: reject Encr Type"""
8033 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
8034 ap_settings += build_wsc_attr(ATTR_SSID, "test")
8035 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
8036 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x00')
8037 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
8038 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
8039 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
8040
8041 @remote_compatible
8042 def test_wps_ext_ap_settings_m2d(dev, apdev):
8043 """WPS and AP Settings: M2D"""
8044 addr, bssid, hapd = wps_start_ext_reg(apdev[0], dev[0])
8045 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8046 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8047
8048 logger.debug("Receive M1 from AP")
8049 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
8050 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
8051
8052 r_nonce = 16*'\x44'
8053 uuid_r = 16*'\x33'
8054
8055 logger.debug("Send M2D to AP")
8056 m2d, raw_m2d_attrs = build_m2d(raw_m1_attrs, msg['eap_identifier'],
8057 e_nonce, r_nonce, uuid_r,
8058 dev_pw_id='\x00\x00', eap_code=2)
8059 send_wsc_msg(hapd, addr, m2d)
8060
8061 ev = hapd.wait_event(["WPS-M2D"], timeout=5)
8062 if ev is None:
8063 raise Exception("M2D not reported")
8064
8065 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8066
8067 def wps_wait_ap_nack(hapd, dev, e_nonce, r_nonce):
8068 logger.debug("Receive WSC_NACK from AP")
8069 msg = get_wsc_msg(hapd)
8070 if msg['wsc_opcode'] != WSC_NACK:
8071 raise Exception("Unexpected message - expected WSC_NACK")
8072
8073 logger.debug("Send WSC_NACK to AP")
8074 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8075 eap_code=2)
8076 send_wsc_msg(hapd, dev.own_addr(), nack)
8077 dev.wait_disconnected()
8078
8079 @remote_compatible
8080 def test_wps_ext_m3_missing_e_hash1(dev, apdev):
8081 """WPS proto: M3 missing E-Hash1"""
8082 pin = "12345670"
8083 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8084 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8085 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8086
8087 logger.debug("Receive WSC/Start from AP")
8088 msg = get_wsc_msg(hapd)
8089 if msg['wsc_opcode'] != WSC_Start:
8090 raise Exception("Unexpected Op-Code for WSC/Start")
8091
8092 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8093 uuid_e = 16*b'\x11'
8094 e_nonce = 16*b'\x22'
8095 own_private, e_pk = wsc_dh_init()
8096
8097 logger.debug("Send M1 to AP")
8098 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8099 e_nonce, e_pk)
8100 send_wsc_msg(hapd, addr, m1)
8101
8102 logger.debug("Receive M2 from AP")
8103 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8104 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8105 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8106
8107 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8108 r_nonce)
8109 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8110
8111 logger.debug("Send M3 to AP")
8112 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8113 attrs += build_attr_msg_type(WPS_M3)
8114 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8115 #attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8116 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8117 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8118 raw_m3_attrs = attrs
8119 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8120 send_wsc_msg(hapd, addr, m3)
8121
8122 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8123
8124 @remote_compatible
8125 def test_wps_ext_m3_missing_e_hash2(dev, apdev):
8126 """WPS proto: M3 missing E-Hash2"""
8127 pin = "12345670"
8128 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8129 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8130 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8131
8132 logger.debug("Receive WSC/Start from AP")
8133 msg = get_wsc_msg(hapd)
8134 if msg['wsc_opcode'] != WSC_Start:
8135 raise Exception("Unexpected Op-Code for WSC/Start")
8136
8137 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8138 uuid_e = 16*b'\x11'
8139 e_nonce = 16*b'\x22'
8140 own_private, e_pk = wsc_dh_init()
8141
8142 logger.debug("Send M1 to AP")
8143 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8144 e_nonce, e_pk)
8145 send_wsc_msg(hapd, addr, m1)
8146
8147 logger.debug("Receive M2 from AP")
8148 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8149 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8150 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8151
8152 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8153 r_nonce)
8154 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8155
8156 logger.debug("Send M3 to AP")
8157 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8158 attrs += build_attr_msg_type(WPS_M3)
8159 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8160 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8161 #attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8162 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8163 raw_m3_attrs = attrs
8164 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8165 send_wsc_msg(hapd, addr, m3)
8166
8167 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8168
8169 @remote_compatible
8170 def test_wps_ext_m5_missing_e_snonce1(dev, apdev):
8171 """WPS proto: M5 missing E-SNonce1"""
8172 pin = "12345670"
8173 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8174 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8175 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8176
8177 logger.debug("Receive WSC/Start from AP")
8178 msg = get_wsc_msg(hapd)
8179 if msg['wsc_opcode'] != WSC_Start:
8180 raise Exception("Unexpected Op-Code for WSC/Start")
8181
8182 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8183 uuid_e = 16*b'\x11'
8184 e_nonce = 16*b'\x22'
8185 own_private, e_pk = wsc_dh_init()
8186
8187 logger.debug("Send M1 to AP")
8188 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8189 e_nonce, e_pk)
8190 send_wsc_msg(hapd, addr, m1)
8191
8192 logger.debug("Receive M2 from AP")
8193 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8194 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8195 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8196
8197 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8198 r_nonce)
8199 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8200
8201 logger.debug("Send M3 to AP")
8202 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8203 attrs += build_attr_msg_type(WPS_M3)
8204 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8205 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8206 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8207 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8208 raw_m3_attrs = attrs
8209 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8210 send_wsc_msg(hapd, addr, m3)
8211
8212 logger.debug("Receive M4 from AP")
8213 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8214
8215 logger.debug("Send M5 to AP")
8216 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8217 attrs += build_attr_msg_type(WPS_M5)
8218 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8219 #data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8220 data = b''
8221 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8222 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8223 raw_m5_attrs = attrs
8224 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8225 send_wsc_msg(hapd, addr, m5)
8226
8227 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8228
8229 @remote_compatible
8230 def test_wps_ext_m5_e_snonce1_mismatch(dev, apdev):
8231 """WPS proto: M5 E-SNonce1 mismatch"""
8232 pin = "12345670"
8233 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8234 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8235 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8236
8237 logger.debug("Receive WSC/Start from AP")
8238 msg = get_wsc_msg(hapd)
8239 if msg['wsc_opcode'] != WSC_Start:
8240 raise Exception("Unexpected Op-Code for WSC/Start")
8241
8242 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8243 uuid_e = 16*b'\x11'
8244 e_nonce = 16*b'\x22'
8245 own_private, e_pk = wsc_dh_init()
8246
8247 logger.debug("Send M1 to AP")
8248 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8249 e_nonce, e_pk)
8250 send_wsc_msg(hapd, addr, m1)
8251
8252 logger.debug("Receive M2 from AP")
8253 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8254 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8255 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8256
8257 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8258 r_nonce)
8259 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8260
8261 logger.debug("Send M3 to AP")
8262 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8263 attrs += build_attr_msg_type(WPS_M3)
8264 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8265 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8266 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8267 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8268 raw_m3_attrs = attrs
8269 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8270 send_wsc_msg(hapd, addr, m3)
8271
8272 logger.debug("Receive M4 from AP")
8273 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8274
8275 logger.debug("Send M5 to AP")
8276 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8277 attrs += build_attr_msg_type(WPS_M5)
8278 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8279 data = build_wsc_attr(ATTR_E_SNONCE1, 16*'\x00')
8280 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8281 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8282 raw_m5_attrs = attrs
8283 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8284 send_wsc_msg(hapd, addr, m5)
8285
8286 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8287
8288 def test_wps_ext_m7_missing_e_snonce2(dev, apdev):
8289 """WPS proto: M7 missing E-SNonce2"""
8290 pin = "12345670"
8291 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8292 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8293 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8294
8295 logger.debug("Receive WSC/Start from AP")
8296 msg = get_wsc_msg(hapd)
8297 if msg['wsc_opcode'] != WSC_Start:
8298 raise Exception("Unexpected Op-Code for WSC/Start")
8299
8300 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8301 uuid_e = 16*b'\x11'
8302 e_nonce = 16*b'\x22'
8303 own_private, e_pk = wsc_dh_init()
8304
8305 logger.debug("Send M1 to AP")
8306 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8307 e_nonce, e_pk)
8308 send_wsc_msg(hapd, addr, m1)
8309
8310 logger.debug("Receive M2 from AP")
8311 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8312 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8313 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8314
8315 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8316 r_nonce)
8317 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8318
8319 logger.debug("Send M3 to AP")
8320 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8321 attrs += build_attr_msg_type(WPS_M3)
8322 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8323 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8324 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8325 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8326 raw_m3_attrs = attrs
8327 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8328 send_wsc_msg(hapd, addr, m3)
8329
8330 logger.debug("Receive M4 from AP")
8331 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8332
8333 logger.debug("Send M5 to AP")
8334 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8335 attrs += build_attr_msg_type(WPS_M5)
8336 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8337 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8338 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8339 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8340 raw_m5_attrs = attrs
8341 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8342 send_wsc_msg(hapd, addr, m5)
8343
8344 logger.debug("Receive M6 from AP")
8345 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8346
8347 logger.debug("Send M7 to AP")
8348 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8349 attrs += build_attr_msg_type(WPS_M7)
8350 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8351 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
8352 data = b''
8353 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8354 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8355 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8356 raw_m7_attrs = attrs
8357 send_wsc_msg(hapd, addr, m7)
8358
8359 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8360
8361 @remote_compatible
8362 def test_wps_ext_m7_e_snonce2_mismatch(dev, apdev):
8363 """WPS proto: M7 E-SNonce2 mismatch"""
8364 pin = "12345670"
8365 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8366 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8367 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8368
8369 logger.debug("Receive WSC/Start from AP")
8370 msg = get_wsc_msg(hapd)
8371 if msg['wsc_opcode'] != WSC_Start:
8372 raise Exception("Unexpected Op-Code for WSC/Start")
8373
8374 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8375 uuid_e = 16*b'\x11'
8376 e_nonce = 16*b'\x22'
8377 own_private, e_pk = wsc_dh_init()
8378
8379 logger.debug("Send M1 to AP")
8380 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8381 e_nonce, e_pk)
8382 send_wsc_msg(hapd, addr, m1)
8383
8384 logger.debug("Receive M2 from AP")
8385 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8386 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8387 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8388
8389 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8390 r_nonce)
8391 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8392
8393 logger.debug("Send M3 to AP")
8394 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8395 attrs += build_attr_msg_type(WPS_M3)
8396 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8397 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8398 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8399 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8400 raw_m3_attrs = attrs
8401 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8402 send_wsc_msg(hapd, addr, m3)
8403
8404 logger.debug("Receive M4 from AP")
8405 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8406
8407 logger.debug("Send M5 to AP")
8408 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8409 attrs += build_attr_msg_type(WPS_M5)
8410 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8411 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8412 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8413 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8414 raw_m5_attrs = attrs
8415 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8416 send_wsc_msg(hapd, addr, m5)
8417
8418 logger.debug("Receive M6 from AP")
8419 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8420
8421 logger.debug("Send M7 to AP")
8422 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8423 attrs += build_attr_msg_type(WPS_M7)
8424 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8425 data = build_wsc_attr(ATTR_E_SNONCE2, 16*'\x00')
8426 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8427 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8428 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8429 raw_m7_attrs = attrs
8430 send_wsc_msg(hapd, addr, m7)
8431
8432 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8433
8434 @remote_compatible
8435 def test_wps_ext_m1_pubkey_oom(dev, apdev):
8436 """WPS proto: M1 PubKey OOM"""
8437 pin = "12345670"
8438 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8439 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8440 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8441
8442 logger.debug("Receive WSC/Start from AP")
8443 msg = get_wsc_msg(hapd)
8444 if msg['wsc_opcode'] != WSC_Start:
8445 raise Exception("Unexpected Op-Code for WSC/Start")
8446
8447 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8448 uuid_e = 16*'\x11'
8449 e_nonce = 16*'\x22'
8450 own_private, e_pk = wsc_dh_init()
8451
8452 logger.debug("Send M1 to AP")
8453 with alloc_fail(hapd, 1, "wpabuf_alloc_copy;wps_process_pubkey"):
8454 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8455 e_nonce, e_pk)
8456 send_wsc_msg(hapd, addr, m1)
8457 wps_wait_eap_failure(hapd, dev[0])
8458
8459 def wps_wait_eap_failure(hapd, dev):
8460 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
8461 if ev is None:
8462 raise Exception("EAP-Failure not reported")
8463 dev.wait_disconnected()
8464
8465 @remote_compatible
8466 def test_wps_ext_m3_m1(dev, apdev):
8467 """WPS proto: M3 replaced with M1"""
8468 pin = "12345670"
8469 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8470 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8471 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8472
8473 logger.debug("Receive WSC/Start from AP")
8474 msg = get_wsc_msg(hapd)
8475 if msg['wsc_opcode'] != WSC_Start:
8476 raise Exception("Unexpected Op-Code for WSC/Start")
8477
8478 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8479 uuid_e = 16*b'\x11'
8480 e_nonce = 16*b'\x22'
8481 own_private, e_pk = wsc_dh_init()
8482
8483 logger.debug("Send M1 to AP")
8484 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8485 e_nonce, e_pk)
8486 send_wsc_msg(hapd, addr, m1)
8487
8488 logger.debug("Receive M2 from AP")
8489 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8490 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8491 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8492
8493 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8494 r_nonce)
8495 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8496
8497 logger.debug("Send M3(M1) to AP")
8498 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8499 attrs += build_attr_msg_type(WPS_M1)
8500 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8501 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8502 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8503 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8504 raw_m3_attrs = attrs
8505 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8506 send_wsc_msg(hapd, addr, m3)
8507
8508 wps_wait_eap_failure(hapd, dev[0])
8509
8510 @remote_compatible
8511 def test_wps_ext_m5_m3(dev, apdev):
8512 """WPS proto: M5 replaced with M3"""
8513 pin = "12345670"
8514 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8515 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8516 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8517
8518 logger.debug("Receive WSC/Start from AP")
8519 msg = get_wsc_msg(hapd)
8520 if msg['wsc_opcode'] != WSC_Start:
8521 raise Exception("Unexpected Op-Code for WSC/Start")
8522
8523 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8524 uuid_e = 16*b'\x11'
8525 e_nonce = 16*b'\x22'
8526 own_private, e_pk = wsc_dh_init()
8527
8528 logger.debug("Send M1 to AP")
8529 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8530 e_nonce, e_pk)
8531 send_wsc_msg(hapd, addr, m1)
8532
8533 logger.debug("Receive M2 from AP")
8534 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8535 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8536 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8537
8538 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8539 r_nonce)
8540 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8541
8542 logger.debug("Send M3 to AP")
8543 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8544 attrs += build_attr_msg_type(WPS_M3)
8545 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8546 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8547 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8548 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8549 raw_m3_attrs = attrs
8550 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8551 send_wsc_msg(hapd, addr, m3)
8552
8553 logger.debug("Receive M4 from AP")
8554 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8555
8556 logger.debug("Send M5(M3) to AP")
8557 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8558 attrs += build_attr_msg_type(WPS_M3)
8559 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8560 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8561 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8562 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8563 raw_m5_attrs = attrs
8564 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8565 send_wsc_msg(hapd, addr, m5)
8566
8567 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8568
8569 @remote_compatible
8570 def test_wps_ext_m3_m2(dev, apdev):
8571 """WPS proto: M3 replaced with M2"""
8572 pin = "12345670"
8573 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8574 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8575 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8576
8577 logger.debug("Receive WSC/Start from AP")
8578 msg = get_wsc_msg(hapd)
8579 if msg['wsc_opcode'] != WSC_Start:
8580 raise Exception("Unexpected Op-Code for WSC/Start")
8581
8582 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8583 uuid_e = 16*b'\x11'
8584 e_nonce = 16*b'\x22'
8585 own_private, e_pk = wsc_dh_init()
8586
8587 logger.debug("Send M1 to AP")
8588 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8589 e_nonce, e_pk)
8590 send_wsc_msg(hapd, addr, m1)
8591
8592 logger.debug("Receive M2 from AP")
8593 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8594 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8595 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8596
8597 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8598 r_nonce)
8599 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8600
8601 logger.debug("Send M3(M2) to AP")
8602 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8603 attrs += build_attr_msg_type(WPS_M2)
8604 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8605 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8606 raw_m3_attrs = attrs
8607 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8608 send_wsc_msg(hapd, addr, m3)
8609
8610 wps_wait_eap_failure(hapd, dev[0])
8611
8612 @remote_compatible
8613 def test_wps_ext_m3_m5(dev, apdev):
8614 """WPS proto: M3 replaced with M5"""
8615 pin = "12345670"
8616 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8617 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8618 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8619
8620 logger.debug("Receive WSC/Start from AP")
8621 msg = get_wsc_msg(hapd)
8622 if msg['wsc_opcode'] != WSC_Start:
8623 raise Exception("Unexpected Op-Code for WSC/Start")
8624
8625 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8626 uuid_e = 16*b'\x11'
8627 e_nonce = 16*b'\x22'
8628 own_private, e_pk = wsc_dh_init()
8629
8630 logger.debug("Send M1 to AP")
8631 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8632 e_nonce, e_pk)
8633 send_wsc_msg(hapd, addr, m1)
8634
8635 logger.debug("Receive M2 from AP")
8636 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8637 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8638 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8639
8640 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8641 r_nonce)
8642 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8643
8644 logger.debug("Send M3(M5) to AP")
8645 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8646 attrs += build_attr_msg_type(WPS_M5)
8647 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8648 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8649 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8650 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8651 raw_m3_attrs = attrs
8652 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8653 send_wsc_msg(hapd, addr, m3)
8654
8655 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8656
8657 @remote_compatible
8658 def test_wps_ext_m3_m7(dev, apdev):
8659 """WPS proto: M3 replaced with M7"""
8660 pin = "12345670"
8661 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8662 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8663 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8664
8665 logger.debug("Receive WSC/Start from AP")
8666 msg = get_wsc_msg(hapd)
8667 if msg['wsc_opcode'] != WSC_Start:
8668 raise Exception("Unexpected Op-Code for WSC/Start")
8669
8670 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8671 uuid_e = 16*b'\x11'
8672 e_nonce = 16*b'\x22'
8673 own_private, e_pk = wsc_dh_init()
8674
8675 logger.debug("Send M1 to AP")
8676 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8677 e_nonce, e_pk)
8678 send_wsc_msg(hapd, addr, m1)
8679
8680 logger.debug("Receive M2 from AP")
8681 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8682 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8683 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8684
8685 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8686 r_nonce)
8687 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8688
8689 logger.debug("Send M3(M7) to AP")
8690 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8691 attrs += build_attr_msg_type(WPS_M7)
8692 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8693 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8694 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8695 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8696 raw_m3_attrs = attrs
8697 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8698 send_wsc_msg(hapd, addr, m3)
8699
8700 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8701
8702 @remote_compatible
8703 def test_wps_ext_m3_done(dev, apdev):
8704 """WPS proto: M3 replaced with WSC_Done"""
8705 pin = "12345670"
8706 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8707 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8708 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8709
8710 logger.debug("Receive WSC/Start from AP")
8711 msg = get_wsc_msg(hapd)
8712 if msg['wsc_opcode'] != WSC_Start:
8713 raise Exception("Unexpected Op-Code for WSC/Start")
8714
8715 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8716 uuid_e = 16*b'\x11'
8717 e_nonce = 16*b'\x22'
8718 own_private, e_pk = wsc_dh_init()
8719
8720 logger.debug("Send M1 to AP")
8721 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8722 e_nonce, e_pk)
8723 send_wsc_msg(hapd, addr, m1)
8724
8725 logger.debug("Receive M2 from AP")
8726 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8727 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8728 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8729
8730 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8731 r_nonce)
8732 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8733
8734 logger.debug("Send M3(WSC_Done) to AP")
8735 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8736 attrs += build_attr_msg_type(WPS_WSC_DONE)
8737 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8738 raw_m3_attrs = attrs
8739 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8740 send_wsc_msg(hapd, addr, m3)
8741
8742 wps_wait_eap_failure(hapd, dev[0])
8743
8744 @remote_compatible
8745 def test_wps_ext_m2_nack_invalid(dev, apdev):
8746 """WPS proto: M2 followed by invalid NACK"""
8747 pin = "12345670"
8748 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8749 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8750 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8751
8752 logger.debug("Receive WSC/Start from AP")
8753 msg = get_wsc_msg(hapd)
8754 if msg['wsc_opcode'] != WSC_Start:
8755 raise Exception("Unexpected Op-Code for WSC/Start")
8756
8757 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8758 uuid_e = 16*b'\x11'
8759 e_nonce = 16*b'\x22'
8760 own_private, e_pk = wsc_dh_init()
8761
8762 logger.debug("Send M1 to AP")
8763 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8764 e_nonce, e_pk)
8765 send_wsc_msg(hapd, addr, m1)
8766
8767 logger.debug("Receive M2 from AP")
8768 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8769 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8770 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8771
8772 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8773 r_nonce)
8774 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8775
8776 logger.debug("Send WSC_NACK to AP")
8777 attrs = b'\x10\x00\x00'
8778 nack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_NACK)
8779 send_wsc_msg(hapd, addr, nack)
8780
8781 wps_wait_eap_failure(hapd, dev[0])
8782
8783 @remote_compatible
8784 def test_wps_ext_m2_nack_no_msg_type(dev, apdev):
8785 """WPS proto: M2 followed by NACK without Msg Type"""
8786 pin = "12345670"
8787 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8788 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8789 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8790
8791 logger.debug("Receive WSC/Start from AP")
8792 msg = get_wsc_msg(hapd)
8793 if msg['wsc_opcode'] != WSC_Start:
8794 raise Exception("Unexpected Op-Code for WSC/Start")
8795
8796 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8797 uuid_e = 16*b'\x11'
8798 e_nonce = 16*b'\x22'
8799 own_private, e_pk = wsc_dh_init()
8800
8801 logger.debug("Send M1 to AP")
8802 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8803 e_nonce, e_pk)
8804 send_wsc_msg(hapd, addr, m1)
8805
8806 logger.debug("Receive M2 from AP")
8807 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8808 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8809 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8810
8811 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8812 r_nonce)
8813 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8814
8815 logger.debug("Send WSC_NACK to AP")
8816 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8817 msg_type=None, eap_code=2)
8818 send_wsc_msg(hapd, addr, nack)
8819
8820 wps_wait_eap_failure(hapd, dev[0])
8821
8822 @remote_compatible
8823 def test_wps_ext_m2_nack_invalid_msg_type(dev, apdev):
8824 """WPS proto: M2 followed by NACK with invalid Msg Type"""
8825 pin = "12345670"
8826 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8827 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8828 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8829
8830 logger.debug("Receive WSC/Start from AP")
8831 msg = get_wsc_msg(hapd)
8832 if msg['wsc_opcode'] != WSC_Start:
8833 raise Exception("Unexpected Op-Code for WSC/Start")
8834
8835 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8836 uuid_e = 16*b'\x11'
8837 e_nonce = 16*b'\x22'
8838 own_private, e_pk = wsc_dh_init()
8839
8840 logger.debug("Send M1 to AP")
8841 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8842 e_nonce, e_pk)
8843 send_wsc_msg(hapd, addr, m1)
8844
8845 logger.debug("Receive M2 from AP")
8846 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8847 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8848 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8849
8850 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8851 r_nonce)
8852 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8853
8854 logger.debug("Send WSC_NACK to AP")
8855 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8856 msg_type=WPS_WSC_ACK, eap_code=2)
8857 send_wsc_msg(hapd, addr, nack)
8858
8859 wps_wait_eap_failure(hapd, dev[0])
8860
8861 @remote_compatible
8862 def test_wps_ext_m2_nack_e_nonce_mismatch(dev, apdev):
8863 """WPS proto: M2 followed by NACK with e-nonce mismatch"""
8864 pin = "12345670"
8865 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8866 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8867 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8868
8869 logger.debug("Receive WSC/Start from AP")
8870 msg = get_wsc_msg(hapd)
8871 if msg['wsc_opcode'] != WSC_Start:
8872 raise Exception("Unexpected Op-Code for WSC/Start")
8873
8874 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8875 uuid_e = 16*b'\x11'
8876 e_nonce = 16*b'\x22'
8877 own_private, e_pk = wsc_dh_init()
8878
8879 logger.debug("Send M1 to AP")
8880 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8881 e_nonce, e_pk)
8882 send_wsc_msg(hapd, addr, m1)
8883
8884 logger.debug("Receive M2 from AP")
8885 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8886 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8887 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8888
8889 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8890 r_nonce)
8891 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8892
8893 logger.debug("Send WSC_NACK to AP")
8894 nack, attrs = build_nack(msg['eap_identifier'], 16*b'\x00', r_nonce,
8895 eap_code=2)
8896 send_wsc_msg(hapd, addr, nack)
8897
8898 wps_wait_eap_failure(hapd, dev[0])
8899
8900 @remote_compatible
8901 def test_wps_ext_m2_nack_no_config_error(dev, apdev):
8902 """WPS proto: M2 followed by NACK without Config Error"""
8903 pin = "12345670"
8904 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8905 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8906 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8907
8908 logger.debug("Receive WSC/Start from AP")
8909 msg = get_wsc_msg(hapd)
8910 if msg['wsc_opcode'] != WSC_Start:
8911 raise Exception("Unexpected Op-Code for WSC/Start")
8912
8913 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8914 uuid_e = 16*b'\x11'
8915 e_nonce = 16*b'\x22'
8916 own_private, e_pk = wsc_dh_init()
8917
8918 logger.debug("Send M1 to AP")
8919 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8920 e_nonce, e_pk)
8921 send_wsc_msg(hapd, addr, m1)
8922
8923 logger.debug("Receive M2 from AP")
8924 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8925 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8926 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8927
8928 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8929 r_nonce)
8930 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8931
8932 logger.debug("Send WSC_NACK to AP")
8933 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8934 config_error=None, eap_code=2)
8935 send_wsc_msg(hapd, addr, nack)
8936
8937 wps_wait_eap_failure(hapd, dev[0])
8938
8939 @remote_compatible
8940 def test_wps_ext_m2_ack_invalid(dev, apdev):
8941 """WPS proto: M2 followed by invalid ACK"""
8942 pin = "12345670"
8943 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8944 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8945 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8946
8947 logger.debug("Receive WSC/Start from AP")
8948 msg = get_wsc_msg(hapd)
8949 if msg['wsc_opcode'] != WSC_Start:
8950 raise Exception("Unexpected Op-Code for WSC/Start")
8951
8952 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8953 uuid_e = 16*b'\x11'
8954 e_nonce = 16*b'\x22'
8955 own_private, e_pk = wsc_dh_init()
8956
8957 logger.debug("Send M1 to AP")
8958 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8959 e_nonce, e_pk)
8960 send_wsc_msg(hapd, addr, m1)
8961
8962 logger.debug("Receive M2 from AP")
8963 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8964 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8965 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8966
8967 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8968 r_nonce)
8969 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8970
8971 logger.debug("Send WSC_ACK to AP")
8972 attrs = b'\x10\x00\x00'
8973 ack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_ACK)
8974 send_wsc_msg(hapd, addr, ack)
8975
8976 wps_wait_eap_failure(hapd, dev[0])
8977
8978 @remote_compatible
8979 def test_wps_ext_m2_ack(dev, apdev):
8980 """WPS proto: M2 followed by ACK"""
8981 pin = "12345670"
8982 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8983 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8984 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8985
8986 logger.debug("Receive WSC/Start from AP")
8987 msg = get_wsc_msg(hapd)
8988 if msg['wsc_opcode'] != WSC_Start:
8989 raise Exception("Unexpected Op-Code for WSC/Start")
8990
8991 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8992 uuid_e = 16*b'\x11'
8993 e_nonce = 16*b'\x22'
8994 own_private, e_pk = wsc_dh_init()
8995
8996 logger.debug("Send M1 to AP")
8997 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8998 e_nonce, e_pk)
8999 send_wsc_msg(hapd, addr, m1)
9000
9001 logger.debug("Receive M2 from AP")
9002 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9003 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9004 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9005
9006 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9007 r_nonce)
9008 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9009
9010 logger.debug("Send WSC_ACK to AP")
9011 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce, eap_code=2)
9012 send_wsc_msg(hapd, addr, ack)
9013
9014 wps_wait_eap_failure(hapd, dev[0])
9015
9016 @remote_compatible
9017 def test_wps_ext_m2_ack_no_msg_type(dev, apdev):
9018 """WPS proto: M2 followed by ACK missing Msg Type"""
9019 pin = "12345670"
9020 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9021 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9022 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9023
9024 logger.debug("Receive WSC/Start from AP")
9025 msg = get_wsc_msg(hapd)
9026 if msg['wsc_opcode'] != WSC_Start:
9027 raise Exception("Unexpected Op-Code for WSC/Start")
9028
9029 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9030 uuid_e = 16*b'\x11'
9031 e_nonce = 16*b'\x22'
9032 own_private, e_pk = wsc_dh_init()
9033
9034 logger.debug("Send M1 to AP")
9035 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9036 e_nonce, e_pk)
9037 send_wsc_msg(hapd, addr, m1)
9038
9039 logger.debug("Receive M2 from AP")
9040 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9041 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9042 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9043
9044 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9045 r_nonce)
9046 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9047
9048 logger.debug("Send WSC_ACK to AP")
9049 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
9050 msg_type=None, eap_code=2)
9051 send_wsc_msg(hapd, addr, ack)
9052
9053 wps_wait_eap_failure(hapd, dev[0])
9054
9055 @remote_compatible
9056 def test_wps_ext_m2_ack_invalid_msg_type(dev, apdev):
9057 """WPS proto: M2 followed by ACK with invalid 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 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9069 uuid_e = 16*b'\x11'
9070 e_nonce = 16*b'\x22'
9071 own_private, e_pk = wsc_dh_init()
9072
9073 logger.debug("Send M1 to AP")
9074 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9075 e_nonce, e_pk)
9076 send_wsc_msg(hapd, addr, m1)
9077
9078 logger.debug("Receive M2 from AP")
9079 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9080 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9081 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9082
9083 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9084 r_nonce)
9085 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9086
9087 logger.debug("Send WSC_ACK to AP")
9088 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
9089 msg_type=WPS_WSC_NACK, eap_code=2)
9090 send_wsc_msg(hapd, addr, ack)
9091
9092 wps_wait_eap_failure(hapd, dev[0])
9093
9094 @remote_compatible
9095 def test_wps_ext_m2_ack_e_nonce_mismatch(dev, apdev):
9096 """WPS proto: M2 followed by ACK with e-nonce mismatch"""
9097 pin = "12345670"
9098 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9099 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9100 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9101
9102 logger.debug("Receive WSC/Start from AP")
9103 msg = get_wsc_msg(hapd)
9104 if msg['wsc_opcode'] != WSC_Start:
9105 raise Exception("Unexpected Op-Code for WSC/Start")
9106
9107 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9108 uuid_e = 16*b'\x11'
9109 e_nonce = 16*b'\x22'
9110 own_private, e_pk = wsc_dh_init()
9111
9112 logger.debug("Send M1 to AP")
9113 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9114 e_nonce, e_pk)
9115 send_wsc_msg(hapd, addr, m1)
9116
9117 logger.debug("Receive M2 from AP")
9118 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9119 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9120 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9121
9122 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9123 r_nonce)
9124 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9125
9126 logger.debug("Send WSC_ACK to AP")
9127 ack, attrs = build_ack(msg['eap_identifier'], 16*b'\x00', r_nonce,
9128 eap_code=2)
9129 send_wsc_msg(hapd, addr, ack)
9130
9131 wps_wait_eap_failure(hapd, dev[0])
9132
9133 @remote_compatible
9134 def test_wps_ext_m1_invalid(dev, apdev):
9135 """WPS proto: M1 failing parsing"""
9136 pin = "12345670"
9137 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9138 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9139 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9140
9141 logger.debug("Receive WSC/Start from AP")
9142 msg = get_wsc_msg(hapd)
9143 if msg['wsc_opcode'] != WSC_Start:
9144 raise Exception("Unexpected Op-Code for WSC/Start")
9145
9146 logger.debug("Send M1 to AP")
9147 attrs = b'\x10\x00\x00'
9148 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9149 send_wsc_msg(hapd, addr, m1)
9150
9151 wps_wait_eap_failure(hapd, dev[0])
9152
9153 def test_wps_ext_m1_missing_msg_type(dev, apdev):
9154 """WPS proto: M1 missing Msg Type"""
9155 pin = "12345670"
9156 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9157 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9158 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9159
9160 logger.debug("Receive WSC/Start from AP")
9161 msg = get_wsc_msg(hapd)
9162 if msg['wsc_opcode'] != WSC_Start:
9163 raise Exception("Unexpected Op-Code for WSC/Start")
9164
9165 logger.debug("Send M1 to AP")
9166 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9167 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9168 send_wsc_msg(hapd, addr, m1)
9169
9170 wps_wait_ap_nack(hapd, dev[0], 16*b'\x00', 16*b'\x00')
9171
9172 def wps_ext_wsc_done(dev, apdev):
9173 pin = "12345670"
9174 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9175 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9176 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9177
9178 logger.debug("Receive WSC/Start from AP")
9179 msg = get_wsc_msg(hapd)
9180 if msg['wsc_opcode'] != WSC_Start:
9181 raise Exception("Unexpected Op-Code for WSC/Start")
9182
9183 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9184 uuid_e = 16*b'\x11'
9185 e_nonce = 16*b'\x22'
9186 own_private, e_pk = wsc_dh_init()
9187
9188 logger.debug("Send M1 to AP")
9189 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9190 e_nonce, e_pk)
9191 send_wsc_msg(hapd, addr, m1)
9192
9193 logger.debug("Receive M2 from AP")
9194 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9195 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9196 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9197
9198 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9199 r_nonce)
9200 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9201
9202 logger.debug("Send M3 to AP")
9203 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9204 attrs += build_attr_msg_type(WPS_M3)
9205 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9206 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9207 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9208 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9209 raw_m3_attrs = attrs
9210 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9211 send_wsc_msg(hapd, addr, m3)
9212
9213 logger.debug("Receive M4 from AP")
9214 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9215
9216 logger.debug("Send M5 to AP")
9217 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9218 attrs += build_attr_msg_type(WPS_M5)
9219 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9220 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9221 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9222 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9223 raw_m5_attrs = attrs
9224 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9225 send_wsc_msg(hapd, addr, m5)
9226
9227 logger.debug("Receive M6 from AP")
9228 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9229
9230 logger.debug("Send M7 to AP")
9231 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9232 attrs += build_attr_msg_type(WPS_M7)
9233 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9234 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9235 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9236 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9237 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9238 raw_m7_attrs = attrs
9239 send_wsc_msg(hapd, addr, m7)
9240
9241 logger.debug("Receive M8 from AP")
9242 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
9243 return hapd, msg, e_nonce, r_nonce
9244
9245 @remote_compatible
9246 def test_wps_ext_wsc_done_invalid(dev, apdev):
9247 """WPS proto: invalid WSC_Done"""
9248 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9249
9250 logger.debug("Send WSC_Done to AP")
9251 attrs = b'\x10\x00\x00'
9252 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9253 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9254
9255 wps_wait_eap_failure(hapd, dev[0])
9256
9257 @remote_compatible
9258 def test_wps_ext_wsc_done_no_msg_type(dev, apdev):
9259 """WPS proto: invalid WSC_Done"""
9260 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9261
9262 logger.debug("Send WSC_Done to AP")
9263 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9264 #attrs += build_attr_msg_type(WPS_WSC_DONE)
9265 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9266 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9267 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9268 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9269
9270 wps_wait_eap_failure(hapd, dev[0])
9271
9272 @remote_compatible
9273 def test_wps_ext_wsc_done_wrong_msg_type(dev, apdev):
9274 """WPS proto: WSC_Done with wrong Msg Type"""
9275 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9276
9277 logger.debug("Send WSC_Done to AP")
9278 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9279 attrs += build_attr_msg_type(WPS_WSC_ACK)
9280 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9281 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9282 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9283 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9284
9285 wps_wait_eap_failure(hapd, dev[0])
9286
9287 @remote_compatible
9288 def test_wps_ext_wsc_done_no_e_nonce(dev, apdev):
9289 """WPS proto: WSC_Done without e_nonce"""
9290 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9291
9292 logger.debug("Send WSC_Done to AP")
9293 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9294 attrs += build_attr_msg_type(WPS_WSC_DONE)
9295 #attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9296 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9297 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9298 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9299
9300 wps_wait_eap_failure(hapd, dev[0])
9301
9302 def test_wps_ext_wsc_done_no_r_nonce(dev, apdev):
9303 """WPS proto: WSC_Done without r_nonce"""
9304 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9305
9306 logger.debug("Send WSC_Done to AP")
9307 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9308 attrs += build_attr_msg_type(WPS_WSC_DONE)
9309 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9310 #attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9311 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9312 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9313
9314 wps_wait_eap_failure(hapd, dev[0])
9315
9316 @remote_compatible
9317 def test_wps_ext_m7_no_encr_settings(dev, apdev):
9318 """WPS proto: M7 without Encr Settings"""
9319 pin = "12345670"
9320 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9321 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9322 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9323
9324 logger.debug("Receive WSC/Start from AP")
9325 msg = get_wsc_msg(hapd)
9326 if msg['wsc_opcode'] != WSC_Start:
9327 raise Exception("Unexpected Op-Code for WSC/Start")
9328
9329 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9330 uuid_e = 16*b'\x11'
9331 e_nonce = 16*b'\x22'
9332 own_private, e_pk = wsc_dh_init()
9333
9334 logger.debug("Send M1 to AP")
9335 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9336 e_nonce, e_pk)
9337 send_wsc_msg(hapd, addr, m1)
9338
9339 logger.debug("Receive M2 from AP")
9340 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9341 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9342 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9343
9344 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9345 r_nonce)
9346 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9347
9348 logger.debug("Send M3 to AP")
9349 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9350 attrs += build_attr_msg_type(WPS_M3)
9351 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9352 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9353 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9354 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9355 raw_m3_attrs = attrs
9356 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9357 send_wsc_msg(hapd, addr, m3)
9358
9359 logger.debug("Receive M4 from AP")
9360 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9361
9362 logger.debug("Send M5 to AP")
9363 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9364 attrs += build_attr_msg_type(WPS_M5)
9365 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9366 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9367 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9368 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9369 raw_m5_attrs = attrs
9370 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9371 send_wsc_msg(hapd, addr, m5)
9372
9373 logger.debug("Receive M6 from AP")
9374 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9375
9376 logger.debug("Send M7 to AP")
9377 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9378 attrs += build_attr_msg_type(WPS_M7)
9379 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9380 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9381 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9382 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9383 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9384 raw_m7_attrs = attrs
9385 send_wsc_msg(hapd, addr, m7)
9386
9387 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
9388
9389 @remote_compatible
9390 def test_wps_ext_m1_workaround(dev, apdev):
9391 """WPS proto: M1 Manufacturer/Model workaround"""
9392 pin = "12345670"
9393 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9394 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9395 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9396
9397 logger.debug("Receive WSC/Start from AP")
9398 msg = get_wsc_msg(hapd)
9399 if msg['wsc_opcode'] != WSC_Start:
9400 raise Exception("Unexpected Op-Code for WSC/Start")
9401
9402 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9403 uuid_e = 16*b'\x11'
9404 e_nonce = 16*b'\x22'
9405 own_private, e_pk = wsc_dh_init()
9406
9407 logger.debug("Send M1 to AP")
9408 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9409 e_nonce, e_pk, manufacturer='Apple TEST',
9410 model_name='AirPort', config_methods=b'\xff\xff')
9411 send_wsc_msg(hapd, addr, m1)
9412
9413 logger.debug("Receive M2 from AP")
9414 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9415
9416 @remote_compatible
9417 def test_ap_wps_disable_enable(dev, apdev):
9418 """WPS and DISABLE/ENABLE AP"""
9419 hapd = wps_start_ap(apdev[0])
9420 hapd.disable()
9421 hapd.enable()
9422 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9423
9424 def test_ap_wps_upnp_web_oom(dev, apdev, params):
9425 """hostapd WPS UPnP web OOM"""
9426 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9427 hapd = add_ssdp_ap(apdev[0], ap_uuid)
9428
9429 location = ssdp_get_location(ap_uuid)
9430 url = urlparse(location)
9431 urls = upnp_get_urls(location)
9432 eventurl = urlparse(urls['event_sub_url'])
9433 ctrlurl = urlparse(urls['control_url'])
9434
9435 conn = HTTPConnection(url.netloc)
9436 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9437 conn.request("GET", "/wps_device.xml")
9438 try:
9439 resp = conn.getresponse()
9440 except:
9441 pass
9442
9443 conn = HTTPConnection(url.netloc)
9444 conn.request("GET", "/unknown")
9445 resp = conn.getresponse()
9446 if resp.status != 404:
9447 raise Exception("Unexpected HTTP result for unknown URL: %d" + resp.status)
9448
9449 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9450 conn.request("GET", "/unknown")
9451 try:
9452 resp = conn.getresponse()
9453 print(resp.status)
9454 except:
9455 pass
9456
9457 conn = HTTPConnection(url.netloc)
9458 conn.request("GET", "/wps_device.xml")
9459 resp = conn.getresponse()
9460 if resp.status != 200:
9461 raise Exception("GET /wps_device.xml failed")
9462
9463 conn = HTTPConnection(url.netloc)
9464 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9465 if resp.status != 200:
9466 raise Exception("GetDeviceInfo failed")
9467
9468 with alloc_fail(hapd, 1, "web_process_get_device_info"):
9469 conn = HTTPConnection(url.netloc)
9470 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9471 if resp.status != 500:
9472 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9473
9474 with alloc_fail(hapd, 1, "wps_build_m1;web_process_get_device_info"):
9475 conn = HTTPConnection(url.netloc)
9476 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9477 if resp.status != 500:
9478 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9479
9480 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_send_reply"):
9481 conn = HTTPConnection(url.netloc)
9482 try:
9483 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9484 except:
9485 pass
9486
9487 conn = HTTPConnection(url.netloc)
9488 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9489 if resp.status != 200:
9490 raise Exception("GetDeviceInfo failed")
9491
9492 # No NewWLANEventType in PutWLANResponse NewMessage
9493 conn = HTTPConnection(url.netloc)
9494 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse", newmsg="foo")
9495 if resp.status != 600:
9496 raise Exception("Unexpected HTTP response: %d" % resp.status)
9497
9498 # No NewWLANEventMAC in PutWLANResponse NewMessage
9499 conn = HTTPConnection(url.netloc)
9500 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9501 newmsg="foo", neweventtype="1")
9502 if resp.status != 600:
9503 raise Exception("Unexpected HTTP response: %d" % resp.status)
9504
9505 # Invalid NewWLANEventMAC in PutWLANResponse NewMessage
9506 conn = HTTPConnection(url.netloc)
9507 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9508 newmsg="foo", neweventtype="1",
9509 neweventmac="foo")
9510 if resp.status != 600:
9511 raise Exception("Unexpected HTTP response: %d" % resp.status)
9512
9513 # Workaround for NewWLANEventMAC in PutWLANResponse NewMessage
9514 # Ignored unexpected PutWLANResponse WLANEventType 1
9515 conn = HTTPConnection(url.netloc)
9516 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9517 newmsg="foo", neweventtype="1",
9518 neweventmac="00.11.22.33.44.55")
9519 if resp.status != 500:
9520 raise Exception("Unexpected HTTP response: %d" % resp.status)
9521
9522 # PutWLANResponse NewMessage with invalid EAP message
9523 conn = HTTPConnection(url.netloc)
9524 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9525 newmsg="foo", neweventtype="2",
9526 neweventmac="00:11:22:33:44:55")
9527 if resp.status != 200:
9528 raise Exception("Unexpected HTTP response: %d" % resp.status)
9529
9530 with alloc_fail(hapd, 1, "web_connection_parse_subscribe"):
9531 conn = HTTPConnection(url.netloc)
9532 headers = {"callback": '<http://127.0.0.1:12345/event>',
9533 "NT": "upnp:event",
9534 "timeout": "Second-1234"}
9535 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9536 try:
9537 resp = conn.getresponse()
9538 except:
9539 pass
9540
9541 with alloc_fail(hapd, 1, "dup_binstr;web_connection_parse_subscribe"):
9542 conn = HTTPConnection(url.netloc)
9543 headers = {"callback": '<http://127.0.0.1:12345/event>',
9544 "NT": "upnp:event",
9545 "timeout": "Second-1234"}
9546 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9547 resp = conn.getresponse()
9548 if resp.status != 500:
9549 raise Exception("Unexpected HTTP response: %d" % resp.status)
9550
9551 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_parse_unsubscribe"):
9552 conn = HTTPConnection(url.netloc)
9553 headers = {"callback": '<http://127.0.0.1:12345/event>',
9554 "NT": "upnp:event",
9555 "timeout": "Second-1234"}
9556 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9557 try:
9558 resp = conn.getresponse()
9559 except:
9560 pass
9561
9562 with alloc_fail(hapd, 1, "web_connection_unimplemented"):
9563 conn = HTTPConnection(url.netloc)
9564 conn.request("HEAD", "/wps_device.xml")
9565 try:
9566 resp = conn.getresponse()
9567 except:
9568 pass
9569
9570 def test_ap_wps_frag_ack_oom(dev, apdev):
9571 """WPS and fragment ack OOM"""
9572 dev[0].request("SET wps_fragment_size 50")
9573 hapd = wps_start_ap(apdev[0])
9574 with alloc_fail(hapd, 1, "eap_wsc_build_frag_ack"):
9575 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
9576
9577 def wait_scan_stopped(dev):
9578 dev.request("ABORT_SCAN")
9579 for i in range(50):
9580 res = dev.get_driver_status_field("scan_state")
9581 if "SCAN_STARTED" not in res and "SCAN_REQUESTED" not in res:
9582 break
9583 logger.debug("Waiting for scan to complete")
9584 time.sleep(0.1)
9585
9586 @remote_compatible
9587 def test_ap_wps_eap_wsc_errors(dev, apdev):
9588 """WPS and EAP-WSC error cases"""
9589 ssid = "test-wps-conf-pin"
9590 appin = "12345670"
9591 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9592 "wpa_passphrase": "12345678", "wpa": "2",
9593 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9594 "fragment_size": "300", "ap_pin": appin}
9595 hapd = hostapd.add_ap(apdev[0], params)
9596 bssid = apdev[0]['bssid']
9597
9598 pin = dev[0].wps_read_pin()
9599 hapd.request("WPS_PIN any " + pin)
9600 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9601 dev[0].dump_monitor()
9602
9603 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK", "CCMP",
9604 "new passphrase", no_wait=True)
9605 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9606 if ev is None:
9607 raise Exception("WPS-FAIL not reported")
9608 dev[0].request("WPS_CANCEL")
9609 dev[0].wait_disconnected()
9610 wait_scan_stopped(dev[0])
9611 dev[0].dump_monitor()
9612
9613 dev[0].wps_reg(bssid, appin, "new ssid", "FOO", "CCMP",
9614 "new passphrase", no_wait=True)
9615 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9616 if ev is None:
9617 raise Exception("WPS-FAIL not reported")
9618 dev[0].request("WPS_CANCEL")
9619 dev[0].wait_disconnected()
9620 wait_scan_stopped(dev[0])
9621 dev[0].dump_monitor()
9622
9623 dev[0].wps_reg(bssid, appin, "new ssid", "WPA2PSK", "FOO",
9624 "new passphrase", no_wait=True)
9625 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9626 if ev is None:
9627 raise Exception("WPS-FAIL not reported")
9628 dev[0].request("WPS_CANCEL")
9629 dev[0].wait_disconnected()
9630 wait_scan_stopped(dev[0])
9631 dev[0].dump_monitor()
9632
9633 dev[0].wps_reg(bssid, appin + "new_key=a", "new ssid", "WPA2PSK", "CCMP",
9634 "new passphrase", no_wait=True)
9635 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9636 if ev is None:
9637 raise Exception("WPS-FAIL not reported")
9638 dev[0].request("WPS_CANCEL")
9639 dev[0].wait_disconnected()
9640 wait_scan_stopped(dev[0])
9641 dev[0].dump_monitor()
9642
9643 tests = ["eap_wsc_init",
9644 "eap_msg_alloc;eap_wsc_build_msg",
9645 "wpabuf_alloc;eap_wsc_process_fragment"]
9646 for func in tests:
9647 with alloc_fail(dev[0], 1, func):
9648 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
9649 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9650 dev[0].request("WPS_CANCEL")
9651 dev[0].wait_disconnected()
9652 wait_scan_stopped(dev[0])
9653 dev[0].dump_monitor()
9654
9655 tests = [(1, "wps_decrypt_encr_settings"),
9656 (2, "hmac_sha256;wps_derive_psk")]
9657 for count, func in tests:
9658 hapd.request("WPS_PIN any " + pin)
9659 with fail_test(dev[0], count, func):
9660 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
9661 wait_fail_trigger(dev[0], "GET_FAIL")
9662 dev[0].request("WPS_CANCEL")
9663 dev[0].wait_disconnected()
9664 wait_scan_stopped(dev[0])
9665 dev[0].dump_monitor()
9666
9667 with alloc_fail(dev[0], 1, "eap_msg_alloc;eap_sm_build_expanded_nak"):
9668 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK",
9669 "CCMP", "new passphrase", no_wait=True)
9670 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9671 dev[0].request("WPS_CANCEL")
9672 dev[0].wait_disconnected()
9673 wait_scan_stopped(dev[0])
9674 dev[0].dump_monitor()
9675
9676 def test_ap_wps_eap_wsc(dev, apdev):
9677 """WPS and EAP-WSC in network profile"""
9678 params = int_eap_server_params()
9679 params["wps_state"] = "2"
9680 hapd = hostapd.add_ap(apdev[0], params)
9681 bssid = apdev[0]['bssid']
9682
9683 logger.info("Unexpected identity")
9684 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9685 eap="WSC", identity="WFA-SimpleConfig-Enrollee-unexpected",
9686 wait_connect=False)
9687 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9688 if ev is None:
9689 raise Exception("No EAP-Failure seen")
9690 dev[0].request("REMOVE_NETWORK all")
9691 dev[0].wait_disconnected()
9692
9693 logger.info("No phase1 parameter")
9694 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9695 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9696 wait_connect=False)
9697 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9698 if ev is None:
9699 raise Exception("Timeout on EAP method start")
9700 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9701 if ev is None:
9702 raise Exception("No EAP-Failure seen")
9703 dev[0].request("REMOVE_NETWORK all")
9704 dev[0].wait_disconnected()
9705
9706 logger.info("No PIN/PBC in phase1")
9707 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9708 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9709 phase1="foo", wait_connect=False)
9710 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9711 if ev is None:
9712 raise Exception("Timeout on EAP method start")
9713 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9714 if ev is None:
9715 raise Exception("No EAP-Failure seen")
9716 dev[0].request("REMOVE_NETWORK all")
9717 dev[0].wait_disconnected()
9718
9719 logger.info("Invalid pkhash in phase1")
9720 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9721 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9722 phase1="foo pkhash=q pbc=1", wait_connect=False)
9723 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9724 if ev is None:
9725 raise Exception("Timeout on EAP method start")
9726 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9727 if ev is None:
9728 raise Exception("No EAP-Failure seen")
9729 dev[0].request("REMOVE_NETWORK all")
9730 dev[0].wait_disconnected()
9731
9732 logger.info("Zero fragment_size")
9733 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9734 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9735 fragment_size="0", phase1="pin=12345670", wait_connect=False)
9736 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9737 if ev is None:
9738 raise Exception("Timeout on EAP method start")
9739 ev = dev[0].wait_event(["WPS-M2D"], timeout=5)
9740 if ev is None:
9741 raise Exception("No M2D seen")
9742 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9743 if ev is None:
9744 raise Exception("No EAP-Failure seen")
9745 dev[0].request("REMOVE_NETWORK all")
9746 dev[0].wait_disconnected()
9747
9748 logger.info("Missing new_auth")
9749 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9750 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9751 phase1="pin=12345670 new_ssid=aa", wait_connect=False)
9752 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9753 if ev is None:
9754 raise Exception("Timeout on EAP method start")
9755 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9756 if ev is None:
9757 raise Exception("No EAP-Failure seen")
9758 dev[0].request("REMOVE_NETWORK all")
9759 dev[0].wait_disconnected()
9760
9761 logger.info("Missing new_encr")
9762 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9763 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9764 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa", wait_connect=False)
9765 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9766 if ev is None:
9767 raise Exception("Timeout on EAP method start")
9768 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9769 if ev is None:
9770 raise Exception("No EAP-Failure seen")
9771 dev[0].request("REMOVE_NETWORK all")
9772 dev[0].wait_disconnected()
9773
9774 logger.info("Missing new_key")
9775 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9776 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9777 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa new_encr=CCMP",
9778 wait_connect=False)
9779 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9780 if ev is None:
9781 raise Exception("Timeout on EAP method start")
9782 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9783 if ev is None:
9784 raise Exception("No EAP-Failure seen")
9785 dev[0].request("REMOVE_NETWORK all")
9786 dev[0].wait_disconnected()
9787
9788 def test_ap_wps_and_bss_limit(dev, apdev):
9789 """WPS and wpa_supplicant BSS entry limit"""
9790 try:
9791 _test_ap_wps_and_bss_limit(dev, apdev)
9792 finally:
9793 dev[0].request("SET bss_max_count 200")
9794 pass
9795
9796 def _test_ap_wps_and_bss_limit(dev, apdev):
9797 params = {"ssid": "test-wps", "eap_server": "1", "wps_state": "2",
9798 "wpa_passphrase": "12345678", "wpa": "2",
9799 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
9800 hapd = hostapd.add_ap(apdev[0], params)
9801
9802 params = {"ssid": "test-wps-2", "eap_server": "1", "wps_state": "2",
9803 "wpa_passphrase": "1234567890", "wpa": "2",
9804 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
9805 hapd2 = hostapd.add_ap(apdev[1], params)
9806
9807 id = dev[1].add_network()
9808 dev[1].set_network(id, "mode", "2")
9809 dev[1].set_network_quoted(id, "ssid", "wpas-ap-no-wps")
9810 dev[1].set_network_quoted(id, "psk", "12345678")
9811 dev[1].set_network(id, "frequency", "2462")
9812 dev[1].set_network(id, "scan_freq", "2462")
9813 dev[1].set_network(id, "wps_disabled", "1")
9814 dev[1].select_network(id)
9815
9816 id = dev[2].add_network()
9817 dev[2].set_network(id, "mode", "2")
9818 dev[2].set_network_quoted(id, "ssid", "wpas-ap")
9819 dev[2].set_network_quoted(id, "psk", "12345678")
9820 dev[2].set_network(id, "frequency", "2437")
9821 dev[2].set_network(id, "scan_freq", "2437")
9822 dev[2].select_network(id)
9823
9824 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9825 wpas.interface_add("wlan5")
9826 id = wpas.add_network()
9827 wpas.set_network(id, "mode", "2")
9828 wpas.set_network_quoted(id, "ssid", "wpas-ap")
9829 wpas.set_network_quoted(id, "psk", "12345678")
9830 wpas.set_network(id, "frequency", "2437")
9831 wpas.set_network(id, "scan_freq", "2437")
9832 wpas.select_network(id)
9833
9834 dev[1].wait_connected()
9835 dev[2].wait_connected()
9836 wpas.wait_connected()
9837 wpas.request("WPS_PIN any 12345670")
9838
9839 hapd.request("WPS_PBC")
9840 hapd2.request("WPS_PBC")
9841
9842 dev[0].request("SET bss_max_count 1")
9843
9844 id = dev[0].add_network()
9845 dev[0].set_network_quoted(id, "ssid", "testing")
9846
9847 id = dev[0].add_network()
9848 dev[0].set_network_quoted(id, "ssid", "testing")
9849 dev[0].set_network(id, "key_mgmt", "WPS")
9850
9851 dev[0].request("WPS_PBC")
9852 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
9853 dev[0].request("WPS_CANCEL")
9854
9855 id = dev[0].add_network()
9856 dev[0].set_network_quoted(id, "ssid", "testing")
9857 dev[0].set_network(id, "key_mgmt", "WPS")
9858
9859 dev[0].scan(freq="2412")
9860
9861 def test_ap_wps_pbc_2ap(dev, apdev):
9862 """WPS PBC with two APs advertising same SSID"""
9863 params = {"ssid": "wps", "eap_server": "1", "wps_state": "2",
9864 "wpa_passphrase": "12345678", "wpa": "2",
9865 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9866 "wps_independent": "1"}
9867 hapd = hostapd.add_ap(apdev[0], params)
9868 params = {"ssid": "wps", "eap_server": "1", "wps_state": "2",
9869 "wpa_passphrase": "123456789", "wpa": "2",
9870 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9871 "wps_independent": "1"}
9872 hapd2 = hostapd.add_ap(apdev[1], params)
9873 hapd.request("WPS_PBC")
9874
9875 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9876 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
9877 wpas.dump_monitor()
9878 wpas.flush_scan_cache()
9879
9880 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
9881 wpas.scan_for_bss(apdev[1]['bssid'], freq="2412")
9882 wpas.request("WPS_PBC")
9883 wpas.wait_connected()
9884 wpas.request("DISCONNECT")
9885 hapd.request("DISABLE")
9886 hapd2.request("DISABLE")
9887 wpas.flush_scan_cache()
9888
9889 def test_ap_wps_er_enrollee_to_conf_ap(dev, apdev):
9890 """WPS ER enrolling a new device to a configured AP"""
9891 try:
9892 _test_ap_wps_er_enrollee_to_conf_ap(dev, apdev)
9893 finally:
9894 dev[0].request("WPS_ER_STOP")
9895
9896 def _test_ap_wps_er_enrollee_to_conf_ap(dev, apdev):
9897 ssid = "wps-er-enrollee-to-conf-ap"
9898 ap_pin = "12345670"
9899 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9900 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9901 "wpa_passphrase": "12345678", "wpa": "2",
9902 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9903 "device_name": "Wireless AP", "manufacturer": "Company",
9904 "model_name": "WAP", "model_number": "123",
9905 "serial_number": "12345", "device_type": "6-0050F204-1",
9906 "os_version": "01020300",
9907 "config_methods": "label push_button",
9908 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
9909 hapd = hostapd.add_ap(apdev[0], params)
9910 bssid = hapd.own_addr()
9911
9912 id = dev[0].connect(ssid, psk="12345678", scan_freq="2412")
9913 dev[0].dump_monitor()
9914
9915 dev[0].request("WPS_ER_START ifname=lo")
9916 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
9917 if ev is None:
9918 raise Exception("AP discovery timed out")
9919 if ap_uuid not in ev:
9920 raise Exception("Expected AP UUID not found")
9921
9922 pin = dev[2].wps_read_pin()
9923 addr2 = dev[2].own_addr()
9924 dev[0].dump_monitor()
9925 dev[2].scan_for_bss(bssid, freq=2412)
9926 dev[2].dump_monitor()
9927 dev[2].request("WPS_PIN %s %s" % (bssid, pin))
9928
9929 for i in range(3):
9930 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
9931 if ev is None:
9932 raise Exception("Enrollee not seen")
9933 if addr2 in ev:
9934 break
9935 if addr2 not in ev:
9936 raise Exception("Unexpected Enrollee MAC address")
9937 dev[0].dump_monitor()
9938
9939 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " " + str(id))
9940 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
9941 dev[2].wait_connected(timeout=30)
9942 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
9943 if ev is None:
9944 raise Exception("WPS ER did not report success")
9945
9946 def test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev):
9947 """WPS ER enrolling a new device to a configured AP (2)"""
9948 try:
9949 _test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev)
9950 finally:
9951 dev[0].request("WPS_ER_STOP")
9952
9953 def _test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev):
9954 ssid = "wps-er-enrollee-to-conf-ap"
9955 ap_pin = "12345670"
9956 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9957 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9958 "wpa_passphrase": "12345678", "wpa": "2",
9959 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9960 "device_name": "Wireless AP", "manufacturer": "Company",
9961 "model_name": "WAP", "model_number": "123",
9962 "serial_number": "12345", "device_type": "6-0050F204-1",
9963 "os_version": "01020300",
9964 "config_methods": "label push_button",
9965 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
9966 hapd = hostapd.add_ap(apdev[0], params)
9967 bssid = hapd.own_addr()
9968
9969 id = dev[0].connect(ssid, psk="12345678", scan_freq="2412")
9970 dev[0].dump_monitor()
9971
9972 dev[0].request("WPS_ER_START ifname=lo")
9973 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
9974 if ev is None:
9975 raise Exception("AP discovery timed out")
9976 if ap_uuid not in ev:
9977 raise Exception("Expected AP UUID not found")
9978
9979 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
9980 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
9981 if ev is None:
9982 raise Exception("AP learn timed out")
9983 if ap_uuid not in ev:
9984 raise Exception("Expected AP UUID not in settings")
9985 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
9986 if ev is None:
9987 raise Exception("WPS-FAIL after AP learn timed out")
9988 time.sleep(0.1)
9989
9990 pin = dev[1].wps_read_pin()
9991 addr1 = dev[1].own_addr()
9992 dev[0].dump_monitor()
9993 dev[0].request("WPS_ER_PIN any " + pin)
9994 time.sleep(0.1)
9995 dev[1].scan_for_bss(bssid, freq=2412)
9996 dev[1].request("WPS_PIN any %s" % pin)
9997 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
9998 if ev is None:
9999 raise Exception("Enrollee did not report success")
10000 dev[1].wait_connected(timeout=15)
10001 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
10002 if ev is None:
10003 raise Exception("WPS ER did not report success")
10004
10005 def test_ap_wps_ignore_broadcast_ssid(dev, apdev):
10006 """WPS AP trying to ignore broadcast SSID"""
10007 ssid = "test-wps"
10008 hapd = hostapd.add_ap(apdev[0],
10009 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
10010 "ignore_broadcast_ssid": "1"})
10011 if "FAIL" not in hapd.request("WPS_PBC"):
10012 raise Exception("WPS unexpectedly enabled")
10013
10014 def test_ap_wps_wep(dev, apdev):
10015 """WPS AP trying to enable WEP"""
10016 ssid = "test-wps"
10017 hapd = hostapd.add_ap(apdev[0],
10018 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
10019 "ieee80211n": "0", "wep_key0": '"hello"'})
10020 if "FAIL" not in hapd.request("WPS_PBC"):
10021 raise Exception("WPS unexpectedly enabled")
10022
10023 def test_ap_wps_tkip(dev, apdev):
10024 """WPS AP trying to enable TKIP"""
10025 ssid = "test-wps"
10026 hapd = hostapd.add_ap(apdev[0],
10027 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
10028 "ieee80211n": "0", "wpa": '1',
10029 "wpa_key_mgmt": "WPA-PSK",
10030 "wpa_passphrase": "12345678"})
10031 if "FAIL" not in hapd.request("WPS_PBC"):
10032 raise Exception("WPS unexpectedly enabled")
10033
10034 def test_ap_wps_conf_dummy_cred(dev, apdev):
10035 """WPS PIN provisioning with configured AP using dummy cred"""
10036 ssid = "test-wps-conf"
10037 hapd = hostapd.add_ap(apdev[0],
10038 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10039 "wpa_passphrase": "12345678", "wpa": "2",
10040 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
10041 hapd.request("WPS_PIN any 12345670")
10042 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10043 dev[0].dump_monitor()
10044 try:
10045 hapd.set("wps_testing_dummy_cred", "1")
10046 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
10047 for i in range(1, 3):
10048 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
10049 if ev is None:
10050 raise Exception("WPS credential %d not received" % i)
10051 dev[0].wait_connected(timeout=30)
10052 finally:
10053 hapd.set("wps_testing_dummy_cred", "0")
10054
10055 def test_ap_wps_rf_bands(dev, apdev):
10056 """WPS and wps_rf_bands configuration"""
10057 ssid = "test-wps-conf"
10058 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10059 "wpa_passphrase": "12345678", "wpa": "2",
10060 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
10061 "wps_rf_bands": "ag"}
10062
10063 hapd = hostapd.add_ap(apdev[0], params)
10064 bssid = hapd.own_addr()
10065 hapd.request("WPS_PBC")
10066 dev[0].scan_for_bss(bssid, freq="2412")
10067 dev[0].dump_monitor()
10068 dev[0].request("WPS_PBC " + bssid)
10069 dev[0].wait_connected(timeout=30)
10070 bss = dev[0].get_bss(bssid)
10071 logger.info("BSS: " + str(bss))
10072 if "103c000103" not in bss['ie']:
10073 raise Exception("RF Bands attribute with expected values not found")
10074 dev[0].request("DISCONNECT")
10075 dev[0].wait_disconnected()
10076 hapd.set("wps_rf_bands", "ad")
10077 hapd.set("wps_rf_bands", "a")
10078 hapd.set("wps_rf_bands", "g")
10079 hapd.set("wps_rf_bands", "b")
10080 hapd.set("wps_rf_bands", "ga")
10081 hapd.disable()
10082 dev[0].dump_monitor()
10083 dev[0].flush_scan_cache()
10084
10085 def test_ap_wps_pbc_in_m1(dev, apdev):
10086 """WPS and pbc_in_m1"""
10087 ssid = "test-wps-conf"
10088 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10089 "wpa_passphrase": "12345678", "wpa": "2",
10090 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
10091 "config_methods": "virtual_push_button virtual_display",
10092 "pbc_in_m1": "1"}
10093
10094 hapd = hostapd.add_ap(apdev[0], params)
10095 bssid = hapd.own_addr()
10096 hapd.request("WPS_PBC")
10097 dev[0].scan_for_bss(bssid, freq="2412")
10098 dev[0].dump_monitor()
10099 dev[0].request("WPS_PBC " + bssid)
10100 dev[0].wait_connected(timeout=30)
10101 dev[0].request("DISCONNECT")
10102 dev[0].wait_disconnected()
10103 hapd.disable()
10104 dev[0].dump_monitor()
10105 dev[0].flush_scan_cache()
10106
10107 def test_ap_wps_pbc_mac_addr_change(dev, apdev, params):
10108 """WPS M1 with MAC address change"""
10109 ssid = "test-wps-mac-addr-change"
10110 hapd = hostapd.add_ap(apdev[0],
10111 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
10112 hapd.request("WPS_PBC")
10113 if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
10114 raise Exception("PBC status not shown correctly")
10115 dev[0].flush_scan_cache()
10116
10117 test_addr = '02:11:22:33:44:55'
10118 addr = dev[0].get_status_field("address")
10119 if addr == test_addr:
10120 raise Exception("Unexpected initial MAC address")
10121
10122 try:
10123 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'down'])
10124 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'address',
10125 test_addr])
10126 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'up'])
10127 addr1 = dev[0].get_status_field("address")
10128 if addr1 != test_addr:
10129 raise Exception("Failed to change MAC address")
10130
10131 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
10132 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
10133 dev[0].wait_connected(timeout=30)
10134 status = dev[0].get_status()
10135 if status['wpa_state'] != 'COMPLETED' or \
10136 status['bssid'] != apdev[0]['bssid']:
10137 raise Exception("Not fully connected")
10138
10139 out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
10140 "wps.message_type == 0x04",
10141 display=["wps.mac_address"])
10142 res = out.splitlines()
10143
10144 if len(res) < 1:
10145 raise Exception("No M1 message with MAC address found")
10146 if res[0] != addr1:
10147 raise Exception("Wrong M1 MAC address")
10148 dev[0].request("DISCONNECT")
10149 dev[0].wait_disconnected()
10150 hapd.disable()
10151 dev[0].dump_monitor()
10152 dev[0].flush_scan_cache()
10153 finally:
10154 # Restore MAC address
10155 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'down'])
10156 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'address',
10157 addr])
10158 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'up'])
10159
10160 def test_ap_wps_pin_start_failure(dev, apdev):
10161 """WPS_PIN start failure"""
10162 with alloc_fail(dev[0], 1, "wpas_wps_start_dev_pw"):
10163 if "FAIL" not in dev[0].request("WPS_PIN any 12345670"):
10164 raise Exception("WPS_PIN not rejected during OOM")
10165 with alloc_fail(dev[0], 1, "wpas_wps_start_dev_pw"):
10166 if "FAIL" not in dev[0].request("WPS_PIN any"):
10167 raise Exception("WPS_PIN not rejected during OOM")
10168
10169 def test_ap_wps_ap_pin_failure(dev, apdev):
10170 """WPS_AP_PIN failure"""
10171 id = dev[0].add_network()
10172 dev[0].set_network(id, "mode", "2")
10173 dev[0].set_network_quoted(id, "ssid", "wpas-ap-wps")
10174 dev[0].set_network_quoted(id, "psk", "1234567890")
10175 dev[0].set_network(id, "frequency", "2412")
10176 dev[0].set_network(id, "scan_freq", "2412")
10177 dev[0].select_network(id)
10178 dev[0].wait_connected()
10179
10180 with fail_test(dev[0], 1,
10181 "os_get_random;wpa_supplicant_ctrl_iface_wps_ap_pin"):
10182 if "FAIL" not in dev[0].request("WPS_AP_PIN random"):
10183 raise Exception("WPS_AP_PIN random accepted")
10184 with alloc_fail(dev[0], 1, "wpas_wps_ap_pin_set"):
10185 if "FAIL" not in dev[0].request("WPS_AP_PIN set 12345670"):
10186 raise Exception("WPS_AP_PIN set accepted")
10187
10188 dev[0].request("DISCONNECT")
10189 dev[0].wait_disconnected()
10190
10191 def test_ap_wps_random_uuid(dev, apdev, params):
10192 """WPS and random UUID on Enrollee"""
10193 ssid = "test-wps-conf"
10194 hapd = hostapd.add_ap(apdev[0],
10195 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10196 "wpa_passphrase": "12345678", "wpa": "2",
10197 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
10198
10199 config = os.path.join(params['logdir'], 'ap_wps_random_uuid.conf')
10200 with open(config, "w") as f:
10201 f.write("auto_uuid=1\n")
10202
10203 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
10204
10205 uuid = []
10206 for i in range(3):
10207 wpas.interface_add("wlan5", config=config)
10208
10209 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
10210 wpas.dump_monitor()
10211 wpas.request("WPS_PBC " + apdev[0]['bssid'])
10212
10213 ev = hapd.wait_event(["WPS-ENROLLEE-SEEN"], timeout=10)
10214 if ev is None:
10215 raise Exception("Enrollee not seen")
10216 uuid.append(ev.split(' ')[2])
10217 wpas.request("WPS_CANCEL")
10218 wpas.dump_monitor()
10219
10220 wpas.interface_remove("wlan5")
10221
10222 hapd.dump_monitor()
10223
10224 logger.info("Seen UUIDs: " + str(uuid))
10225 if uuid[0] == uuid[1] or uuid[0] == uuid[2] or uuid[1] == uuid[2]:
10226 raise Exception("Same UUID used multiple times")
10227
10228 def test_ap_wps_conf_pin_gcmp_128(dev, apdev):
10229 """WPS PIN provisioning with configured AP using GCMP-128"""
10230 run_ap_wps_conf_pin_cipher(dev, apdev, "GCMP")
10231
10232 def test_ap_wps_conf_pin_gcmp_256(dev, apdev):
10233 """WPS PIN provisioning with configured AP using GCMP-256"""
10234 run_ap_wps_conf_pin_cipher(dev, apdev, "GCMP-256")
10235
10236 def test_ap_wps_conf_pin_ccmp_256(dev, apdev):
10237 """WPS PIN provisioning with configured AP using CCMP-256"""
10238 run_ap_wps_conf_pin_cipher(dev, apdev, "CCMP-256")
10239
10240 def run_ap_wps_conf_pin_cipher(dev, apdev, cipher):
10241 if cipher not in dev[0].get_capability("pairwise"):
10242 raise HwsimSkip("Cipher %s not supported" % cipher)
10243 ssid = "test-wps-conf-pin"
10244 hapd = hostapd.add_ap(apdev[0],
10245 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10246 "wpa_passphrase": "12345678", "wpa": "2",
10247 "wpa_key_mgmt": "WPA-PSK",
10248 "rsn_pairwise": cipher})
10249 logger.info("WPS provisioning step")
10250 pin = dev[0].wps_read_pin()
10251 hapd.request("WPS_PIN any " + pin)
10252 dev[0].flush_scan_cache()
10253 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10254 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
10255 dev[0].wait_connected(timeout=15)
10256
10257 def test_ap_wps_and_sae(dev, apdev):
10258 """Initial AP configuration with first WPS Enrollee and adding SAE"""
10259 try:
10260 run_ap_wps_and_sae(dev, apdev)
10261 finally:
10262 dev[0].set("wps_cred_add_sae", "0")
10263
10264 def run_ap_wps_and_sae(dev, apdev):
10265 check_sae_capab(dev[0])
10266 ssid = "test-wps-sae"
10267 hapd = hostapd.add_ap(apdev[0],
10268 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
10269 "wps_cred_add_sae": "1"})
10270 logger.info("WPS provisioning step")
10271 pin = dev[0].wps_read_pin()
10272 hapd.request("WPS_PIN any " + pin)
10273
10274 dev[0].set("wps_cred_add_sae", "1")
10275 dev[0].request("SET sae_groups ")
10276 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
10277 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
10278 dev[0].wait_connected(timeout=30)
10279 status = dev[0].get_status()
10280 if status['key_mgmt'] != "SAE":
10281 raise Exception("SAE not used")
10282 if 'pmf' not in status or status['pmf'] != "1":
10283 raise Exception("PMF not enabled")
10284
10285 pin = dev[1].wps_read_pin()
10286 hapd.request("WPS_PIN any " + pin)
10287 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
10288 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
10289 dev[1].wait_connected(timeout=30)
10290 status = dev[1].get_status()
10291 if status['key_mgmt'] != "WPA2-PSK":
10292 raise Exception("WPA2-PSK not used")
10293 if 'pmf' in status:
10294 raise Exception("PMF enabled")
10295
10296 def test_ap_wps_conf_and_sae(dev, apdev):
10297 """WPS PBC provisioning with configured AP using PSK+SAE"""
10298 try:
10299 run_ap_wps_conf_and_sae(dev, apdev)
10300 finally:
10301 dev[0].set("wps_cred_add_sae", "0")
10302
10303 def run_ap_wps_conf_and_sae(dev, apdev):
10304 check_sae_capab(dev[0])
10305 ssid = "test-wps-conf-sae"
10306 hapd = hostapd.add_ap(apdev[0],
10307 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10308 "wpa_passphrase": "12345678", "wpa": "2",
10309 "ieee80211w": "1", "sae_require_mfp": "1",
10310 "wpa_key_mgmt": "WPA-PSK SAE",
10311 "rsn_pairwise": "CCMP"})
10312
10313 dev[0].set("wps_cred_add_sae", "1")
10314 dev[0].request("SET sae_groups ")
10315 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10316 pin = dev[0].wps_read_pin()
10317 hapd.request("WPS_PIN any " + pin)
10318 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
10319 dev[0].wait_connected(timeout=30)
10320 status = dev[0].get_status()
10321 if status['key_mgmt'] != "SAE":
10322 raise Exception("SAE not used")
10323 if 'pmf' not in status or status['pmf'] != "1":
10324 raise Exception("PMF not enabled")
10325
10326 dev[1].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
10327 key_mgmt="WPA-PSK", ieee80211w="0")
10328
10329 def test_ap_wps_reg_config_and_sae(dev, apdev):
10330 """WPS registrar configuring an AP using AP PIN and using PSK+SAE"""
10331 try:
10332 run_ap_wps_reg_config_and_sae(dev, apdev)
10333 finally:
10334 dev[0].set("wps_cred_add_sae", "0")
10335
10336 def run_ap_wps_reg_config_and_sae(dev, apdev):
10337 check_sae_capab(dev[0])
10338 ssid = "test-wps-init-ap-pin-sae"
10339 appin = "12345670"
10340 hostapd.add_ap(apdev[0],
10341 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10342 "ap_pin": appin, "wps_cred_add_sae": "1"})
10343 logger.info("WPS configuration step")
10344 dev[0].flush_scan_cache()
10345 dev[0].set("wps_cred_add_sae", "1")
10346 dev[0].request("SET sae_groups ")
10347 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
10348 dev[0].dump_monitor()
10349 new_ssid = "wps-new-ssid"
10350 new_passphrase = "1234567890"
10351 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
10352 new_passphrase)
10353 status = dev[0].get_status()
10354 if status['key_mgmt'] != "SAE":
10355 raise Exception("SAE not used")
10356 if 'pmf' not in status or status['pmf'] != "1":
10357 raise Exception("PMF not enabled")
10358
10359 dev[1].connect(new_ssid, psk=new_passphrase, scan_freq="2412", proto="WPA2",
10360 key_mgmt="WPA-PSK", ieee80211w="0")
10361
10362 def test_ap_wps_appl_ext(dev, apdev):
10363 """WPS Application Extension attribute"""
10364 ssid = "test-wps-conf"
10365 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10366 "wps_application_ext": 16*"11" + 5*"ee",
10367 "wpa_passphrase": "12345678", "wpa": "2",
10368 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
10369 hapd = hostapd.add_ap(apdev[0], params)
10370 pin = dev[0].wps_read_pin()
10371 hapd.request("WPS_PIN any " + pin)
10372 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10373 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
10374 dev[0].wait_connected(timeout=30)