]> git.ipfire.org Git - thirdparty/hostap.git/blob - tests/hwsim/test_ap_wps.py
60b36c2519d607fdaa099fbf054e4f8d1266b0ef
[thirdparty/hostap.git] / tests / hwsim / test_ap_wps.py
1 # WPS tests
2 # Copyright (c) 2013-2017, Jouni Malinen <j@w1.fi>
3 #
4 # This software may be distributed under the terms of the BSD license.
5 # See README for more details.
6
7 from remotehost import remote_compatible
8 import base64
9 import binascii
10 from Crypto.Cipher import AES
11 import hashlib
12 import hmac
13 import os
14 import time
15 import sys
16 import stat
17 import subprocess
18 import logging
19 logger = logging.getLogger()
20 import re
21 import socket
22 import struct
23 try:
24 from http.client import HTTPConnection
25 from urllib.request import urlopen
26 from urllib.parse import urlparse, urljoin
27 from urllib.error import HTTPError
28 from io import StringIO
29 from socketserver import StreamRequestHandler, TCPServer
30 except ImportError:
31 from httplib import HTTPConnection
32 from urllib import urlopen
33 from urlparse import urlparse, urljoin
34 from urllib2 import build_opener, ProxyHandler, HTTPError
35 from StringIO import StringIO
36 from SocketServer import StreamRequestHandler, TCPServer
37 import urllib
38 import xml.etree.ElementTree as ET
39
40 import hwsim_utils
41 import hostapd
42 from wpasupplicant import WpaSupplicant
43 from utils import HwsimSkip, alloc_fail, fail_test, skip_with_fips
44 from utils import wait_fail_trigger, clear_regdom
45 from test_ap_eap import int_eap_server_params
46
47 def wps_start_ap(apdev, ssid="test-wps-conf"):
48 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
49 "wpa_passphrase": "12345678", "wpa": "2",
50 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
51 return hostapd.add_ap(apdev, params)
52
53 @remote_compatible
54 def test_ap_wps_init(dev, apdev):
55 """Initial AP configuration with first WPS Enrollee"""
56 ssid = "test-wps"
57 hapd = hostapd.add_ap(apdev[0],
58 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
59 logger.info("WPS provisioning step")
60 hapd.request("WPS_PBC")
61 if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
62 raise Exception("PBC status not shown correctly")
63
64 id = dev[0].add_network()
65 dev[0].set_network_quoted(id, "ssid", "home")
66 dev[0].set_network_quoted(id, "psk", "12345678")
67 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
68
69 id = dev[0].add_network()
70 dev[0].set_network_quoted(id, "ssid", "home2")
71 dev[0].set_network(id, "bssid", "00:11:22:33:44:55")
72 dev[0].set_network(id, "key_mgmt", "NONE")
73 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
74
75 dev[0].request("WPS_PBC")
76 dev[0].wait_connected(timeout=30)
77 status = dev[0].get_status()
78 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
79 raise Exception("Not fully connected")
80 if status['ssid'] != ssid:
81 raise Exception("Unexpected SSID")
82 if status['pairwise_cipher'] != 'CCMP':
83 raise Exception("Unexpected encryption configuration")
84 if status['key_mgmt'] != 'WPA2-PSK':
85 raise Exception("Unexpected key_mgmt")
86
87 status = hapd.request("WPS_GET_STATUS")
88 if "PBC Status: Disabled" not in status:
89 raise Exception("PBC status not shown correctly")
90 if "Last WPS result: Success" not in status:
91 raise Exception("Last WPS result not shown correctly")
92 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
93 raise Exception("Peer address not shown correctly")
94 conf = hapd.request("GET_CONFIG")
95 if "wps_state=configured" not in conf:
96 raise Exception("AP not in WPS configured state")
97 if "wpa=3" not in conf:
98 raise Exception("AP not in WPA+WPA2 configuration")
99 if "rsn_pairwise_cipher=CCMP TKIP" not in conf:
100 raise Exception("Unexpected rsn_pairwise_cipher")
101 if "wpa_pairwise_cipher=CCMP TKIP" not in conf:
102 raise Exception("Unexpected wpa_pairwise_cipher")
103 if "group_cipher=TKIP" not in conf:
104 raise Exception("Unexpected group_cipher")
105
106 if len(dev[0].list_networks()) != 3:
107 raise Exception("Unexpected number of network blocks")
108
109 def test_ap_wps_init_2ap_pbc(dev, apdev):
110 """Initial two-radio AP configuration with first WPS PBC Enrollee"""
111 ssid = "test-wps"
112 params = {"ssid": ssid, "eap_server": "1", "wps_state": "1"}
113 hapd = hostapd.add_ap(apdev[0], params)
114 hostapd.add_ap(apdev[1], params)
115 logger.info("WPS provisioning step")
116 hapd.request("WPS_PBC")
117 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
118 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
119 bss = dev[0].get_bss(apdev[0]['bssid'])
120 if "[WPS-PBC]" not in bss['flags']:
121 raise Exception("WPS-PBC flag missing from AP1")
122 bss = dev[0].get_bss(apdev[1]['bssid'])
123 if "[WPS-PBC]" not in bss['flags']:
124 raise Exception("WPS-PBC flag missing from AP2")
125 dev[0].dump_monitor()
126 dev[0].request("SET wps_cred_processing 2")
127 dev[0].request("WPS_PBC")
128 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=30)
129 dev[0].request("SET wps_cred_processing 0")
130 if ev is None:
131 raise Exception("WPS cred event not seen")
132 if "100e" not in ev:
133 raise Exception("WPS attributes not included in the cred event")
134 dev[0].wait_connected(timeout=30)
135
136 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
137 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
138 bss = dev[1].get_bss(apdev[0]['bssid'])
139 if "[WPS-PBC]" in bss['flags']:
140 raise Exception("WPS-PBC flag not cleared from AP1")
141 bss = dev[1].get_bss(apdev[1]['bssid'])
142 if "[WPS-PBC]" in bss['flags']:
143 raise Exception("WPS-PBC flag not cleared from AP2")
144
145 def test_ap_wps_init_2ap_pin(dev, apdev):
146 """Initial two-radio AP configuration with first WPS PIN Enrollee"""
147 ssid = "test-wps"
148 params = {"ssid": ssid, "eap_server": "1", "wps_state": "1"}
149 hapd = hostapd.add_ap(apdev[0], params)
150 hostapd.add_ap(apdev[1], params)
151 logger.info("WPS provisioning step")
152 pin = dev[0].wps_read_pin()
153 hapd.request("WPS_PIN any " + pin)
154 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
155 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
156 bss = dev[0].get_bss(apdev[0]['bssid'])
157 if "[WPS-AUTH]" not in bss['flags']:
158 raise Exception("WPS-AUTH flag missing from AP1")
159 bss = dev[0].get_bss(apdev[1]['bssid'])
160 if "[WPS-AUTH]" not in bss['flags']:
161 raise Exception("WPS-AUTH flag missing from AP2")
162 dev[0].dump_monitor()
163 dev[0].request("WPS_PIN any " + pin)
164 dev[0].wait_connected(timeout=30)
165
166 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
167 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
168 bss = dev[1].get_bss(apdev[0]['bssid'])
169 if "[WPS-AUTH]" in bss['flags']:
170 raise Exception("WPS-AUTH flag not cleared from AP1")
171 bss = dev[1].get_bss(apdev[1]['bssid'])
172 if "[WPS-AUTH]" in bss['flags']:
173 raise Exception("WPS-AUTH flag not cleared from AP2")
174
175 @remote_compatible
176 def test_ap_wps_init_through_wps_config(dev, apdev):
177 """Initial AP configuration using wps_config command"""
178 ssid = "test-wps-init-config"
179 hapd = hostapd.add_ap(apdev[0],
180 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
181 if "FAIL" in hapd.request("WPS_CONFIG " + binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(b"12345678").decode()):
182 raise Exception("WPS_CONFIG command failed")
183 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
184 if ev is None:
185 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
186 # It takes some time for the AP to update Beacon and Probe Response frames,
187 # so wait here before requesting the scan to be started to avoid adding
188 # extra five second wait to the test due to fetching obsolete scan results.
189 hapd.ping()
190 time.sleep(0.2)
191 dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
192 pairwise="CCMP", group="CCMP")
193
194 if "FAIL" not in hapd.request("WPS_CONFIG foo"):
195 raise Exception("Invalid WPS_CONFIG accepted")
196
197 @remote_compatible
198 def test_ap_wps_init_through_wps_config_2(dev, apdev):
199 """AP configuration using wps_config and wps_cred_processing=2"""
200 ssid = "test-wps-init-config"
201 hapd = hostapd.add_ap(apdev[0],
202 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
203 "wps_cred_processing": "2"})
204 if "FAIL" in hapd.request("WPS_CONFIG " + binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(b"12345678").decode()):
205 raise Exception("WPS_CONFIG command failed")
206 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
207 if ev is None:
208 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
209 if "100e" not in ev:
210 raise Exception("WPS-NEW-AP-SETTINGS did not include Credential")
211
212 @remote_compatible
213 def test_ap_wps_invalid_wps_config_passphrase(dev, apdev):
214 """AP configuration using wps_config command with invalid passphrase"""
215 ssid = "test-wps-init-config"
216 hapd = hostapd.add_ap(apdev[0],
217 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
218 if "FAIL" not in hapd.request("WPS_CONFIG " + binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(b"1234567").decode()):
219 raise Exception("Invalid WPS_CONFIG command accepted")
220
221 def test_ap_wps_conf(dev, apdev):
222 """WPS PBC provisioning with configured AP"""
223 ssid = "test-wps-conf"
224 hapd = hostapd.add_ap(apdev[0],
225 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
226 "wpa_passphrase": "12345678", "wpa": "2",
227 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
228 logger.info("WPS provisioning step")
229 hapd.request("WPS_PBC")
230 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
231 dev[0].dump_monitor()
232 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
233 dev[0].wait_connected(timeout=30)
234 status = dev[0].get_status()
235 if status['wpa_state'] != 'COMPLETED':
236 raise Exception("Not fully connected")
237 if status['bssid'] != apdev[0]['bssid']:
238 raise Exception("Unexpected BSSID")
239 if status['ssid'] != ssid:
240 raise Exception("Unexpected SSID")
241 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
242 raise Exception("Unexpected encryption configuration")
243 if status['key_mgmt'] != 'WPA2-PSK':
244 raise Exception("Unexpected key_mgmt")
245
246 sta = hapd.get_sta(dev[0].p2p_interface_addr())
247 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
248 raise Exception("Device name not available in STA command")
249
250 def test_ap_wps_conf_5ghz(dev, apdev):
251 """WPS PBC provisioning with configured AP on 5 GHz band"""
252 try:
253 hapd = None
254 ssid = "test-wps-conf"
255 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
256 "wpa_passphrase": "12345678", "wpa": "2",
257 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
258 "country_code": "FI", "hw_mode": "a", "channel": "36"}
259 hapd = hostapd.add_ap(apdev[0], params)
260 logger.info("WPS provisioning step")
261 hapd.request("WPS_PBC")
262 dev[0].scan_for_bss(apdev[0]['bssid'], freq="5180")
263 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
264 dev[0].wait_connected(timeout=30)
265
266 sta = hapd.get_sta(dev[0].p2p_interface_addr())
267 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
268 raise Exception("Device name not available in STA command")
269 finally:
270 dev[0].request("DISCONNECT")
271 clear_regdom(hapd, dev)
272
273 def test_ap_wps_conf_chan14(dev, apdev):
274 """WPS PBC provisioning with configured AP on channel 14"""
275 try:
276 hapd = None
277 ssid = "test-wps-conf"
278 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
279 "wpa_passphrase": "12345678", "wpa": "2",
280 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
281 "country_code": "JP", "hw_mode": "b", "channel": "14"}
282 hapd = hostapd.add_ap(apdev[0], params)
283 logger.info("WPS provisioning step")
284 hapd.request("WPS_PBC")
285 dev[0].request("WPS_PBC")
286 dev[0].wait_connected(timeout=30)
287
288 sta = hapd.get_sta(dev[0].p2p_interface_addr())
289 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
290 raise Exception("Device name not available in STA command")
291 finally:
292 dev[0].request("DISCONNECT")
293 clear_regdom(hapd, dev)
294
295 @remote_compatible
296 def test_ap_wps_twice(dev, apdev):
297 """WPS provisioning with twice to change passphrase"""
298 ssid = "test-wps-twice"
299 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
300 "wpa_passphrase": "12345678", "wpa": "2",
301 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
302 hapd = hostapd.add_ap(apdev[0], params)
303 logger.info("WPS provisioning step")
304 hapd.request("WPS_PBC")
305 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
306 dev[0].dump_monitor()
307 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
308 dev[0].wait_connected(timeout=30)
309 dev[0].request("DISCONNECT")
310
311 logger.info("Restart AP with different passphrase and re-run WPS")
312 hostapd.remove_bss(apdev[0])
313 params['wpa_passphrase'] = 'another passphrase'
314 hapd = hostapd.add_ap(apdev[0], params)
315 logger.info("WPS provisioning step")
316 hapd.request("WPS_PBC")
317 dev[0].dump_monitor()
318 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
319 dev[0].wait_connected(timeout=30)
320 networks = dev[0].list_networks()
321 if len(networks) > 1:
322 raise Exception("Unexpected duplicated network block present")
323
324 @remote_compatible
325 def test_ap_wps_incorrect_pin(dev, apdev):
326 """WPS PIN provisioning with incorrect PIN"""
327 ssid = "test-wps-incorrect-pin"
328 hapd = hostapd.add_ap(apdev[0],
329 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
330 "wpa_passphrase": "12345678", "wpa": "2",
331 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
332
333 logger.info("WPS provisioning attempt 1")
334 hapd.request("WPS_PIN any 12345670")
335 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
336 dev[0].dump_monitor()
337 dev[0].request("WPS_PIN %s 55554444" % apdev[0]['bssid'])
338 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
339 if ev is None:
340 raise Exception("WPS operation timed out")
341 if "config_error=18" not in ev:
342 raise Exception("Incorrect config_error reported")
343 if "msg=8" not in ev:
344 raise Exception("PIN error detected on incorrect message")
345 dev[0].wait_disconnected(timeout=10)
346 dev[0].request("WPS_CANCEL")
347 # if a scan was in progress, wait for it to complete before trying WPS again
348 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
349
350 status = hapd.request("WPS_GET_STATUS")
351 if "Last WPS result: Failed" not in status:
352 raise Exception("WPS failure result not shown correctly")
353
354 logger.info("WPS provisioning attempt 2")
355 hapd.request("WPS_PIN any 12345670")
356 dev[0].dump_monitor()
357 dev[0].request("WPS_PIN %s 12344444" % apdev[0]['bssid'])
358 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
359 if ev is None:
360 raise Exception("WPS operation timed out")
361 if "config_error=18" not in ev:
362 raise Exception("Incorrect config_error reported")
363 if "msg=10" not in ev:
364 raise Exception("PIN error detected on incorrect message")
365 dev[0].wait_disconnected(timeout=10)
366
367 @remote_compatible
368 def test_ap_wps_conf_pin(dev, apdev):
369 """WPS PIN provisioning with configured AP"""
370 ssid = "test-wps-conf-pin"
371 hapd = hostapd.add_ap(apdev[0],
372 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
373 "wpa_passphrase": "12345678", "wpa": "2",
374 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
375 logger.info("WPS provisioning step")
376 pin = dev[0].wps_read_pin()
377 hapd.request("WPS_PIN any " + pin)
378 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
379 dev[0].dump_monitor()
380 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
381 dev[0].wait_connected(timeout=30)
382 status = dev[0].get_status()
383 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
384 raise Exception("Not fully connected")
385 if status['ssid'] != ssid:
386 raise Exception("Unexpected SSID")
387 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
388 raise Exception("Unexpected encryption configuration")
389 if status['key_mgmt'] != 'WPA2-PSK':
390 raise Exception("Unexpected key_mgmt")
391
392 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
393 bss = dev[1].get_bss(apdev[0]['bssid'])
394 if "[WPS-AUTH]" in bss['flags']:
395 raise Exception("WPS-AUTH flag not cleared")
396 logger.info("Try to connect from another station using the same PIN")
397 pin = dev[1].request("WPS_PIN " + apdev[0]['bssid'])
398 ev = dev[1].wait_event(["WPS-M2D", "CTRL-EVENT-CONNECTED"], timeout=30)
399 if ev is None:
400 raise Exception("Operation timed out")
401 if "WPS-M2D" not in ev:
402 raise Exception("Unexpected WPS operation started")
403 hapd.request("WPS_PIN any " + pin)
404 dev[1].wait_connected(timeout=30)
405
406 def test_ap_wps_conf_pin_mixed_mode(dev, apdev):
407 """WPS PIN provisioning with configured AP (WPA+WPA2)"""
408 ssid = "test-wps-conf-pin-mixed"
409 hapd = hostapd.add_ap(apdev[0],
410 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
411 "wpa_passphrase": "12345678", "wpa": "3",
412 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
413 "wpa_pairwise": "TKIP"})
414
415 logger.info("WPS provisioning step")
416 pin = dev[0].wps_read_pin()
417 hapd.request("WPS_PIN any " + pin)
418 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
419 dev[0].dump_monitor()
420 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
421 dev[0].wait_connected(timeout=30)
422 status = dev[0].get_status()
423 dev[0].request("REMOVE_NETWORK all")
424 dev[0].wait_disconnected()
425 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
426 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
427
428 logger.info("WPS provisioning step (auth_types=0x1b)")
429 if "OK" not in dev[0].request("SET wps_force_auth_types 0x1b"):
430 raise Exception("Failed to set wps_force_auth_types 0x1b")
431 pin = dev[0].wps_read_pin()
432 hapd.request("WPS_PIN any " + pin)
433 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
434 dev[0].dump_monitor()
435 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
436 dev[0].wait_connected(timeout=30)
437 status = dev[0].get_status()
438 dev[0].request("REMOVE_NETWORK all")
439 dev[0].wait_disconnected()
440 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
441 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
442
443 logger.info("WPS provisioning step (auth_types=0 encr_types=0)")
444 if "OK" not in dev[0].request("SET wps_force_auth_types 0"):
445 raise Exception("Failed to set wps_force_auth_types 0")
446 if "OK" not in dev[0].request("SET wps_force_encr_types 0"):
447 raise Exception("Failed to set wps_force_encr_types 0")
448 pin = dev[0].wps_read_pin()
449 hapd.request("WPS_PIN any " + pin)
450 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
451 dev[0].dump_monitor()
452 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
453 dev[0].wait_connected(timeout=30)
454 status = dev[0].get_status()
455 dev[0].request("REMOVE_NETWORK all")
456 dev[0].wait_disconnected()
457 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
458 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
459
460 dev[0].request("SET wps_force_auth_types ")
461 dev[0].request("SET wps_force_encr_types ")
462
463 @remote_compatible
464 def test_ap_wps_conf_pin_v1(dev, apdev):
465 """WPS PIN provisioning with configured WPS v1.0 AP"""
466 ssid = "test-wps-conf-pin-v1"
467 hapd = hostapd.add_ap(apdev[0],
468 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
469 "wpa_passphrase": "12345678", "wpa": "2",
470 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
471 logger.info("WPS provisioning step")
472 pin = dev[0].wps_read_pin()
473 hapd.request("SET wps_version_number 0x10")
474 hapd.request("WPS_PIN any " + pin)
475 found = False
476 for i in range(0, 10):
477 dev[0].scan(freq="2412")
478 if "[WPS-PIN]" in dev[0].request("SCAN_RESULTS"):
479 found = True
480 break
481 if not found:
482 hapd.request("SET wps_version_number 0x20")
483 raise Exception("WPS-PIN flag not seen in scan results")
484 dev[0].dump_monitor()
485 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
486 dev[0].wait_connected(timeout=30)
487 hapd.request("SET wps_version_number 0x20")
488
489 @remote_compatible
490 def test_ap_wps_conf_pin_2sta(dev, apdev):
491 """Two stations trying to use WPS PIN at the same time"""
492 ssid = "test-wps-conf-pin2"
493 hapd = hostapd.add_ap(apdev[0],
494 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
495 "wpa_passphrase": "12345678", "wpa": "2",
496 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
497 logger.info("WPS provisioning step")
498 pin = "12345670"
499 pin2 = "55554444"
500 hapd.request("WPS_PIN " + dev[0].get_status_field("uuid") + " " + pin)
501 hapd.request("WPS_PIN " + dev[1].get_status_field("uuid") + " " + pin)
502 dev[0].dump_monitor()
503 dev[1].dump_monitor()
504 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
505 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
506 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
507 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
508 dev[0].wait_connected(timeout=30)
509 dev[1].wait_connected(timeout=30)
510
511 @remote_compatible
512 def test_ap_wps_conf_pin_timeout(dev, apdev):
513 """WPS PIN provisioning with configured AP timing out PIN"""
514 ssid = "test-wps-conf-pin"
515 hapd = hostapd.add_ap(apdev[0],
516 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
517 "wpa_passphrase": "12345678", "wpa": "2",
518 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
519 addr = dev[0].p2p_interface_addr()
520 pin = dev[0].wps_read_pin()
521 if "FAIL" not in hapd.request("WPS_PIN "):
522 raise Exception("Unexpected success on invalid WPS_PIN")
523 hapd.request("WPS_PIN any " + pin + " 1")
524 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
525 time.sleep(1.1)
526 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
527 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=20)
528 if ev is None:
529 raise Exception("WPS-PIN-NEEDED event timed out")
530 ev = dev[0].wait_event(["WPS-M2D"])
531 if ev is None:
532 raise Exception("M2D not reported")
533 dev[0].request("WPS_CANCEL")
534
535 hapd.request("WPS_PIN any " + pin + " 20 " + addr)
536 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
537 dev[0].wait_connected(timeout=30)
538
539 def test_ap_wps_reg_connect(dev, apdev):
540 """WPS registrar using AP PIN to connect"""
541 ssid = "test-wps-reg-ap-pin"
542 appin = "12345670"
543 hostapd.add_ap(apdev[0],
544 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
545 "wpa_passphrase": "12345678", "wpa": "2",
546 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
547 "ap_pin": appin})
548 logger.info("WPS provisioning step")
549 dev[0].dump_monitor()
550 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
551 dev[0].wps_reg(apdev[0]['bssid'], appin)
552 status = dev[0].get_status()
553 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
554 raise Exception("Not fully connected")
555 if status['ssid'] != ssid:
556 raise Exception("Unexpected SSID")
557 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
558 raise Exception("Unexpected encryption configuration")
559 if status['key_mgmt'] != 'WPA2-PSK':
560 raise Exception("Unexpected key_mgmt")
561
562 def test_ap_wps_reg_connect_zero_len_ap_pin(dev, apdev):
563 """hostapd with zero length ap_pin parameter"""
564 ssid = "test-wps-reg-ap-pin"
565 appin = ""
566 hostapd.add_ap(apdev[0],
567 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
568 "wpa_passphrase": "12345678", "wpa": "2",
569 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
570 "ap_pin": appin})
571 logger.info("WPS provisioning step")
572 dev[0].dump_monitor()
573 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
574 dev[0].wps_reg(apdev[0]['bssid'], appin, no_wait=True)
575 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
576 if ev is None:
577 raise Exception("No WPS-FAIL reported")
578 if "msg=5 config_error=15" not in ev:
579 raise Exception("Unexpected WPS-FAIL: " + ev)
580
581 def test_ap_wps_reg_connect_mixed_mode(dev, apdev):
582 """WPS registrar using AP PIN to connect (WPA+WPA2)"""
583 ssid = "test-wps-reg-ap-pin"
584 appin = "12345670"
585 hostapd.add_ap(apdev[0],
586 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
587 "wpa_passphrase": "12345678", "wpa": "3",
588 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
589 "wpa_pairwise": "TKIP", "ap_pin": appin})
590 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
591 dev[0].wps_reg(apdev[0]['bssid'], appin)
592 status = dev[0].get_status()
593 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
594 raise Exception("Not fully connected")
595 if status['ssid'] != ssid:
596 raise Exception("Unexpected SSID")
597 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
598 raise Exception("Unexpected encryption configuration")
599 if status['key_mgmt'] != 'WPA2-PSK':
600 raise Exception("Unexpected key_mgmt")
601
602 def test_ap_wps_reg_override_ap_settings(dev, apdev):
603 """WPS registrar and ap_settings override"""
604 ap_settings = "/tmp/ap_wps_reg_override_ap_settings"
605 try:
606 os.remove(ap_settings)
607 except:
608 pass
609 # Override AP Settings with values that point to another AP
610 data = build_wsc_attr(ATTR_NETWORK_INDEX, b'\x01')
611 data += build_wsc_attr(ATTR_SSID, b"test")
612 data += build_wsc_attr(ATTR_AUTH_TYPE, b'\x00\x01')
613 data += build_wsc_attr(ATTR_ENCR_TYPE, b'\x00\x01')
614 data += build_wsc_attr(ATTR_NETWORK_KEY, b'')
615 data += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[1]['bssid'].replace(':', '')))
616 with open(ap_settings, "wb") as f:
617 f.write(data)
618 ssid = "test-wps-reg-ap-pin"
619 appin = "12345670"
620 hostapd.add_ap(apdev[0],
621 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
622 "wpa_passphrase": "12345678", "wpa": "2",
623 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
624 "ap_pin": appin, "ap_settings": ap_settings})
625 hapd2 = hostapd.add_ap(apdev[1], {"ssid": "test"})
626 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
627 dev[0].scan_for_bss(apdev[1]['bssid'], freq=2412)
628 dev[0].wps_reg(apdev[0]['bssid'], appin)
629 ev = hapd2.wait_event(['AP-STA-CONNECTED'], timeout=10)
630 os.remove(ap_settings)
631 if ev is None:
632 raise Exception("No connection with the other AP")
633
634 def check_wps_reg_failure(dev, ap, appin):
635 dev.request("WPS_REG " + ap['bssid'] + " " + appin)
636 ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
637 if ev is None:
638 raise Exception("WPS operation timed out")
639 if "WPS-SUCCESS" in ev:
640 raise Exception("WPS operation succeeded unexpectedly")
641 if "config_error=15" not in ev:
642 raise Exception("WPS setup locked state was not reported correctly")
643
644 def test_ap_wps_random_ap_pin(dev, apdev):
645 """WPS registrar using random AP PIN"""
646 ssid = "test-wps-reg-random-ap-pin"
647 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
648 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
649 "wpa_passphrase": "12345678", "wpa": "2",
650 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
651 "device_name": "Wireless AP", "manufacturer": "Company",
652 "model_name": "WAP", "model_number": "123",
653 "serial_number": "12345", "device_type": "6-0050F204-1",
654 "os_version": "01020300",
655 "config_methods": "label push_button",
656 "uuid": ap_uuid, "upnp_iface": "lo"}
657 hapd = hostapd.add_ap(apdev[0], params)
658 appin = hapd.request("WPS_AP_PIN random")
659 if "FAIL" in appin:
660 raise Exception("Could not generate random AP PIN")
661 if appin not in hapd.request("WPS_AP_PIN get"):
662 raise Exception("Could not fetch current AP PIN")
663 logger.info("WPS provisioning step")
664 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
665 dev[0].wps_reg(apdev[0]['bssid'], appin)
666
667 hapd.request("WPS_AP_PIN disable")
668 logger.info("WPS provisioning step with AP PIN disabled")
669 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
670 check_wps_reg_failure(dev[1], apdev[0], appin)
671
672 logger.info("WPS provisioning step with AP PIN reset")
673 appin = "12345670"
674 hapd.request("WPS_AP_PIN set " + appin)
675 dev[1].wps_reg(apdev[0]['bssid'], appin)
676 dev[0].request("REMOVE_NETWORK all")
677 dev[1].request("REMOVE_NETWORK all")
678 dev[0].wait_disconnected(timeout=10)
679 dev[1].wait_disconnected(timeout=10)
680
681 logger.info("WPS provisioning step after AP PIN timeout")
682 hapd.request("WPS_AP_PIN disable")
683 appin = hapd.request("WPS_AP_PIN random 1")
684 time.sleep(1.1)
685 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
686 raise Exception("AP PIN unexpectedly still enabled")
687 check_wps_reg_failure(dev[0], apdev[0], appin)
688
689 logger.info("WPS provisioning step after AP PIN timeout(2)")
690 hapd.request("WPS_AP_PIN disable")
691 appin = "12345670"
692 hapd.request("WPS_AP_PIN set " + appin + " 1")
693 time.sleep(1.1)
694 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
695 raise Exception("AP PIN unexpectedly still enabled")
696 check_wps_reg_failure(dev[1], apdev[0], appin)
697
698 with fail_test(hapd, 1, "os_get_random;wps_generate_pin"):
699 hapd.request("WPS_AP_PIN random 1")
700 hapd.request("WPS_AP_PIN disable")
701
702 with alloc_fail(hapd, 1, "upnp_wps_set_ap_pin"):
703 hapd.request("WPS_AP_PIN set 12345670")
704 hapd.request("WPS_AP_PIN disable")
705
706 if "FAIL" not in hapd.request("WPS_AP_PIN set"):
707 raise Exception("Invalid WPS_AP_PIN accepted")
708 if "FAIL" not in hapd.request("WPS_AP_PIN foo"):
709 raise Exception("Invalid WPS_AP_PIN accepted")
710
711 def test_ap_wps_reg_config(dev, apdev):
712 """WPS registrar configuring an AP using AP PIN"""
713 ssid = "test-wps-init-ap-pin"
714 appin = "12345670"
715 hostapd.add_ap(apdev[0],
716 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
717 "ap_pin": appin})
718 logger.info("WPS configuration step")
719 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
720 dev[0].dump_monitor()
721 new_ssid = "wps-new-ssid"
722 new_passphrase = "1234567890"
723 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
724 new_passphrase)
725 status = dev[0].get_status()
726 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
727 raise Exception("Not fully connected")
728 if status['ssid'] != new_ssid:
729 raise Exception("Unexpected SSID")
730 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
731 raise Exception("Unexpected encryption configuration")
732 if status['key_mgmt'] != 'WPA2-PSK':
733 raise Exception("Unexpected key_mgmt")
734
735 logger.info("Re-configure back to open")
736 dev[0].request("REMOVE_NETWORK all")
737 dev[0].flush_scan_cache()
738 dev[0].dump_monitor()
739 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-open", "OPEN", "NONE", "")
740 status = dev[0].get_status()
741 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
742 raise Exception("Not fully connected")
743 if status['ssid'] != "wps-open":
744 raise Exception("Unexpected SSID")
745 if status['key_mgmt'] != 'NONE':
746 raise Exception("Unexpected key_mgmt")
747
748 def test_ap_wps_reg_config_ext_processing(dev, apdev):
749 """WPS registrar configuring an AP with external config processing"""
750 ssid = "test-wps-init-ap-pin"
751 appin = "12345670"
752 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
753 "wps_cred_processing": "1", "ap_pin": appin}
754 hapd = hostapd.add_ap(apdev[0], params)
755 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
756 new_ssid = "wps-new-ssid"
757 new_passphrase = "1234567890"
758 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
759 new_passphrase, no_wait=True)
760 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
761 if ev is None:
762 raise Exception("WPS registrar operation timed out")
763 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=15)
764 if ev is None:
765 raise Exception("WPS configuration timed out")
766 if "1026" not in ev:
767 raise Exception("AP Settings missing from event")
768 hapd.request("SET wps_cred_processing 0")
769 if "FAIL" in hapd.request("WPS_CONFIG " + binascii.hexlify(new_ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(new_passphrase.encode()).decode()):
770 raise Exception("WPS_CONFIG command failed")
771 dev[0].wait_connected(timeout=15)
772
773 def test_ap_wps_reg_config_tkip(dev, apdev):
774 """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
775 skip_with_fips(dev[0])
776 ssid = "test-wps-init-ap"
777 appin = "12345670"
778 hostapd.add_ap(apdev[0],
779 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
780 "ap_pin": appin})
781 logger.info("WPS configuration step")
782 dev[0].request("SET wps_version_number 0x10")
783 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
784 dev[0].dump_monitor()
785 new_ssid = "wps-new-ssid-with-tkip"
786 new_passphrase = "1234567890"
787 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
788 new_passphrase)
789 logger.info("Re-connect to verify WPA2 mixed mode")
790 dev[0].request("DISCONNECT")
791 id = 0
792 dev[0].set_network(id, "pairwise", "CCMP")
793 dev[0].set_network(id, "proto", "RSN")
794 dev[0].connect_network(id)
795 status = dev[0].get_status()
796 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
797 raise Exception("Not fully connected: wpa_state={} bssid={}".format(status['wpa_state'], status['bssid']))
798 if status['ssid'] != new_ssid:
799 raise Exception("Unexpected SSID")
800 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
801 raise Exception("Unexpected encryption configuration")
802 if status['key_mgmt'] != 'WPA2-PSK':
803 raise Exception("Unexpected key_mgmt")
804
805 def test_ap_wps_setup_locked(dev, apdev):
806 """WPS registrar locking up AP setup on AP PIN failures"""
807 ssid = "test-wps-incorrect-ap-pin"
808 appin = "12345670"
809 hapd = hostapd.add_ap(apdev[0],
810 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
811 "wpa_passphrase": "12345678", "wpa": "2",
812 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
813 "ap_pin": appin})
814 new_ssid = "wps-new-ssid-test"
815 new_passphrase = "1234567890"
816
817 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
818 ap_setup_locked = False
819 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
820 dev[0].dump_monitor()
821 logger.info("Try incorrect AP PIN - attempt " + pin)
822 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
823 "CCMP", new_passphrase, no_wait=True)
824 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
825 if ev is None:
826 raise Exception("Timeout on receiving WPS operation failure event")
827 if "CTRL-EVENT-CONNECTED" in ev:
828 raise Exception("Unexpected connection")
829 if "config_error=15" in ev:
830 logger.info("AP Setup Locked")
831 ap_setup_locked = True
832 elif "config_error=18" not in ev:
833 raise Exception("config_error=18 not reported")
834 dev[0].wait_disconnected(timeout=10)
835 time.sleep(0.1)
836 if not ap_setup_locked:
837 raise Exception("AP setup was not locked")
838 dev[0].request("WPS_CANCEL")
839 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True,
840 only_new=True)
841 bss = dev[0].get_bss(apdev[0]['bssid'])
842 if 'wps_ap_setup_locked' not in bss or bss['wps_ap_setup_locked'] != '1':
843 logger.info("BSS: " + str(bss))
844 raise Exception("AP Setup Locked not indicated in scan results")
845
846 status = hapd.request("WPS_GET_STATUS")
847 if "Last WPS result: Failed" not in status:
848 raise Exception("WPS failure result not shown correctly")
849 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
850 raise Exception("Peer address not shown correctly")
851
852 time.sleep(0.5)
853 dev[0].dump_monitor()
854 logger.info("WPS provisioning step")
855 pin = dev[0].wps_read_pin()
856 hapd.request("WPS_PIN any " + pin)
857 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
858 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
859 if ev is None:
860 raise Exception("WPS success was not reported")
861 dev[0].wait_connected(timeout=30)
862
863 appin = hapd.request("WPS_AP_PIN random")
864 if "FAIL" in appin:
865 raise Exception("Could not generate random AP PIN")
866 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=10)
867 if ev is None:
868 raise Exception("Failed to unlock AP PIN")
869
870 def test_ap_wps_setup_locked_timeout(dev, apdev):
871 """WPS re-enabling AP PIN after timeout"""
872 ssid = "test-wps-incorrect-ap-pin"
873 appin = "12345670"
874 hapd = hostapd.add_ap(apdev[0],
875 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
876 "wpa_passphrase": "12345678", "wpa": "2",
877 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
878 "ap_pin": appin})
879 new_ssid = "wps-new-ssid-test"
880 new_passphrase = "1234567890"
881
882 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
883 ap_setup_locked = False
884 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
885 dev[0].dump_monitor()
886 logger.info("Try incorrect AP PIN - attempt " + pin)
887 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
888 "CCMP", new_passphrase, no_wait=True)
889 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"], timeout=15)
890 if ev is None:
891 raise Exception("Timeout on receiving WPS operation failure event")
892 if "CTRL-EVENT-CONNECTED" in ev:
893 raise Exception("Unexpected connection")
894 if "config_error=15" in ev:
895 logger.info("AP Setup Locked")
896 ap_setup_locked = True
897 break
898 elif "config_error=18" not in ev:
899 raise Exception("config_error=18 not reported")
900 dev[0].wait_disconnected(timeout=10)
901 time.sleep(0.1)
902 if not ap_setup_locked:
903 raise Exception("AP setup was not locked")
904 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=80)
905 if ev is None:
906 raise Exception("AP PIN did not get unlocked on 60 second timeout")
907
908 def test_ap_wps_setup_locked_2(dev, apdev):
909 """WPS AP configured for special ap_setup_locked=2 mode"""
910 ssid = "test-wps-ap-pin"
911 appin = "12345670"
912 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
913 "wpa_passphrase": "12345678", "wpa": "2",
914 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
915 "ap_pin": appin, "ap_setup_locked": "2"}
916 hapd = hostapd.add_ap(apdev[0], params)
917 new_ssid = "wps-new-ssid-test"
918 new_passphrase = "1234567890"
919
920 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
921 dev[0].wps_reg(apdev[0]['bssid'], appin)
922 dev[0].request("REMOVE_NETWORK all")
923 dev[0].wait_disconnected()
924
925 hapd.dump_monitor()
926 dev[0].dump_monitor()
927 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK",
928 "CCMP", new_passphrase, no_wait=True)
929
930 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
931 if ev is None:
932 raise Exception("hostapd did not report WPS failure")
933 if "msg=12 config_error=15" not in ev:
934 raise Exception("Unexpected failure reason (AP): " + ev)
935
936 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
937 if ev is None:
938 raise Exception("Timeout on receiving WPS operation failure event")
939 if "CTRL-EVENT-CONNECTED" in ev:
940 raise Exception("Unexpected connection")
941 if "config_error=15" not in ev:
942 raise Exception("Unexpected failure reason (STA): " + ev)
943 dev[0].request("WPS_CANCEL")
944 dev[0].wait_disconnected()
945
946 @remote_compatible
947 def test_ap_wps_pbc_overlap_2ap(dev, apdev):
948 """WPS PBC session overlap with two active APs"""
949 params = {"ssid": "wps1", "eap_server": "1", "wps_state": "2",
950 "wpa_passphrase": "12345678", "wpa": "2",
951 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
952 "wps_independent": "1"}
953 hapd = hostapd.add_ap(apdev[0], params)
954 params = {"ssid": "wps2", "eap_server": "1", "wps_state": "2",
955 "wpa_passphrase": "123456789", "wpa": "2",
956 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
957 "wps_independent": "1"}
958 hapd2 = hostapd.add_ap(apdev[1], params)
959 hapd.request("WPS_PBC")
960 hapd2.request("WPS_PBC")
961 logger.info("WPS provisioning step")
962 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
963 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
964 dev[0].request("WPS_PBC")
965 ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
966 if ev is None:
967 raise Exception("PBC session overlap not detected")
968 hapd.request("DISABLE")
969 hapd2.request("DISABLE")
970 dev[0].flush_scan_cache()
971
972 @remote_compatible
973 def test_ap_wps_pbc_overlap_2sta(dev, apdev):
974 """WPS PBC session overlap with two active STAs"""
975 ssid = "test-wps-pbc-overlap"
976 hapd = hostapd.add_ap(apdev[0],
977 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
978 "wpa_passphrase": "12345678", "wpa": "2",
979 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
980 logger.info("WPS provisioning step")
981 hapd.request("WPS_PBC")
982 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
983 dev[0].dump_monitor()
984 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
985 dev[1].dump_monitor()
986 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
987 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
988 ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
989 if ev is None:
990 raise Exception("PBC session overlap not detected (dev0)")
991 if "config_error=12" not in ev:
992 raise Exception("PBC session overlap not correctly reported (dev0)")
993 dev[0].request("WPS_CANCEL")
994 dev[0].request("DISCONNECT")
995 ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
996 if ev is None:
997 raise Exception("PBC session overlap not detected (dev1)")
998 if "config_error=12" not in ev:
999 raise Exception("PBC session overlap not correctly reported (dev1)")
1000 dev[1].request("WPS_CANCEL")
1001 dev[1].request("DISCONNECT")
1002 hapd.request("WPS_CANCEL")
1003 ret = hapd.request("WPS_PBC")
1004 if "FAIL" not in ret:
1005 raise Exception("PBC mode allowed to be started while PBC overlap still active")
1006 hapd.request("DISABLE")
1007 dev[0].flush_scan_cache()
1008 dev[1].flush_scan_cache()
1009
1010 @remote_compatible
1011 def test_ap_wps_cancel(dev, apdev):
1012 """WPS AP cancelling enabled config method"""
1013 ssid = "test-wps-ap-cancel"
1014 hapd = hostapd.add_ap(apdev[0],
1015 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1016 "wpa_passphrase": "12345678", "wpa": "2",
1017 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
1018 bssid = apdev[0]['bssid']
1019
1020 logger.info("Verify PBC enable/cancel")
1021 hapd.request("WPS_PBC")
1022 dev[0].scan(freq="2412")
1023 dev[0].scan(freq="2412")
1024 bss = dev[0].get_bss(apdev[0]['bssid'])
1025 if "[WPS-PBC]" not in bss['flags']:
1026 raise Exception("WPS-PBC flag missing")
1027 if "FAIL" in hapd.request("WPS_CANCEL"):
1028 raise Exception("WPS_CANCEL failed")
1029 dev[0].scan(freq="2412")
1030 dev[0].scan(freq="2412")
1031 bss = dev[0].get_bss(apdev[0]['bssid'])
1032 if "[WPS-PBC]" in bss['flags']:
1033 raise Exception("WPS-PBC flag not cleared")
1034
1035 logger.info("Verify PIN enable/cancel")
1036 hapd.request("WPS_PIN any 12345670")
1037 dev[0].scan(freq="2412")
1038 dev[0].scan(freq="2412")
1039 bss = dev[0].get_bss(apdev[0]['bssid'])
1040 if "[WPS-AUTH]" not in bss['flags']:
1041 raise Exception("WPS-AUTH flag missing")
1042 if "FAIL" in hapd.request("WPS_CANCEL"):
1043 raise Exception("WPS_CANCEL failed")
1044 dev[0].scan(freq="2412")
1045 dev[0].scan(freq="2412")
1046 bss = dev[0].get_bss(apdev[0]['bssid'])
1047 if "[WPS-AUTH]" in bss['flags']:
1048 raise Exception("WPS-AUTH flag not cleared")
1049
1050 def test_ap_wps_er_add_enrollee(dev, apdev):
1051 """WPS ER configuring AP and adding a new enrollee using PIN"""
1052 try:
1053 _test_ap_wps_er_add_enrollee(dev, apdev)
1054 finally:
1055 dev[0].request("WPS_ER_STOP")
1056
1057 def _test_ap_wps_er_add_enrollee(dev, apdev):
1058 ssid = "wps-er-add-enrollee"
1059 ap_pin = "12345670"
1060 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1061 hostapd.add_ap(apdev[0],
1062 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
1063 "device_name": "Wireless AP", "manufacturer": "Company",
1064 "model_name": "WAP", "model_number": "123",
1065 "serial_number": "12345", "device_type": "6-0050F204-1",
1066 "os_version": "01020300",
1067 'friendly_name': "WPS AP - <>&'\" - TEST",
1068 "config_methods": "label push_button",
1069 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1070 logger.info("WPS configuration step")
1071 new_passphrase = "1234567890"
1072 dev[0].dump_monitor()
1073 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1074 dev[0].wps_reg(apdev[0]['bssid'], ap_pin, ssid, "WPA2PSK", "CCMP",
1075 new_passphrase)
1076 status = dev[0].get_status()
1077 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1078 raise Exception("Not fully connected")
1079 if status['ssid'] != ssid:
1080 raise Exception("Unexpected SSID")
1081 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
1082 raise Exception("Unexpected encryption configuration")
1083 if status['key_mgmt'] != 'WPA2-PSK':
1084 raise Exception("Unexpected key_mgmt")
1085
1086 logger.info("Start ER")
1087 dev[0].request("WPS_ER_START ifname=lo")
1088 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1089 if ev is None:
1090 raise Exception("AP discovery timed out")
1091 if ap_uuid not in ev:
1092 raise Exception("Expected AP UUID not found")
1093 if "|WPS AP - &lt;&gt;&amp;&apos;&quot; - TEST|Company|" not in ev:
1094 raise Exception("Expected friendly name not found")
1095
1096 logger.info("Learn AP configuration through UPnP")
1097 dev[0].dump_monitor()
1098 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1099 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1100 if ev is None:
1101 raise Exception("AP learn timed out")
1102 if ap_uuid not in ev:
1103 raise Exception("Expected AP UUID not in settings")
1104 if "ssid=" + ssid not in ev:
1105 raise Exception("Expected SSID not in settings")
1106 if "key=" + new_passphrase not in ev:
1107 raise Exception("Expected passphrase not in settings")
1108 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1109 if ev is None:
1110 raise Exception("WPS-FAIL after AP learn timed out")
1111 time.sleep(0.1)
1112
1113 logger.info("Add Enrollee using ER")
1114 pin = dev[1].wps_read_pin()
1115 dev[0].dump_monitor()
1116 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1117 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1118 dev[1].dump_monitor()
1119 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1120 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
1121 if ev is None:
1122 raise Exception("Enrollee did not report success")
1123 dev[1].wait_connected(timeout=15)
1124 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1125 if ev is None:
1126 raise Exception("WPS ER did not report success")
1127 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1128
1129 logger.info("Add a specific Enrollee using ER")
1130 pin = dev[2].wps_read_pin()
1131 addr2 = dev[2].p2p_interface_addr()
1132 dev[0].dump_monitor()
1133 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1134 dev[2].dump_monitor()
1135 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1136 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1137 if ev is None:
1138 raise Exception("Enrollee not seen")
1139 if addr2 not in ev:
1140 raise Exception("Unexpected Enrollee MAC address")
1141 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
1142 dev[2].wait_connected(timeout=30)
1143 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1144 if ev is None:
1145 raise Exception("WPS ER did not report success")
1146
1147 logger.info("Verify registrar selection behavior")
1148 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1149 dev[1].request("DISCONNECT")
1150 dev[1].wait_disconnected(timeout=10)
1151 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1152 dev[1].scan(freq="2412")
1153 bss = dev[1].get_bss(apdev[0]['bssid'])
1154 if "[WPS-AUTH]" not in bss['flags']:
1155 # It is possible for scan to miss an update especially when running
1156 # tests under load with multiple VMs, so allow another attempt.
1157 dev[1].scan(freq="2412")
1158 bss = dev[1].get_bss(apdev[0]['bssid'])
1159 if "[WPS-AUTH]" not in bss['flags']:
1160 raise Exception("WPS-AUTH flag missing")
1161
1162 logger.info("Stop ER")
1163 dev[0].dump_monitor()
1164 dev[0].request("WPS_ER_STOP")
1165 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
1166 if ev is None:
1167 raise Exception("WPS ER unsubscription timed out")
1168 # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
1169 # a bit before verifying that the scan results have changed.
1170 time.sleep(0.2)
1171
1172 for i in range(0, 10):
1173 dev[1].request("BSS_FLUSH 0")
1174 dev[1].scan(freq="2412", only_new=True)
1175 bss = dev[1].get_bss(apdev[0]['bssid'])
1176 if bss and 'flags' in bss and "[WPS-AUTH]" not in bss['flags']:
1177 break
1178 logger.debug("WPS-AUTH flag was still in place - wait a bit longer")
1179 time.sleep(0.1)
1180 if "[WPS-AUTH]" in bss['flags']:
1181 raise Exception("WPS-AUTH flag not removed")
1182
1183 def test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1184 """WPS ER adding a new enrollee identified by UUID"""
1185 try:
1186 _test_ap_wps_er_add_enrollee_uuid(dev, apdev)
1187 finally:
1188 dev[0].request("WPS_ER_STOP")
1189
1190 def _test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1191 ssid = "wps-er-add-enrollee"
1192 ap_pin = "12345670"
1193 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1194 hostapd.add_ap(apdev[0],
1195 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1196 "wpa_passphrase": "12345678", "wpa": "2",
1197 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1198 "device_name": "Wireless AP", "manufacturer": "Company",
1199 "model_name": "WAP", "model_number": "123",
1200 "serial_number": "12345", "device_type": "6-0050F204-1",
1201 "os_version": "01020300",
1202 "config_methods": "label push_button",
1203 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1204 logger.info("WPS configuration step")
1205 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1206 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1207
1208 logger.info("Start ER")
1209 dev[0].request("WPS_ER_START ifname=lo")
1210 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1211 if ev is None:
1212 raise Exception("AP discovery timed out")
1213 if ap_uuid not in ev:
1214 raise Exception("Expected AP UUID not found")
1215
1216 logger.info("Learn AP configuration through UPnP")
1217 dev[0].dump_monitor()
1218 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1219 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1220 if ev is None:
1221 raise Exception("AP learn timed out")
1222 if ap_uuid not in ev:
1223 raise Exception("Expected AP UUID not in settings")
1224 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1225 if ev is None:
1226 raise Exception("WPS-FAIL after AP learn timed out")
1227 time.sleep(0.1)
1228
1229 logger.info("Add a specific Enrollee using ER (PBC/UUID)")
1230 addr1 = dev[1].p2p_interface_addr()
1231 dev[0].dump_monitor()
1232 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1233 dev[1].dump_monitor()
1234 dev[1].request("WPS_PBC %s" % apdev[0]['bssid'])
1235 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1236 if ev is None:
1237 raise Exception("Enrollee not seen")
1238 if addr1 not in ev:
1239 raise Exception("Unexpected Enrollee MAC address")
1240 uuid = ev.split(' ')[1]
1241 dev[0].request("WPS_ER_PBC " + uuid)
1242 dev[1].wait_connected(timeout=30)
1243 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1244 if ev is None:
1245 raise Exception("WPS ER did not report success")
1246
1247 logger.info("Add a specific Enrollee using ER (PIN/UUID)")
1248 pin = dev[2].wps_read_pin()
1249 addr2 = dev[2].p2p_interface_addr()
1250 dev[0].dump_monitor()
1251 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1252 dev[2].dump_monitor()
1253 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1254 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1255 if ev is None:
1256 raise Exception("Enrollee not seen")
1257 if addr2 not in ev:
1258 raise Exception("Unexpected Enrollee MAC address")
1259 uuid = ev.split(' ')[1]
1260 dev[0].request("WPS_ER_PIN " + uuid + " " + pin)
1261 dev[2].wait_connected(timeout=30)
1262 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1263 if ev is None:
1264 raise Exception("WPS ER did not report success")
1265
1266 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-REMOVE"], timeout=15)
1267 if ev is None:
1268 raise Exception("No Enrollee STA entry timeout seen")
1269
1270 logger.info("Stop ER")
1271 dev[0].dump_monitor()
1272 dev[0].request("WPS_ER_STOP")
1273
1274 def test_ap_wps_er_multi_add_enrollee(dev, apdev):
1275 """Multiple WPS ERs adding a new enrollee using PIN"""
1276 try:
1277 _test_ap_wps_er_multi_add_enrollee(dev, apdev)
1278 finally:
1279 for i in range(2):
1280 dev[i].request("WPS_ER_STOP")
1281
1282 def _test_ap_wps_er_multi_add_enrollee(dev, apdev):
1283 ssid = "wps-er-add-enrollee"
1284 ap_pin = "12345670"
1285 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1286 hostapd.add_ap(apdev[0],
1287 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1288 "wpa_passphrase": "12345678", "wpa": "2",
1289 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1290 "device_name": "Wireless AP", "manufacturer": "Company",
1291 "model_name": "WAP", "model_number": "123",
1292 "serial_number": "12345", "device_type": "6-0050F204-1",
1293 "os_version": "01020300",
1294 'friendly_name': "WPS AP",
1295 "config_methods": "label push_button",
1296 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1297
1298 for i in range(2):
1299 dev[i].scan_for_bss(apdev[0]['bssid'], freq=2412)
1300 dev[i].wps_reg(apdev[0]['bssid'], ap_pin)
1301 for i in range(2):
1302 dev[i].request("WPS_ER_START ifname=lo")
1303 for i in range(2):
1304 ev = dev[i].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1305 if ev is None:
1306 raise Exception("AP discovery timed out")
1307 dev[i].dump_monitor()
1308 for i in range(2):
1309 dev[i].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1310 for i in range(2):
1311 ev = dev[i].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1312 if ev is None:
1313 raise Exception("AP learn timed out")
1314 ev = dev[i].wait_event(["WPS-FAIL"], timeout=15)
1315 if ev is None:
1316 raise Exception("WPS-FAIL after AP learn timed out")
1317
1318 time.sleep(0.1)
1319
1320 pin = dev[2].wps_read_pin()
1321 addr = dev[2].own_addr()
1322 dev[0].dump_monitor()
1323 dev[0].request("WPS_ER_PIN any " + pin + " " + addr)
1324 dev[1].dump_monitor()
1325 dev[1].request("WPS_ER_PIN any " + pin + " " + addr)
1326
1327 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1328 dev[2].dump_monitor()
1329 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1330 ev = dev[2].wait_event(["WPS-SUCCESS"], timeout=30)
1331 if ev is None:
1332 raise Exception("Enrollee did not report success")
1333 dev[2].wait_connected(timeout=15)
1334
1335 def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1336 """WPS ER connected to AP and adding a new enrollee using PBC"""
1337 try:
1338 _test_ap_wps_er_add_enrollee_pbc(dev, apdev)
1339 finally:
1340 dev[0].request("WPS_ER_STOP")
1341
1342 def _test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1343 ssid = "wps-er-add-enrollee-pbc"
1344 ap_pin = "12345670"
1345 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1346 hostapd.add_ap(apdev[0],
1347 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1348 "wpa_passphrase": "12345678", "wpa": "2",
1349 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1350 "device_name": "Wireless AP", "manufacturer": "Company",
1351 "model_name": "WAP", "model_number": "123",
1352 "serial_number": "12345", "device_type": "6-0050F204-1",
1353 "os_version": "01020300",
1354 "config_methods": "label push_button",
1355 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1356 logger.info("Learn AP configuration")
1357 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1358 dev[0].dump_monitor()
1359 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1360 status = dev[0].get_status()
1361 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1362 raise Exception("Not fully connected")
1363
1364 logger.info("Start ER")
1365 dev[0].request("WPS_ER_START ifname=lo")
1366 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1367 if ev is None:
1368 raise Exception("AP discovery timed out")
1369 if ap_uuid not in ev:
1370 raise Exception("Expected AP UUID not found")
1371
1372 enrollee = dev[1].p2p_interface_addr()
1373
1374 if "FAIL-UNKNOWN-UUID" not in dev[0].request("WPS_ER_PBC " + enrollee):
1375 raise Exception("Unknown UUID not reported")
1376
1377 logger.info("Add Enrollee using ER and PBC")
1378 dev[0].dump_monitor()
1379 dev[1].dump_monitor()
1380 dev[1].request("WPS_PBC")
1381
1382 for i in range(0, 2):
1383 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1384 if ev is None:
1385 raise Exception("Enrollee discovery timed out")
1386 if enrollee in ev:
1387 break
1388 if i == 1:
1389 raise Exception("Expected Enrollee not found")
1390 if "FAIL-NO-AP-SETTINGS" not in dev[0].request("WPS_ER_PBC " + enrollee):
1391 raise Exception("Unknown UUID not reported")
1392 logger.info("Use learned network configuration on ER")
1393 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1394 if "OK" not in dev[0].request("WPS_ER_PBC " + enrollee):
1395 raise Exception("WPS_ER_PBC failed")
1396
1397 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
1398 if ev is None:
1399 raise Exception("Enrollee did not report success")
1400 dev[1].wait_connected(timeout=15)
1401 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1402 if ev is None:
1403 raise Exception("WPS ER did not report success")
1404 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1405
1406 def test_ap_wps_er_pbc_overlap(dev, apdev):
1407 """WPS ER connected to AP and PBC session overlap"""
1408 try:
1409 _test_ap_wps_er_pbc_overlap(dev, apdev)
1410 finally:
1411 dev[0].request("WPS_ER_STOP")
1412
1413 def _test_ap_wps_er_pbc_overlap(dev, apdev):
1414 ssid = "wps-er-add-enrollee-pbc"
1415 ap_pin = "12345670"
1416 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1417 hostapd.add_ap(apdev[0],
1418 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1419 "wpa_passphrase": "12345678", "wpa": "2",
1420 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1421 "device_name": "Wireless AP", "manufacturer": "Company",
1422 "model_name": "WAP", "model_number": "123",
1423 "serial_number": "12345", "device_type": "6-0050F204-1",
1424 "os_version": "01020300",
1425 "config_methods": "label push_button",
1426 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1427 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1428 dev[0].dump_monitor()
1429 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1430
1431 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1432 dev[2].scan_for_bss(apdev[0]['bssid'], freq="2412")
1433 # avoid leaving dev 1 or 2 as the last Probe Request to the AP
1434 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True)
1435
1436 dev[0].dump_monitor()
1437 dev[0].request("WPS_ER_START ifname=lo")
1438
1439 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1440 if ev is None:
1441 raise Exception("AP discovery timed out")
1442 if ap_uuid not in ev:
1443 raise Exception("Expected AP UUID not found")
1444
1445 # verify BSSID selection of the AP instead of UUID
1446 if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
1447 raise Exception("Could not select AP based on BSSID")
1448
1449 dev[0].dump_monitor()
1450 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1451 dev[2].request("WPS_PBC " + apdev[0]['bssid'])
1452 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1453 if ev is None:
1454 raise Exception("PBC scan failed")
1455 ev = dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1456 if ev is None:
1457 raise Exception("PBC scan failed")
1458 found1 = False
1459 found2 = False
1460 addr1 = dev[1].own_addr()
1461 addr2 = dev[2].own_addr()
1462 for i in range(3):
1463 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1464 if ev is None:
1465 raise Exception("Enrollee discovery timed out")
1466 if addr1 in ev:
1467 found1 = True
1468 if found2:
1469 break
1470 if addr2 in ev:
1471 found2 = True
1472 if found1:
1473 break
1474 if dev[0].request("WPS_ER_PBC " + ap_uuid) != "FAIL-PBC-OVERLAP\n":
1475 raise Exception("PBC overlap not reported")
1476 dev[1].request("WPS_CANCEL")
1477 dev[2].request("WPS_CANCEL")
1478 if dev[0].request("WPS_ER_PBC foo") != "FAIL\n":
1479 raise Exception("Invalid WPS_ER_PBC accepted")
1480
1481 def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1482 """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
1483 try:
1484 _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev)
1485 finally:
1486 dev[0].request("WPS_ER_STOP")
1487
1488 def _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1489 ssid = "wps-er-add-enrollee-pbc"
1490 ap_pin = "12345670"
1491 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1492 hostapd.add_ap(apdev[0],
1493 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1494 "wpa_passphrase": "12345678", "wpa": "2",
1495 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1496 "device_name": "Wireless AP", "manufacturer": "Company",
1497 "model_name": "WAP", "model_number": "123",
1498 "serial_number": "12345", "device_type": "6-0050F204-1",
1499 "os_version": "01020300",
1500 "config_methods": "label push_button",
1501 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1502 logger.info("Learn AP configuration")
1503 dev[0].request("SET wps_version_number 0x10")
1504 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1505 dev[0].dump_monitor()
1506 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1507 status = dev[0].get_status()
1508 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1509 raise Exception("Not fully connected")
1510
1511 logger.info("Start ER")
1512 dev[0].request("WPS_ER_START ifname=lo")
1513 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1514 if ev is None:
1515 raise Exception("AP discovery timed out")
1516 if ap_uuid not in ev:
1517 raise Exception("Expected AP UUID not found")
1518
1519 logger.info("Use learned network configuration on ER")
1520 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1521
1522 logger.info("Add Enrollee using ER and PIN")
1523 enrollee = dev[1].p2p_interface_addr()
1524 pin = dev[1].wps_read_pin()
1525 dev[0].dump_monitor()
1526 dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
1527 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1528 dev[1].dump_monitor()
1529 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1530 dev[1].wait_connected(timeout=30)
1531 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1532 if ev is None:
1533 raise Exception("WPS ER did not report success")
1534
1535 @remote_compatible
1536 def test_ap_wps_er_config_ap(dev, apdev):
1537 """WPS ER configuring AP over UPnP"""
1538 try:
1539 _test_ap_wps_er_config_ap(dev, apdev)
1540 finally:
1541 dev[0].request("WPS_ER_STOP")
1542
1543 def _test_ap_wps_er_config_ap(dev, apdev):
1544 ssid = "wps-er-ap-config"
1545 ap_pin = "12345670"
1546 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1547 hostapd.add_ap(apdev[0],
1548 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1549 "wpa_passphrase": "12345678", "wpa": "2",
1550 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1551 "device_name": "Wireless AP", "manufacturer": "Company",
1552 "model_name": "WAP", "model_number": "123",
1553 "serial_number": "12345", "device_type": "6-0050F204-1",
1554 "os_version": "01020300",
1555 "config_methods": "label push_button",
1556 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1557
1558 logger.info("Connect ER to the AP")
1559 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
1560
1561 logger.info("WPS configuration step")
1562 dev[0].request("WPS_ER_START ifname=lo")
1563 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1564 if ev is None:
1565 raise Exception("AP discovery timed out")
1566 if ap_uuid not in ev:
1567 raise Exception("Expected AP UUID not found")
1568 new_passphrase = "1234567890"
1569 dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
1570 binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " +
1571 binascii.hexlify(new_passphrase.encode()).decode())
1572 ev = dev[0].wait_event(["WPS-SUCCESS"])
1573 if ev is None:
1574 raise Exception("WPS ER configuration operation timed out")
1575 dev[0].wait_disconnected(timeout=10)
1576 dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
1577
1578 logger.info("WPS ER restart")
1579 dev[0].request("WPS_ER_START")
1580 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1581 if ev is None:
1582 raise Exception("AP discovery timed out on ER restart")
1583 if ap_uuid not in ev:
1584 raise Exception("Expected AP UUID not found on ER restart")
1585 if "OK" not in dev[0].request("WPS_ER_STOP"):
1586 raise Exception("WPS_ER_STOP failed")
1587 if "OK" not in dev[0].request("WPS_ER_STOP"):
1588 raise Exception("WPS_ER_STOP failed")
1589
1590 @remote_compatible
1591 def test_ap_wps_er_cache_ap_settings(dev, apdev):
1592 """WPS ER caching AP settings"""
1593 try:
1594 _test_ap_wps_er_cache_ap_settings(dev, apdev)
1595 finally:
1596 dev[0].request("WPS_ER_STOP")
1597
1598 def _test_ap_wps_er_cache_ap_settings(dev, apdev):
1599 ssid = "wps-er-add-enrollee"
1600 ap_pin = "12345670"
1601 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1602 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1603 "wpa_passphrase": "12345678", "wpa": "2",
1604 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1605 "device_name": "Wireless AP", "manufacturer": "Company",
1606 "model_name": "WAP", "model_number": "123",
1607 "serial_number": "12345", "device_type": "6-0050F204-1",
1608 "os_version": "01020300",
1609 "config_methods": "label push_button",
1610 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
1611 hapd = hostapd.add_ap(apdev[0], params)
1612 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1613 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1614 id = int(dev[0].list_networks()[0]['id'])
1615 dev[0].set_network(id, "scan_freq", "2412")
1616
1617 dev[0].request("WPS_ER_START ifname=lo")
1618 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1619 if ev is None:
1620 raise Exception("AP discovery timed out")
1621 if ap_uuid not in ev:
1622 raise Exception("Expected AP UUID not found")
1623
1624 dev[0].dump_monitor()
1625 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1626 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1627 if ev is None:
1628 raise Exception("AP learn timed out")
1629 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1630 if ev is None:
1631 raise Exception("WPS-FAIL after AP learn timed out")
1632 time.sleep(0.1)
1633
1634 hapd.disable()
1635
1636 for i in range(2):
1637 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE", "CTRL-EVENT-DISCONNECTED"],
1638 timeout=15)
1639 if ev is None:
1640 raise Exception("AP removal or disconnection timed out")
1641
1642 hapd = hostapd.add_ap(apdev[0], params)
1643 for i in range(2):
1644 ev = dev[0].wait_event(["WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED"],
1645 timeout=15)
1646 if ev is None:
1647 raise Exception("AP discovery or connection timed out")
1648
1649 pin = dev[1].wps_read_pin()
1650 dev[0].dump_monitor()
1651 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1652
1653 time.sleep(0.2)
1654
1655 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1656 dev[1].dump_monitor()
1657 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1658 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
1659 if ev is None:
1660 raise Exception("Enrollee did not report success")
1661 dev[1].wait_connected(timeout=15)
1662 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1663 if ev is None:
1664 raise Exception("WPS ER did not report success")
1665
1666 dev[0].dump_monitor()
1667 dev[0].request("WPS_ER_STOP")
1668
1669 def test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1670 """WPS ER caching AP settings (OOM)"""
1671 try:
1672 _test_ap_wps_er_cache_ap_settings_oom(dev, apdev)
1673 finally:
1674 dev[0].request("WPS_ER_STOP")
1675
1676 def _test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1677 ssid = "wps-er-add-enrollee"
1678 ap_pin = "12345670"
1679 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1680 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1681 "wpa_passphrase": "12345678", "wpa": "2",
1682 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1683 "device_name": "Wireless AP", "manufacturer": "Company",
1684 "model_name": "WAP", "model_number": "123",
1685 "serial_number": "12345", "device_type": "6-0050F204-1",
1686 "os_version": "01020300",
1687 "config_methods": "label push_button",
1688 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
1689 hapd = hostapd.add_ap(apdev[0], params)
1690 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1691 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1692 id = int(dev[0].list_networks()[0]['id'])
1693 dev[0].set_network(id, "scan_freq", "2412")
1694
1695 dev[0].request("WPS_ER_START ifname=lo")
1696 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1697 if ev is None:
1698 raise Exception("AP discovery timed out")
1699 if ap_uuid not in ev:
1700 raise Exception("Expected AP UUID not found")
1701
1702 dev[0].dump_monitor()
1703 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1704 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1705 if ev is None:
1706 raise Exception("AP learn timed out")
1707 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1708 if ev is None:
1709 raise Exception("WPS-FAIL after AP learn timed out")
1710 time.sleep(0.1)
1711
1712 with alloc_fail(dev[0], 1, "=wps_er_ap_use_cached_settings"):
1713 hapd.disable()
1714
1715 for i in range(2):
1716 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE",
1717 "CTRL-EVENT-DISCONNECTED"],
1718 timeout=15)
1719 if ev is None:
1720 raise Exception("AP removal or disconnection timed out")
1721
1722 hapd = hostapd.add_ap(apdev[0], params)
1723 for i in range(2):
1724 ev = dev[0].wait_event(["WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED"],
1725 timeout=15)
1726 if ev is None:
1727 raise Exception("AP discovery or connection timed out")
1728
1729 dev[0].request("WPS_ER_STOP")
1730
1731 def test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1732 """WPS ER caching AP settings (OOM 2)"""
1733 try:
1734 _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev)
1735 finally:
1736 dev[0].request("WPS_ER_STOP")
1737
1738 def _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1739 ssid = "wps-er-add-enrollee"
1740 ap_pin = "12345670"
1741 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1742 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1743 "wpa_passphrase": "12345678", "wpa": "2",
1744 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1745 "device_name": "Wireless AP", "manufacturer": "Company",
1746 "model_name": "WAP", "model_number": "123",
1747 "serial_number": "12345", "device_type": "6-0050F204-1",
1748 "os_version": "01020300",
1749 "config_methods": "label push_button",
1750 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
1751 hapd = hostapd.add_ap(apdev[0], params)
1752 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1753 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1754 id = int(dev[0].list_networks()[0]['id'])
1755 dev[0].set_network(id, "scan_freq", "2412")
1756
1757 dev[0].request("WPS_ER_START ifname=lo")
1758 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1759 if ev is None:
1760 raise Exception("AP discovery timed out")
1761 if ap_uuid not in ev:
1762 raise Exception("Expected AP UUID not found")
1763
1764 dev[0].dump_monitor()
1765 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1766 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1767 if ev is None:
1768 raise Exception("AP learn timed out")
1769 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1770 if ev is None:
1771 raise Exception("WPS-FAIL after AP learn timed out")
1772 time.sleep(0.1)
1773
1774 with alloc_fail(dev[0], 1, "=wps_er_ap_cache_settings"):
1775 hapd.disable()
1776
1777 for i in range(2):
1778 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE",
1779 "CTRL-EVENT-DISCONNECTED"],
1780 timeout=15)
1781 if ev is None:
1782 raise Exception("AP removal or disconnection timed out")
1783
1784 hapd = hostapd.add_ap(apdev[0], params)
1785 for i in range(2):
1786 ev = dev[0].wait_event(["WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED"],
1787 timeout=15)
1788 if ev is None:
1789 raise Exception("AP discovery or connection timed out")
1790
1791 dev[0].request("WPS_ER_STOP")
1792
1793 def test_ap_wps_er_subscribe_oom(dev, apdev):
1794 """WPS ER subscribe OOM"""
1795 try:
1796 _test_ap_wps_er_subscribe_oom(dev, apdev)
1797 finally:
1798 dev[0].request("WPS_ER_STOP")
1799
1800 def _test_ap_wps_er_subscribe_oom(dev, apdev):
1801 ssid = "wps-er-add-enrollee"
1802 ap_pin = "12345670"
1803 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1804 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1805 "wpa_passphrase": "12345678", "wpa": "2",
1806 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1807 "device_name": "Wireless AP", "manufacturer": "Company",
1808 "model_name": "WAP", "model_number": "123",
1809 "serial_number": "12345", "device_type": "6-0050F204-1",
1810 "os_version": "01020300",
1811 "config_methods": "label push_button",
1812 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
1813 hapd = hostapd.add_ap(apdev[0], params)
1814 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1815 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1816 id = int(dev[0].list_networks()[0]['id'])
1817 dev[0].set_network(id, "scan_freq", "2412")
1818
1819 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_subscribe"):
1820 dev[0].request("WPS_ER_START ifname=lo")
1821 for i in range(50):
1822 res = dev[0].request("GET_ALLOC_FAIL")
1823 if res.startswith("0:"):
1824 break
1825 time.sleep(0.1)
1826 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=0)
1827 if ev:
1828 raise Exception("Unexpected AP discovery during OOM")
1829
1830 dev[0].request("WPS_ER_STOP")
1831
1832 def test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1833 """WPS ER SetSelectedRegistrar OOM"""
1834 try:
1835 _test_ap_wps_er_set_sel_reg_oom(dev, apdev)
1836 finally:
1837 dev[0].request("WPS_ER_STOP")
1838
1839 def _test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1840 ssid = "wps-er-add-enrollee"
1841 ap_pin = "12345670"
1842 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1843 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1844 "wpa_passphrase": "12345678", "wpa": "2",
1845 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1846 "device_name": "Wireless AP", "manufacturer": "Company",
1847 "model_name": "WAP", "model_number": "123",
1848 "serial_number": "12345", "device_type": "6-0050F204-1",
1849 "os_version": "01020300",
1850 "config_methods": "label push_button",
1851 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
1852 hapd = hostapd.add_ap(apdev[0], params)
1853 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1854 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1855
1856 dev[0].request("WPS_ER_START ifname=lo")
1857 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1858 if ev is None:
1859 raise Exception("AP not discovered")
1860
1861 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1862 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1863 if ev is None:
1864 raise Exception("AP learn timed out")
1865 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1866 if ev is None:
1867 raise Exception("WPS-FAIL timed out")
1868 time.sleep(0.1)
1869
1870 for func in ["http_client_url_parse;wps_er_send_set_sel_reg",
1871 "wps_er_soap_hdr;wps_er_send_set_sel_reg",
1872 "http_client_addr;wps_er_send_set_sel_reg",
1873 "wpabuf_alloc;wps_er_set_sel_reg"]:
1874 with alloc_fail(dev[0], 1, func):
1875 if "OK" not in dev[0].request("WPS_ER_PBC " + ap_uuid):
1876 raise Exception("WPS_ER_PBC failed")
1877 ev = dev[0].wait_event(["WPS-PBC-ACTIVE"], timeout=3)
1878 if ev is None:
1879 raise Exception("WPS-PBC-ACTIVE not seen")
1880
1881 dev[0].request("WPS_ER_STOP")
1882
1883 @remote_compatible
1884 def test_ap_wps_er_learn_oom(dev, apdev):
1885 """WPS ER learn OOM"""
1886 try:
1887 _test_ap_wps_er_learn_oom(dev, apdev)
1888 finally:
1889 dev[0].request("WPS_ER_STOP")
1890
1891 def _test_ap_wps_er_learn_oom(dev, apdev):
1892 ssid = "wps-er-add-enrollee"
1893 ap_pin = "12345670"
1894 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1895 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1896 "wpa_passphrase": "12345678", "wpa": "2",
1897 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1898 "device_name": "Wireless AP", "manufacturer": "Company",
1899 "model_name": "WAP", "model_number": "123",
1900 "serial_number": "12345", "device_type": "6-0050F204-1",
1901 "os_version": "01020300",
1902 "config_methods": "label push_button",
1903 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
1904 hapd = hostapd.add_ap(apdev[0], params)
1905 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1906 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1907
1908 dev[0].request("WPS_ER_START ifname=lo")
1909 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1910 if ev is None:
1911 raise Exception("AP not discovered")
1912
1913 for func in ["wps_er_http_put_message_cb",
1914 "xml_get_base64_item;wps_er_http_put_message_cb",
1915 "http_client_url_parse;wps_er_ap_put_message",
1916 "wps_er_soap_hdr;wps_er_ap_put_message",
1917 "http_client_addr;wps_er_ap_put_message"]:
1918 with alloc_fail(dev[0], 1, func):
1919 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1920 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=1)
1921 if ev is not None:
1922 raise Exception("AP learn succeeded during OOM")
1923
1924 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1925 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=10)
1926 if ev is None:
1927 raise Exception("AP learn did not succeed")
1928
1929 if "FAIL" not in dev[0].request("WPS_ER_LEARN 00000000-9e5c-4e73-bd82-f89cbcd10d7e " + ap_pin):
1930 raise Exception("WPS_ER_LEARN for unknown AP accepted")
1931
1932 dev[0].request("WPS_ER_STOP")
1933
1934 def test_ap_wps_fragmentation(dev, apdev):
1935 """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
1936 ssid = "test-wps-fragmentation"
1937 appin = "12345670"
1938 hapd = hostapd.add_ap(apdev[0],
1939 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1940 "wpa_passphrase": "12345678", "wpa": "3",
1941 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1942 "wpa_pairwise": "TKIP", "ap_pin": appin,
1943 "fragment_size": "50"})
1944 logger.info("WPS provisioning step (PBC)")
1945 hapd.request("WPS_PBC")
1946 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1947 dev[0].dump_monitor()
1948 dev[0].request("SET wps_fragment_size 50")
1949 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1950 dev[0].wait_connected(timeout=30)
1951 status = dev[0].get_status()
1952 if status['wpa_state'] != 'COMPLETED':
1953 raise Exception("Not fully connected")
1954 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1955 raise Exception("Unexpected encryption configuration")
1956 if status['key_mgmt'] != 'WPA2-PSK':
1957 raise Exception("Unexpected key_mgmt")
1958
1959 logger.info("WPS provisioning step (PIN)")
1960 pin = dev[1].wps_read_pin()
1961 hapd.request("WPS_PIN any " + pin)
1962 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1963 dev[1].request("SET wps_fragment_size 50")
1964 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1965 dev[1].wait_connected(timeout=30)
1966 status = dev[1].get_status()
1967 if status['wpa_state'] != 'COMPLETED':
1968 raise Exception("Not fully connected")
1969 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1970 raise Exception("Unexpected encryption configuration")
1971 if status['key_mgmt'] != 'WPA2-PSK':
1972 raise Exception("Unexpected key_mgmt")
1973
1974 logger.info("WPS connection as registrar")
1975 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1976 dev[2].request("SET wps_fragment_size 50")
1977 dev[2].wps_reg(apdev[0]['bssid'], appin)
1978 status = dev[2].get_status()
1979 if status['wpa_state'] != 'COMPLETED':
1980 raise Exception("Not fully connected")
1981 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1982 raise Exception("Unexpected encryption configuration")
1983 if status['key_mgmt'] != 'WPA2-PSK':
1984 raise Exception("Unexpected key_mgmt")
1985
1986 @remote_compatible
1987 def test_ap_wps_new_version_sta(dev, apdev):
1988 """WPS compatibility with new version number on the station"""
1989 ssid = "test-wps-ver"
1990 hapd = hostapd.add_ap(apdev[0],
1991 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1992 "wpa_passphrase": "12345678", "wpa": "2",
1993 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
1994 logger.info("WPS provisioning step")
1995 hapd.request("WPS_PBC")
1996 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1997 dev[0].dump_monitor()
1998 dev[0].request("SET wps_version_number 0x43")
1999 dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
2000 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2001 dev[0].wait_connected(timeout=30)
2002
2003 @remote_compatible
2004 def test_ap_wps_new_version_ap(dev, apdev):
2005 """WPS compatibility with new version number on the AP"""
2006 ssid = "test-wps-ver"
2007 hapd = hostapd.add_ap(apdev[0],
2008 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2009 "wpa_passphrase": "12345678", "wpa": "2",
2010 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2011 logger.info("WPS provisioning step")
2012 if "FAIL" in hapd.request("SET wps_version_number 0x43"):
2013 raise Exception("Failed to enable test functionality")
2014 hapd.request("WPS_PBC")
2015 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2016 dev[0].dump_monitor()
2017 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2018 dev[0].wait_connected(timeout=30)
2019 hapd.request("SET wps_version_number 0x20")
2020
2021 @remote_compatible
2022 def test_ap_wps_check_pin(dev, apdev):
2023 """Verify PIN checking through control interface"""
2024 hapd = hostapd.add_ap(apdev[0],
2025 {"ssid": "wps", "eap_server": "1", "wps_state": "2",
2026 "wpa_passphrase": "12345678", "wpa": "2",
2027 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2028 for t in [("12345670", "12345670"),
2029 ("12345678", "FAIL-CHECKSUM"),
2030 ("12345", "FAIL"),
2031 ("123456789", "FAIL"),
2032 ("1234-5670", "12345670"),
2033 ("1234 5670", "12345670"),
2034 ("1-2.3:4 5670", "12345670")]:
2035 res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
2036 res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
2037 if res != res2:
2038 raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
2039 if res != t[1]:
2040 raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
2041
2042 if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
2043 raise Exception("Unexpected WPS_CHECK_PIN success")
2044 if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
2045 raise Exception("Unexpected WPS_CHECK_PIN success")
2046
2047 for i in range(0, 10):
2048 pin = dev[0].request("WPS_PIN get")
2049 rpin = dev[0].request("WPS_CHECK_PIN " + pin).rstrip('\n')
2050 if pin != rpin:
2051 raise Exception("Random PIN validation failed for " + pin)
2052
2053 def test_ap_wps_pin_get_failure(dev, apdev):
2054 """PIN generation failure"""
2055 with fail_test(dev[0], 1,
2056 "os_get_random;wpa_supplicant_ctrl_iface_wps_pin"):
2057 if "FAIL" not in dev[0].request("WPS_PIN get"):
2058 raise Exception("WPS_PIN did not report failure")
2059
2060 def test_ap_wps_wep_config(dev, apdev):
2061 """WPS 2.0 AP rejecting WEP configuration"""
2062 ssid = "test-wps-config"
2063 appin = "12345670"
2064 hapd = hostapd.add_ap(apdev[0],
2065 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2066 "ap_pin": appin})
2067 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2068 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
2069 "hello", no_wait=True)
2070 ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
2071 if ev is None:
2072 raise Exception("WPS-FAIL timed out")
2073 if "reason=2" not in ev:
2074 raise Exception("Unexpected reason code in WPS-FAIL")
2075 status = hapd.request("WPS_GET_STATUS")
2076 if "Last WPS result: Failed" not in status:
2077 raise Exception("WPS failure result not shown correctly")
2078 if "Failure Reason: WEP Prohibited" not in status:
2079 raise Exception("Failure reason not reported correctly")
2080 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
2081 raise Exception("Peer address not shown correctly")
2082
2083 def test_ap_wps_wep_enroll(dev, apdev):
2084 """WPS 2.0 STA rejecting WEP configuration"""
2085 ssid = "test-wps-wep"
2086 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2087 "skip_cred_build": "1", "extra_cred": "wps-wep-cred"}
2088 hapd = hostapd.add_ap(apdev[0], params)
2089 hapd.request("WPS_PBC")
2090 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2091 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2092 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
2093 if ev is None:
2094 raise Exception("WPS-FAIL event timed out")
2095 if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
2096 raise Exception("Unexpected WPS-FAIL event: " + ev)
2097
2098 @remote_compatible
2099 def test_ap_wps_ie_fragmentation(dev, apdev):
2100 """WPS AP using fragmented WPS IE"""
2101 ssid = "test-wps-ie-fragmentation"
2102 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2103 "wpa_passphrase": "12345678", "wpa": "2",
2104 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2105 "device_name": "1234567890abcdef1234567890abcdef",
2106 "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
2107 "model_name": "1234567890abcdef1234567890abcdef",
2108 "model_number": "1234567890abcdef1234567890abcdef",
2109 "serial_number": "1234567890abcdef1234567890abcdef"}
2110 hapd = hostapd.add_ap(apdev[0], params)
2111 hapd.request("WPS_PBC")
2112 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2113 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2114 dev[0].wait_connected(timeout=30)
2115 bss = dev[0].get_bss(apdev[0]['bssid'])
2116 if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
2117 logger.info("Device Name not received correctly")
2118 logger.info(bss)
2119 # This can fail if Probe Response frame is missed and Beacon frame was
2120 # used to fill in the BSS entry. This can happen, e.g., during heavy
2121 # load every now and then and is not really an error, so try to
2122 # workaround by runnign another scan.
2123 dev[0].scan(freq="2412", only_new=True)
2124 bss = dev[0].get_bss(apdev[0]['bssid'])
2125 if not bss or "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
2126 logger.info(bss)
2127 raise Exception("Device Name not received correctly")
2128 if len(re.findall("dd..0050f204", bss['ie'])) != 2:
2129 raise Exception("Unexpected number of WPS IEs")
2130
2131 def get_psk(pskfile):
2132 psks = {}
2133 with open(pskfile, "r") as f:
2134 lines = f.read().splitlines()
2135 for l in lines:
2136 if l == "# WPA PSKs":
2137 continue
2138 (addr, psk) = l.split(' ')
2139 psks[addr] = psk
2140 return psks
2141
2142 def test_ap_wps_per_station_psk(dev, apdev):
2143 """WPS PBC provisioning with per-station PSK"""
2144 addr0 = dev[0].own_addr()
2145 addr1 = dev[1].own_addr()
2146 addr2 = dev[2].own_addr()
2147 ssid = "wps"
2148 appin = "12345670"
2149 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2150 try:
2151 os.remove(pskfile)
2152 except:
2153 pass
2154
2155 hapd = None
2156 try:
2157 with open(pskfile, "w") as f:
2158 f.write("# WPA PSKs\n")
2159
2160 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2161 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2162 "rsn_pairwise": "CCMP", "ap_pin": appin,
2163 "wpa_psk_file": pskfile}
2164 hapd = hostapd.add_ap(apdev[0], params)
2165
2166 logger.info("First enrollee")
2167 hapd.request("WPS_PBC")
2168 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2169 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2170 dev[0].wait_connected(timeout=30)
2171
2172 logger.info("Second enrollee")
2173 hapd.request("WPS_PBC")
2174 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2175 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
2176 dev[1].wait_connected(timeout=30)
2177
2178 logger.info("External registrar")
2179 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2180 dev[2].wps_reg(apdev[0]['bssid'], appin)
2181
2182 logger.info("Verifying PSK results")
2183 psks = get_psk(pskfile)
2184 if addr0 not in psks:
2185 raise Exception("No PSK recorded for sta0")
2186 if addr1 not in psks:
2187 raise Exception("No PSK recorded for sta1")
2188 if addr2 not in psks:
2189 raise Exception("No PSK recorded for sta2")
2190 if psks[addr0] == psks[addr1]:
2191 raise Exception("Same PSK recorded for sta0 and sta1")
2192 if psks[addr0] == psks[addr2]:
2193 raise Exception("Same PSK recorded for sta0 and sta2")
2194 if psks[addr1] == psks[addr2]:
2195 raise Exception("Same PSK recorded for sta1 and sta2")
2196
2197 dev[0].request("REMOVE_NETWORK all")
2198 logger.info("Second external registrar")
2199 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2200 dev[0].wps_reg(apdev[0]['bssid'], appin)
2201 psks2 = get_psk(pskfile)
2202 if addr0 not in psks2:
2203 raise Exception("No PSK recorded for sta0(reg)")
2204 if psks[addr0] == psks2[addr0]:
2205 raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
2206 finally:
2207 os.remove(pskfile)
2208 if hapd:
2209 dev[0].request("DISCONNECT")
2210 dev[1].request("DISCONNECT")
2211 dev[2].request("DISCONNECT")
2212 hapd.disable()
2213 dev[0].flush_scan_cache()
2214 dev[1].flush_scan_cache()
2215 dev[2].flush_scan_cache()
2216
2217 def test_ap_wps_per_station_psk_failure(dev, apdev):
2218 """WPS PBC provisioning with per-station PSK (file not writable)"""
2219 addr0 = dev[0].p2p_dev_addr()
2220 addr1 = dev[1].p2p_dev_addr()
2221 addr2 = dev[2].p2p_dev_addr()
2222 ssid = "wps"
2223 appin = "12345670"
2224 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2225 try:
2226 os.remove(pskfile)
2227 except:
2228 pass
2229
2230 hapd = None
2231 try:
2232 with open(pskfile, "w") as f:
2233 f.write("# WPA PSKs\n")
2234
2235 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2236 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2237 "rsn_pairwise": "CCMP", "ap_pin": appin,
2238 "wpa_psk_file": pskfile}
2239 hapd = hostapd.add_ap(apdev[0], params)
2240 if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
2241 raise Exception("Failed to set wpa_psk_file")
2242
2243 logger.info("First enrollee")
2244 hapd.request("WPS_PBC")
2245 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2246 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2247 dev[0].wait_connected(timeout=30)
2248
2249 logger.info("Second enrollee")
2250 hapd.request("WPS_PBC")
2251 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2252 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
2253 dev[1].wait_connected(timeout=30)
2254
2255 logger.info("External registrar")
2256 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2257 dev[2].wps_reg(apdev[0]['bssid'], appin)
2258
2259 logger.info("Verifying PSK results")
2260 psks = get_psk(pskfile)
2261 if len(psks) > 0:
2262 raise Exception("PSK recorded unexpectedly")
2263 finally:
2264 if hapd:
2265 for i in range(3):
2266 dev[i].request("DISCONNECT")
2267 hapd.disable()
2268 for i in range(3):
2269 dev[i].flush_scan_cache()
2270 os.remove(pskfile)
2271
2272 def test_ap_wps_pin_request_file(dev, apdev):
2273 """WPS PIN provisioning with configured AP"""
2274 ssid = "wps"
2275 pinfile = "/tmp/ap_wps_pin_request_file.log"
2276 if os.path.exists(pinfile):
2277 os.remove(pinfile)
2278 hapd = hostapd.add_ap(apdev[0],
2279 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2280 "wps_pin_requests": pinfile,
2281 "wpa_passphrase": "12345678", "wpa": "2",
2282 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2283 uuid = dev[0].get_status_field("uuid")
2284 pin = dev[0].wps_read_pin()
2285 try:
2286 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2287 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
2288 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
2289 if ev is None:
2290 raise Exception("PIN needed event not shown")
2291 if uuid not in ev:
2292 raise Exception("UUID mismatch")
2293 dev[0].request("WPS_CANCEL")
2294 success = False
2295 with open(pinfile, "r") as f:
2296 lines = f.readlines()
2297 for l in lines:
2298 if uuid in l:
2299 success = True
2300 break
2301 if not success:
2302 raise Exception("PIN request entry not in the log file")
2303 finally:
2304 try:
2305 os.remove(pinfile)
2306 except:
2307 pass
2308
2309 def test_ap_wps_auto_setup_with_config_file(dev, apdev):
2310 """WPS auto-setup with configuration file"""
2311 conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
2312 ifname = apdev[0]['ifname']
2313 try:
2314 with open(conffile, "w") as f:
2315 f.write("driver=nl80211\n")
2316 f.write("hw_mode=g\n")
2317 f.write("channel=1\n")
2318 f.write("ieee80211n=1\n")
2319 f.write("interface=%s\n" % ifname)
2320 f.write("ctrl_interface=/var/run/hostapd\n")
2321 f.write("ssid=wps\n")
2322 f.write("eap_server=1\n")
2323 f.write("wps_state=1\n")
2324 hapd = hostapd.add_bss(apdev[0], ifname, conffile)
2325 hapd.request("WPS_PBC")
2326 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2327 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2328 dev[0].wait_connected(timeout=30)
2329 with open(conffile, "r") as f:
2330 lines = f.read().splitlines()
2331 vals = dict()
2332 for l in lines:
2333 try:
2334 [name, value] = l.split('=', 1)
2335 vals[name] = value
2336 except ValueError as e:
2337 if "# WPS configuration" in l:
2338 pass
2339 else:
2340 raise Exception("Unexpected configuration line: " + l)
2341 if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
2342 raise Exception("Incorrect configuration: " + str(vals))
2343 finally:
2344 try:
2345 os.remove(conffile)
2346 except:
2347 pass
2348
2349 def test_ap_wps_pbc_timeout(dev, apdev, params):
2350 """wpa_supplicant PBC walk time and WPS ER SelReg timeout [long]"""
2351 if not params['long']:
2352 raise HwsimSkip("Skip test case with long duration due to --long not specified")
2353 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2354 hapd = add_ssdp_ap(apdev[0], ap_uuid)
2355
2356 location = ssdp_get_location(ap_uuid)
2357 urls = upnp_get_urls(location)
2358 eventurl = urlparse(urls['event_sub_url'])
2359 ctrlurl = urlparse(urls['control_url'])
2360
2361 url = urlparse(location)
2362 conn = HTTPConnection(url.netloc)
2363
2364 class WPSERHTTPServer(StreamRequestHandler):
2365 def handle(self):
2366 data = self.rfile.readline().strip()
2367 logger.debug(data)
2368 self.wfile.write(gen_wps_event())
2369
2370 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
2371 server.timeout = 1
2372
2373 headers = {"callback": '<http://127.0.0.1:12345/event>',
2374 "NT": "upnp:event",
2375 "timeout": "Second-1234"}
2376 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2377 resp = conn.getresponse()
2378 if resp.status != 200:
2379 raise Exception("Unexpected HTTP response: %d" % resp.status)
2380 sid = resp.getheader("sid")
2381 logger.debug("Subscription SID " + sid)
2382
2383 msg = '''<?xml version="1.0"?>
2384 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
2385 <s:Body>
2386 <u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
2387 <NewMessage>EEoAARAQQQABARASAAIAABBTAAIxSBBJAA4ANyoAASABBv///////xBIABA2LbR7pTpRkYj7
2388 VFi5hrLk
2389 </NewMessage>
2390 </u:SetSelectedRegistrar>
2391 </s:Body>
2392 </s:Envelope>'''
2393 headers = {"Content-type": 'text/xml; charset="utf-8"'}
2394 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
2395 conn.request("POST", ctrlurl.path, msg, headers)
2396 resp = conn.getresponse()
2397 if resp.status != 200:
2398 raise Exception("Unexpected HTTP response: %d" % resp.status)
2399
2400 server.handle_request()
2401
2402 logger.info("Start WPS_PBC and wait for PBC walk time expiration")
2403 if "OK" not in dev[0].request("WPS_PBC"):
2404 raise Exception("WPS_PBC failed")
2405
2406 start = os.times()[4]
2407
2408 server.handle_request()
2409 dev[1].request("BSS_FLUSH 0")
2410 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2411 only_new=True)
2412 bss = dev[1].get_bss(apdev[0]['bssid'])
2413 logger.debug("BSS: " + str(bss))
2414 if '[WPS-AUTH]' not in bss['flags']:
2415 raise Exception("WPS not indicated authorized")
2416
2417 server.handle_request()
2418
2419 wps_timeout_seen = False
2420
2421 while True:
2422 hapd.dump_monitor()
2423 dev[1].dump_monitor()
2424 if not wps_timeout_seen:
2425 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=0)
2426 if ev is not None:
2427 logger.info("PBC timeout seen")
2428 wps_timeout_seen = True
2429 else:
2430 dev[0].dump_monitor()
2431 now = os.times()[4]
2432 if now - start > 130:
2433 raise Exception("Selected registration information not removed")
2434 dev[1].request("BSS_FLUSH 0")
2435 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2436 only_new=True)
2437 bss = dev[1].get_bss(apdev[0]['bssid'])
2438 logger.debug("BSS: " + str(bss))
2439 if '[WPS-AUTH]' not in bss['flags']:
2440 break
2441 server.handle_request()
2442
2443 server.server_close()
2444
2445 if wps_timeout_seen:
2446 return
2447
2448 now = os.times()[4]
2449 if now < start + 150:
2450 dur = start + 150 - now
2451 else:
2452 dur = 1
2453 logger.info("Continue waiting for PBC timeout (%d sec)" % dur)
2454 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=dur)
2455 if ev is None:
2456 raise Exception("WPS-TIMEOUT not reported")
2457
2458 def add_ssdp_ap(ap, ap_uuid):
2459 ssid = "wps-ssdp"
2460 ap_pin = "12345670"
2461 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2462 "wpa_passphrase": "12345678", "wpa": "2",
2463 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2464 "device_name": "Wireless AP", "manufacturer": "Company",
2465 "model_name": "WAP", "model_number": "123",
2466 "serial_number": "12345", "device_type": "6-0050F204-1",
2467 "os_version": "01020300",
2468 "config_methods": "label push_button",
2469 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
2470 "friendly_name": "WPS Access Point",
2471 "manufacturer_url": "http://www.example.com/",
2472 "model_description": "Wireless Access Point",
2473 "model_url": "http://www.example.com/model/",
2474 "upc": "123456789012"}
2475 return hostapd.add_ap(ap, params)
2476
2477 def ssdp_send(msg, no_recv=False):
2478 socket.setdefaulttimeout(1)
2479 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2480 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2481 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2482 sock.bind(("127.0.0.1", 0))
2483 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2484 if no_recv:
2485 return None
2486 return sock.recv(1000).decode()
2487
2488 def ssdp_send_msearch(st, no_recv=False):
2489 msg = '\r\n'.join([
2490 'M-SEARCH * HTTP/1.1',
2491 'HOST: 239.255.255.250:1900',
2492 'MX: 1',
2493 'MAN: "ssdp:discover"',
2494 'ST: ' + st,
2495 '', ''])
2496 return ssdp_send(msg, no_recv=no_recv)
2497
2498 def test_ap_wps_ssdp_msearch(dev, apdev):
2499 """WPS AP and SSDP M-SEARCH messages"""
2500 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2501 add_ssdp_ap(apdev[0], ap_uuid)
2502
2503 msg = '\r\n'.join([
2504 'M-SEARCH * HTTP/1.1',
2505 'Host: 239.255.255.250:1900',
2506 'Mx: 1',
2507 'Man: "ssdp:discover"',
2508 'St: urn:schemas-wifialliance-org:device:WFADevice:1',
2509 '', ''])
2510 ssdp_send(msg)
2511
2512 msg = '\r\n'.join([
2513 'M-SEARCH * HTTP/1.1',
2514 'host:\t239.255.255.250:1900\t\t\t\t \t\t',
2515 'mx: \t1\t\t ',
2516 'man: \t \t "ssdp:discover" ',
2517 'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
2518 '', ''])
2519 ssdp_send(msg)
2520
2521 ssdp_send_msearch("ssdp:all")
2522 ssdp_send_msearch("upnp:rootdevice")
2523 ssdp_send_msearch("uuid:" + ap_uuid)
2524 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
2525 ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1")
2526
2527 msg = '\r\n'.join([
2528 'M-SEARCH * HTTP/1.1',
2529 'HOST:\t239.255.255.250:1900',
2530 'MAN: "ssdp:discover"',
2531 'MX: 130',
2532 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2533 '', ''])
2534 ssdp_send(msg, no_recv=True)
2535
2536 def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
2537 """WPS AP and invalid SSDP M-SEARCH messages"""
2538 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2539 add_ssdp_ap(apdev[0], ap_uuid)
2540
2541 socket.setdefaulttimeout(1)
2542 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2543 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2544 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2545 sock.bind(("127.0.0.1", 0))
2546
2547 logger.debug("Missing MX")
2548 msg = '\r\n'.join([
2549 'M-SEARCH * HTTP/1.1',
2550 'HOST: 239.255.255.250:1900',
2551 'MAN: "ssdp:discover"',
2552 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2553 '', ''])
2554 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2555
2556 logger.debug("Negative MX")
2557 msg = '\r\n'.join([
2558 'M-SEARCH * HTTP/1.1',
2559 'HOST: 239.255.255.250:1900',
2560 'MX: -1',
2561 'MAN: "ssdp:discover"',
2562 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2563 '', ''])
2564 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2565
2566 logger.debug("Invalid MX")
2567 msg = '\r\n'.join([
2568 'M-SEARCH * HTTP/1.1',
2569 'HOST: 239.255.255.250:1900',
2570 'MX; 1',
2571 'MAN: "ssdp:discover"',
2572 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2573 '', ''])
2574 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2575
2576 logger.debug("Missing MAN")
2577 msg = '\r\n'.join([
2578 'M-SEARCH * HTTP/1.1',
2579 'HOST: 239.255.255.250:1900',
2580 'MX: 1',
2581 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2582 '', ''])
2583 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2584
2585 logger.debug("Invalid MAN")
2586 msg = '\r\n'.join([
2587 'M-SEARCH * HTTP/1.1',
2588 'HOST: 239.255.255.250:1900',
2589 'MX: 1',
2590 'MAN: foo',
2591 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2592 '', ''])
2593 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2594 msg = '\r\n'.join([
2595 'M-SEARCH * HTTP/1.1',
2596 'HOST: 239.255.255.250:1900',
2597 'MX: 1',
2598 'MAN; "ssdp:discover"',
2599 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2600 '', ''])
2601 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2602
2603 logger.debug("Missing HOST")
2604 msg = '\r\n'.join([
2605 'M-SEARCH * HTTP/1.1',
2606 'MAN: "ssdp:discover"',
2607 'MX: 1',
2608 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2609 '', ''])
2610 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2611
2612 logger.debug("Missing ST")
2613 msg = '\r\n'.join([
2614 'M-SEARCH * HTTP/1.1',
2615 'HOST: 239.255.255.250:1900',
2616 'MAN: "ssdp:discover"',
2617 'MX: 1',
2618 '', ''])
2619 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2620
2621 logger.debug("Mismatching ST")
2622 msg = '\r\n'.join([
2623 'M-SEARCH * HTTP/1.1',
2624 'HOST: 239.255.255.250:1900',
2625 'MAN: "ssdp:discover"',
2626 'MX: 1',
2627 'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
2628 '', ''])
2629 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2630 msg = '\r\n'.join([
2631 'M-SEARCH * HTTP/1.1',
2632 'HOST: 239.255.255.250:1900',
2633 'MAN: "ssdp:discover"',
2634 'MX: 1',
2635 'ST: foo:bar',
2636 '', ''])
2637 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2638 msg = '\r\n'.join([
2639 'M-SEARCH * HTTP/1.1',
2640 'HOST: 239.255.255.250:1900',
2641 'MAN: "ssdp:discover"',
2642 'MX: 1',
2643 'ST: foobar',
2644 '', ''])
2645 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2646
2647 logger.debug("Invalid ST")
2648 msg = '\r\n'.join([
2649 'M-SEARCH * HTTP/1.1',
2650 'HOST: 239.255.255.250:1900',
2651 'MAN: "ssdp:discover"',
2652 'MX: 1',
2653 'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
2654 '', ''])
2655 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2656
2657 logger.debug("Invalid M-SEARCH")
2658 msg = '\r\n'.join([
2659 'M+SEARCH * HTTP/1.1',
2660 'HOST: 239.255.255.250:1900',
2661 'MAN: "ssdp:discover"',
2662 'MX: 1',
2663 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2664 '', ''])
2665 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2666 msg = '\r\n'.join([
2667 'M-SEARCH-* HTTP/1.1',
2668 'HOST: 239.255.255.250:1900',
2669 'MAN: "ssdp:discover"',
2670 'MX: 1',
2671 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2672 '', ''])
2673 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2674
2675 logger.debug("Invalid message format")
2676 sock.sendto(b"NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
2677 msg = '\r'.join([
2678 'M-SEARCH * HTTP/1.1',
2679 'HOST: 239.255.255.250:1900',
2680 'MAN: "ssdp:discover"',
2681 'MX: 1',
2682 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2683 '', ''])
2684 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2685
2686 try:
2687 r = sock.recv(1000)
2688 raise Exception("Unexpected M-SEARCH response: " + r)
2689 except socket.timeout:
2690 pass
2691
2692 logger.debug("Valid M-SEARCH")
2693 msg = '\r\n'.join([
2694 'M-SEARCH * HTTP/1.1',
2695 'HOST: 239.255.255.250:1900',
2696 'MAN: "ssdp:discover"',
2697 'MX: 1',
2698 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2699 '', ''])
2700 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2701
2702 try:
2703 r = sock.recv(1000)
2704 pass
2705 except socket.timeout:
2706 raise Exception("No SSDP response")
2707
2708 def test_ap_wps_ssdp_burst(dev, apdev):
2709 """WPS AP and SSDP burst"""
2710 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2711 add_ssdp_ap(apdev[0], ap_uuid)
2712
2713 msg = '\r\n'.join([
2714 'M-SEARCH * HTTP/1.1',
2715 'HOST: 239.255.255.250:1900',
2716 'MAN: "ssdp:discover"',
2717 'MX: 1',
2718 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2719 '', ''])
2720 socket.setdefaulttimeout(1)
2721 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2722 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2723 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2724 sock.bind(("127.0.0.1", 0))
2725 for i in range(0, 25):
2726 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2727 resp = 0
2728 while True:
2729 try:
2730 r = sock.recv(1000).decode()
2731 if not r.startswith("HTTP/1.1 200 OK\r\n"):
2732 raise Exception("Unexpected message: " + r)
2733 resp += 1
2734 except socket.timeout:
2735 break
2736 if resp < 20:
2737 raise Exception("Too few SSDP responses")
2738
2739 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2740 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2741 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2742 sock.bind(("127.0.0.1", 0))
2743 for i in range(0, 25):
2744 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2745 while True:
2746 try:
2747 r = sock.recv(1000).decode()
2748 if ap_uuid in r:
2749 break
2750 except socket.timeout:
2751 raise Exception("No SSDP response")
2752
2753 def ssdp_get_location(uuid):
2754 res = ssdp_send_msearch("uuid:" + uuid)
2755 location = None
2756 for l in res.splitlines():
2757 if l.lower().startswith("location:"):
2758 location = l.split(':', 1)[1].strip()
2759 break
2760 if location is None:
2761 raise Exception("No UPnP location found")
2762 return location
2763
2764 def upnp_get_urls(location):
2765 if sys.version_info[0] > 2:
2766 conn = urlopen(location)
2767 else:
2768 conn = urlopen(location, proxies={})
2769 tree = ET.parse(conn)
2770 root = tree.getroot()
2771 urn = '{urn:schemas-upnp-org:device-1-0}'
2772 service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
2773 res = {}
2774 res['scpd_url'] = urljoin(location, service.find(urn + 'SCPDURL').text)
2775 res['control_url'] = urljoin(location,
2776 service.find(urn + 'controlURL').text)
2777 res['event_sub_url'] = urljoin(location,
2778 service.find(urn + 'eventSubURL').text)
2779 return res
2780
2781 def upnp_soap_action(conn, path, action, include_soap_action=True,
2782 soap_action_override=None, newmsg=None, neweventtype=None,
2783 neweventmac=None):
2784 soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
2785 wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
2786 ET.register_namespace('soapenv', soapns)
2787 ET.register_namespace('wfa', wpsns)
2788 attrib = {}
2789 attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
2790 root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
2791 body = ET.SubElement(root, "{%s}Body" % soapns)
2792 act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
2793 if newmsg:
2794 msg = ET.SubElement(act, "NewMessage")
2795 msg.text = base64.b64encode(newmsg.encode()).decode()
2796 if neweventtype:
2797 msg = ET.SubElement(act, "NewWLANEventType")
2798 msg.text = neweventtype
2799 if neweventmac:
2800 msg = ET.SubElement(act, "NewWLANEventMAC")
2801 msg.text = neweventmac
2802
2803 headers = {"Content-type": 'text/xml; charset="utf-8"'}
2804 if include_soap_action:
2805 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
2806 elif soap_action_override:
2807 headers["SOAPAction"] = soap_action_override
2808 decl = b'<?xml version=\'1.0\' encoding=\'utf8\'?>\n'
2809 conn.request("POST", path, decl + ET.tostring(root), headers)
2810 return conn.getresponse()
2811
2812 def test_ap_wps_upnp(dev, apdev):
2813 """WPS AP and UPnP operations"""
2814 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2815 add_ssdp_ap(apdev[0], ap_uuid)
2816
2817 location = ssdp_get_location(ap_uuid)
2818 urls = upnp_get_urls(location)
2819
2820 if sys.version_info[0] > 2:
2821 conn = urlopen(urls['scpd_url'])
2822 else:
2823 conn = urlopen(urls['scpd_url'], proxies={})
2824 scpd = conn.read()
2825
2826 if sys.version_info[0] > 2:
2827 try:
2828 conn = urlopen(urljoin(location, "unknown.html"))
2829 raise Exception("Unexpected HTTP response to GET unknown URL")
2830 except HTTPError as e:
2831 if e.code != 404:
2832 raise Exception("Unexpected HTTP response to GET unknown URL")
2833 else:
2834 conn = urlopen(urljoin(location, "unknown.html"), proxies={})
2835 if conn.getcode() != 404:
2836 raise Exception("Unexpected HTTP response to GET unknown URL")
2837
2838 url = urlparse(location)
2839 conn = HTTPConnection(url.netloc)
2840 #conn.set_debuglevel(1)
2841 headers = {"Content-type": 'text/xml; charset="utf-8"',
2842 "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"'}
2843 conn.request("POST", "hello", "\r\n\r\n", headers)
2844 resp = conn.getresponse()
2845 if resp.status != 404:
2846 raise Exception("Unexpected HTTP response: %d" % resp.status)
2847
2848 conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
2849 resp = conn.getresponse()
2850 if resp.status != 501:
2851 raise Exception("Unexpected HTTP response: %d" % resp.status)
2852
2853 headers = {"Content-type": 'text/xml; charset="utf-8"',
2854 "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"'}
2855 ctrlurl = urlparse(urls['control_url'])
2856 conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
2857 resp = conn.getresponse()
2858 if resp.status != 401:
2859 raise Exception("Unexpected HTTP response: %d" % resp.status)
2860
2861 logger.debug("GetDeviceInfo without SOAPAction header")
2862 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2863 include_soap_action=False)
2864 if resp.status != 401:
2865 raise Exception("Unexpected HTTP response: %d" % resp.status)
2866
2867 logger.debug("GetDeviceInfo with invalid SOAPAction header")
2868 for act in ["foo",
2869 "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
2870 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
2871 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
2872 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2873 include_soap_action=False,
2874 soap_action_override=act)
2875 if resp.status != 401:
2876 raise Exception("Unexpected HTTP response: %d" % resp.status)
2877
2878 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
2879 if resp.status != 200:
2880 raise Exception("Unexpected HTTP response: %d" % resp.status)
2881 dev = resp.read().decode()
2882 if "NewDeviceInfo" not in dev:
2883 raise Exception("Unexpected GetDeviceInfo response")
2884
2885 logger.debug("PutMessage without required parameters")
2886 resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
2887 if resp.status != 600:
2888 raise Exception("Unexpected HTTP response: %d" % resp.status)
2889
2890 logger.debug("PutWLANResponse without required parameters")
2891 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
2892 if resp.status != 600:
2893 raise Exception("Unexpected HTTP response: %d" % resp.status)
2894
2895 logger.debug("SetSelectedRegistrar from unregistered ER")
2896 resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
2897 if resp.status != 501:
2898 raise Exception("Unexpected HTTP response: %d" % resp.status)
2899
2900 logger.debug("Unknown action")
2901 resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
2902 if resp.status != 401:
2903 raise Exception("Unexpected HTTP response: %d" % resp.status)
2904
2905 def test_ap_wps_upnp_subscribe(dev, apdev):
2906 """WPS AP and UPnP event subscription"""
2907 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2908 hapd = add_ssdp_ap(apdev[0], ap_uuid)
2909
2910 location = ssdp_get_location(ap_uuid)
2911 urls = upnp_get_urls(location)
2912 eventurl = urlparse(urls['event_sub_url'])
2913
2914 url = urlparse(location)
2915 conn = HTTPConnection(url.netloc)
2916 #conn.set_debuglevel(1)
2917 headers = {"callback": '<http://127.0.0.1:12345/event>',
2918 "timeout": "Second-1234"}
2919 conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
2920 resp = conn.getresponse()
2921 if resp.status != 412:
2922 raise Exception("Unexpected HTTP response: %d" % resp.status)
2923
2924 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2925 resp = conn.getresponse()
2926 if resp.status != 412:
2927 raise Exception("Unexpected HTTP response: %d" % resp.status)
2928
2929 headers = {"NT": "upnp:event",
2930 "timeout": "Second-1234"}
2931 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2932 resp = conn.getresponse()
2933 if resp.status != 412:
2934 raise Exception("Unexpected HTTP response: %d" % resp.status)
2935
2936 headers = {"callback": '<http://127.0.0.1:12345/event>',
2937 "NT": "upnp:foobar",
2938 "timeout": "Second-1234"}
2939 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2940 resp = conn.getresponse()
2941 if resp.status != 400:
2942 raise Exception("Unexpected HTTP response: %d" % resp.status)
2943
2944 logger.debug("Valid subscription")
2945 headers = {"callback": '<http://127.0.0.1:12345/event>',
2946 "NT": "upnp:event",
2947 "timeout": "Second-1234"}
2948 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2949 resp = conn.getresponse()
2950 if resp.status != 200:
2951 raise Exception("Unexpected HTTP response: %d" % resp.status)
2952 sid = resp.getheader("sid")
2953 logger.debug("Subscription SID " + sid)
2954
2955 logger.debug("Invalid re-subscription")
2956 headers = {"NT": "upnp:event",
2957 "sid": "123456734567854",
2958 "timeout": "Second-1234"}
2959 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2960 resp = conn.getresponse()
2961 if resp.status != 400:
2962 raise Exception("Unexpected HTTP response: %d" % resp.status)
2963
2964 logger.debug("Invalid re-subscription")
2965 headers = {"NT": "upnp:event",
2966 "sid": "uuid:123456734567854",
2967 "timeout": "Second-1234"}
2968 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2969 resp = conn.getresponse()
2970 if resp.status != 400:
2971 raise Exception("Unexpected HTTP response: %d" % resp.status)
2972
2973 logger.debug("Invalid re-subscription")
2974 headers = {"callback": '<http://127.0.0.1:12345/event>',
2975 "NT": "upnp:event",
2976 "sid": sid,
2977 "timeout": "Second-1234"}
2978 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2979 resp = conn.getresponse()
2980 if resp.status != 400:
2981 raise Exception("Unexpected HTTP response: %d" % resp.status)
2982
2983 logger.debug("SID mismatch in re-subscription")
2984 headers = {"NT": "upnp:event",
2985 "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
2986 "timeout": "Second-1234"}
2987 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2988 resp = conn.getresponse()
2989 if resp.status != 412:
2990 raise Exception("Unexpected HTTP response: %d" % resp.status)
2991
2992 logger.debug("Valid re-subscription")
2993 headers = {"NT": "upnp:event",
2994 "sid": sid,
2995 "timeout": "Second-1234"}
2996 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2997 resp = conn.getresponse()
2998 if resp.status != 200:
2999 raise Exception("Unexpected HTTP response: %d" % resp.status)
3000 sid2 = resp.getheader("sid")
3001 logger.debug("Subscription SID " + sid2)
3002
3003 if sid != sid2:
3004 raise Exception("Unexpected SID change")
3005
3006 logger.debug("Valid re-subscription")
3007 headers = {"NT": "upnp:event",
3008 "sid": "uuid: \t \t" + sid.split(':')[1],
3009 "timeout": "Second-1234"}
3010 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3011 resp = conn.getresponse()
3012 if resp.status != 200:
3013 raise Exception("Unexpected HTTP response: %d" % resp.status)
3014
3015 logger.debug("Invalid unsubscription")
3016 headers = {"sid": sid}
3017 conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
3018 resp = conn.getresponse()
3019 if resp.status != 412:
3020 raise Exception("Unexpected HTTP response: %d" % resp.status)
3021 headers = {"foo": "bar"}
3022 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3023 resp = conn.getresponse()
3024 if resp.status != 412:
3025 raise Exception("Unexpected HTTP response: %d" % resp.status)
3026
3027 logger.debug("Valid unsubscription")
3028 headers = {"sid": sid}
3029 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3030 resp = conn.getresponse()
3031 if resp.status != 200:
3032 raise Exception("Unexpected HTTP response: %d" % resp.status)
3033
3034 logger.debug("Unsubscription for not existing SID")
3035 headers = {"sid": sid}
3036 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3037 resp = conn.getresponse()
3038 if resp.status != 412:
3039 raise Exception("Unexpected HTTP response: %d" % resp.status)
3040
3041 logger.debug("Invalid unsubscription")
3042 headers = {"sid": " \t \tfoo"}
3043 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3044 resp = conn.getresponse()
3045 if resp.status != 400:
3046 raise Exception("Unexpected HTTP response: %d" % resp.status)
3047
3048 logger.debug("Invalid unsubscription")
3049 headers = {"sid": "uuid:\t \tfoo"}
3050 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3051 resp = conn.getresponse()
3052 if resp.status != 400:
3053 raise Exception("Unexpected HTTP response: %d" % resp.status)
3054
3055 logger.debug("Invalid unsubscription")
3056 headers = {"NT": "upnp:event",
3057 "sid": sid}
3058 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3059 resp = conn.getresponse()
3060 if resp.status != 400:
3061 raise Exception("Unexpected HTTP response: %d" % resp.status)
3062 headers = {"callback": '<http://127.0.0.1:12345/event>',
3063 "sid": sid}
3064 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3065 resp = conn.getresponse()
3066 if resp.status != 400:
3067 raise Exception("Unexpected HTTP response: %d" % resp.status)
3068
3069 logger.debug("Valid subscription with multiple callbacks")
3070 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>',
3071 "NT": "upnp:event",
3072 "timeout": "Second-1234"}
3073 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3074 resp = conn.getresponse()
3075 if resp.status != 200:
3076 raise Exception("Unexpected HTTP response: %d" % resp.status)
3077 sid = resp.getheader("sid")
3078 logger.debug("Subscription SID " + sid)
3079
3080 # Force subscription to be deleted due to errors
3081 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3082 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3083 with alloc_fail(hapd, 1, "event_build_message"):
3084 for i in range(10):
3085 dev[1].dump_monitor()
3086 dev[2].dump_monitor()
3087 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3088 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3089 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3090 dev[1].request("WPS_CANCEL")
3091 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3092 dev[2].request("WPS_CANCEL")
3093 if i % 4 == 1:
3094 time.sleep(1)
3095 else:
3096 time.sleep(0.1)
3097 time.sleep(0.2)
3098
3099 headers = {"sid": sid}
3100 conn.request("UNSUBSCRIBE", eventurl.path, "", headers)
3101 resp = conn.getresponse()
3102 if resp.status != 200 and resp.status != 412:
3103 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3104
3105 headers = {"callback": '<http://127.0.0.1:12345/event>',
3106 "NT": "upnp:event",
3107 "timeout": "Second-1234"}
3108 with alloc_fail(hapd, 1, "http_client_addr;event_send_start"):
3109 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3110 resp = conn.getresponse()
3111 if resp.status != 200:
3112 raise Exception("Unexpected HTTP response for SUBSCRIBE: %d" % resp.status)
3113 sid = resp.getheader("sid")
3114 logger.debug("Subscription SID " + sid)
3115
3116 headers = {"sid": sid}
3117 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3118 resp = conn.getresponse()
3119 if resp.status != 200:
3120 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3121
3122 headers = {"callback": '<http://127.0.0.1:12345/event>',
3123 "NT": "upnp:event",
3124 "timeout": "Second-1234"}
3125 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3126 resp = conn.getresponse()
3127 if resp.status != 200:
3128 raise Exception("Unexpected HTTP response: %d" % resp.status)
3129 sid = resp.getheader("sid")
3130 logger.debug("Subscription SID " + sid)
3131
3132 with alloc_fail(hapd, 1, "=event_add"):
3133 for i in range(2):
3134 dev[1].dump_monitor()
3135 dev[2].dump_monitor()
3136 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3137 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3138 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3139 dev[1].request("WPS_CANCEL")
3140 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3141 dev[2].request("WPS_CANCEL")
3142 if i == 0:
3143 time.sleep(1)
3144 else:
3145 time.sleep(0.1)
3146
3147 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3148 resp = conn.getresponse()
3149 if resp.status != 200:
3150 raise Exception("Unexpected HTTP response: %d" % resp.status)
3151
3152 with alloc_fail(hapd, 1, "wpabuf_dup;event_add"):
3153 dev[1].dump_monitor()
3154 dev[2].dump_monitor()
3155 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3156 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3157 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3158 dev[1].request("WPS_CANCEL")
3159 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3160 dev[2].request("WPS_CANCEL")
3161 time.sleep(0.1)
3162
3163 with fail_test(hapd, 1, "os_get_random;uuid_make;subscription_start"):
3164 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3165 resp = conn.getresponse()
3166 if resp.status != 500:
3167 raise Exception("Unexpected HTTP response: %d" % resp.status)
3168
3169 with alloc_fail(hapd, 1, "=subscription_start"):
3170 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3171 resp = conn.getresponse()
3172 if resp.status != 500:
3173 raise Exception("Unexpected HTTP response: %d" % resp.status)
3174
3175 headers = {"callback": '',
3176 "NT": "upnp:event",
3177 "timeout": "Second-1234"}
3178 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3179 resp = conn.getresponse()
3180 if resp.status != 500:
3181 raise Exception("Unexpected HTTP response: %d" % resp.status)
3182
3183 headers = {"callback": ' <',
3184 "NT": "upnp:event",
3185 "timeout": "Second-1234"}
3186 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3187 resp = conn.getresponse()
3188 if resp.status != 500:
3189 raise Exception("Unexpected HTTP response: %d" % resp.status)
3190
3191 headers = {"callback": '<http://127.0.0.1:12345/event>',
3192 "NT": "upnp:event",
3193 "timeout": "Second-1234"}
3194 with alloc_fail(hapd, 1, "wpabuf_alloc;subscription_first_event"):
3195 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3196 resp = conn.getresponse()
3197 if resp.status != 500:
3198 raise Exception("Unexpected HTTP response: %d" % resp.status)
3199
3200 with alloc_fail(hapd, 1, "event_add;subscription_first_event"):
3201 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3202 resp = conn.getresponse()
3203 if resp.status != 500:
3204 raise Exception("Unexpected HTTP response: %d" % resp.status)
3205
3206 with alloc_fail(hapd, 1, "subscr_addr_add_url"):
3207 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3208 resp = conn.getresponse()
3209 if resp.status != 500:
3210 raise Exception("Unexpected HTTP response: %d" % resp.status)
3211
3212 with alloc_fail(hapd, 2, "subscr_addr_add_url"):
3213 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3214 resp = conn.getresponse()
3215 if resp.status != 500:
3216 raise Exception("Unexpected HTTP response: %d" % resp.status)
3217
3218 for i in range(6):
3219 headers = {"callback": '<http://127.0.0.1:%d/event>' % (12345 + i),
3220 "NT": "upnp:event",
3221 "timeout": "Second-1234"}
3222 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3223 resp = conn.getresponse()
3224 if resp.status != 200:
3225 raise Exception("Unexpected HTTP response: %d" % resp.status)
3226
3227 with alloc_fail(hapd, 1, "=upnp_wps_device_send_wlan_event"):
3228 dev[1].dump_monitor()
3229 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3230 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3231 dev[1].request("WPS_CANCEL")
3232 time.sleep(0.1)
3233
3234 with alloc_fail(hapd, 1, "wpabuf_alloc;upnp_wps_device_send_event"):
3235 dev[1].dump_monitor()
3236 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3237 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3238 dev[1].request("WPS_CANCEL")
3239 time.sleep(0.1)
3240
3241 with alloc_fail(hapd, 1,
3242 "base64_gen_encode;?base64_encode;upnp_wps_device_send_wlan_event"):
3243 dev[1].dump_monitor()
3244 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3245 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3246 dev[1].request("WPS_CANCEL")
3247 time.sleep(0.1)
3248
3249 hapd.disable()
3250 with alloc_fail(hapd, 1, "get_netif_info"):
3251 if "FAIL" not in hapd.request("ENABLE"):
3252 raise Exception("ENABLE succeeded during OOM")
3253
3254 def test_ap_wps_upnp_subscribe_events(dev, apdev):
3255 """WPS AP and UPnP event subscription and many events"""
3256 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3257 hapd = add_ssdp_ap(apdev[0], ap_uuid)
3258
3259 location = ssdp_get_location(ap_uuid)
3260 urls = upnp_get_urls(location)
3261 eventurl = urlparse(urls['event_sub_url'])
3262
3263 class WPSERHTTPServer(StreamRequestHandler):
3264 def handle(self):
3265 data = self.rfile.readline().strip()
3266 logger.debug(data)
3267 self.wfile.write(gen_wps_event())
3268
3269 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
3270 server.timeout = 1
3271
3272 url = urlparse(location)
3273 conn = HTTPConnection(url.netloc)
3274
3275 headers = {"callback": '<http://127.0.0.1:12345/event>',
3276 "NT": "upnp:event",
3277 "timeout": "Second-1234"}
3278 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3279 resp = conn.getresponse()
3280 if resp.status != 200:
3281 raise Exception("Unexpected HTTP response: %d" % resp.status)
3282 sid = resp.getheader("sid")
3283 logger.debug("Subscription SID " + sid)
3284
3285 # Fetch the first event message
3286 server.handle_request()
3287
3288 # Force subscription event queue to reach the maximum length by generating
3289 # new proxied events without the ER fetching any of the pending events.
3290 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3291 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3292 for i in range(16):
3293 dev[1].dump_monitor()
3294 dev[2].dump_monitor()
3295 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3296 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3297 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3298 dev[1].request("WPS_CANCEL")
3299 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3300 dev[2].request("WPS_CANCEL")
3301 if i % 4 == 1:
3302 time.sleep(1)
3303 else:
3304 time.sleep(0.1)
3305
3306 hapd.request("WPS_PIN any 12345670")
3307 dev[1].dump_monitor()
3308 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3309 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=10)
3310 if ev is None:
3311 raise Exception("WPS success not reported")
3312
3313 # Close the WPS ER HTTP server without fetching all the pending events.
3314 # This tests hostapd code path that clears subscription and the remaining
3315 # event queue when the interface is deinitialized.
3316 server.handle_request()
3317 server.server_close()
3318
3319 dev[1].wait_connected()
3320
3321 def test_ap_wps_upnp_http_proto(dev, apdev):
3322 """WPS AP and UPnP/HTTP protocol testing"""
3323 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3324 add_ssdp_ap(apdev[0], ap_uuid)
3325
3326 location = ssdp_get_location(ap_uuid)
3327
3328 url = urlparse(location)
3329 conn = HTTPConnection(url.netloc, timeout=0.2)
3330 #conn.set_debuglevel(1)
3331
3332 conn.request("HEAD", "hello")
3333 resp = conn.getresponse()
3334 if resp.status != 501:
3335 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3336 conn.close()
3337
3338 for cmd in ["PUT", "DELETE", "TRACE", "CONNECT", "M-SEARCH", "M-POST"]:
3339 try:
3340 conn.request(cmd, "hello")
3341 resp = conn.getresponse()
3342 except Exception as e:
3343 pass
3344 conn.close()
3345
3346 headers = {"Content-Length": 'abc'}
3347 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3348 try:
3349 resp = conn.getresponse()
3350 except Exception as e:
3351 pass
3352 conn.close()
3353
3354 headers = {"Content-Length": '-10'}
3355 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3356 try:
3357 resp = conn.getresponse()
3358 except Exception as e:
3359 pass
3360 conn.close()
3361
3362 headers = {"Content-Length": '10000000000000'}
3363 conn.request("HEAD", "hello", "\r\n\r\nhello", headers)
3364 try:
3365 resp = conn.getresponse()
3366 except Exception as e:
3367 pass
3368 conn.close()
3369
3370 headers = {"Transfer-Encoding": 'abc'}
3371 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3372 resp = conn.getresponse()
3373 if resp.status != 501:
3374 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3375 conn.close()
3376
3377 headers = {"Transfer-Encoding": 'chunked'}
3378 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3379 resp = conn.getresponse()
3380 if resp.status != 501:
3381 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3382 conn.close()
3383
3384 # Too long a header
3385 conn.request("HEAD", 5000 * 'A')
3386 try:
3387 resp = conn.getresponse()
3388 except Exception as e:
3389 pass
3390 conn.close()
3391
3392 # Long URL but within header length limits
3393 conn.request("HEAD", 3000 * 'A')
3394 resp = conn.getresponse()
3395 if resp.status != 501:
3396 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3397 conn.close()
3398
3399 headers = {"Content-Length": '20'}
3400 conn.request("POST", "hello", 10 * 'A' + "\r\n\r\n", headers)
3401 try:
3402 resp = conn.getresponse()
3403 except Exception as e:
3404 pass
3405 conn.close()
3406
3407 conn.request("POST", "hello", 5000 * 'A' + "\r\n\r\n")
3408 resp = conn.getresponse()
3409 if resp.status != 404:
3410 raise Exception("Unexpected HTTP response: %d" % resp.status)
3411 conn.close()
3412
3413 conn.request("POST", "hello", 60000 * 'A' + "\r\n\r\n")
3414 try:
3415 resp = conn.getresponse()
3416 except Exception as e:
3417 pass
3418 conn.close()
3419
3420 def test_ap_wps_upnp_http_proto_chunked(dev, apdev):
3421 """WPS AP and UPnP/HTTP protocol testing for chunked encoding"""
3422 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3423 add_ssdp_ap(apdev[0], ap_uuid)
3424
3425 location = ssdp_get_location(ap_uuid)
3426
3427 url = urlparse(location)
3428 conn = HTTPConnection(url.netloc)
3429 #conn.set_debuglevel(1)
3430
3431 headers = {"Transfer-Encoding": 'chunked'}
3432 conn.request("POST", "hello",
3433 "a\r\nabcdefghij\r\n" + "2\r\nkl\r\n" + "0\r\n\r\n",
3434 headers)
3435 resp = conn.getresponse()
3436 if resp.status != 404:
3437 raise Exception("Unexpected HTTP response: %d" % resp.status)
3438 conn.close()
3439
3440 conn.putrequest("POST", "hello")
3441 conn.putheader('Transfer-Encoding', 'chunked')
3442 conn.endheaders()
3443 conn.send(b"a\r\nabcdefghij\r\n")
3444 time.sleep(0.1)
3445 conn.send(b"2\r\nkl\r\n")
3446 conn.send(b"0\r\n\r\n")
3447 resp = conn.getresponse()
3448 if resp.status != 404:
3449 raise Exception("Unexpected HTTP response: %d" % resp.status)
3450 conn.close()
3451
3452 conn.putrequest("POST", "hello")
3453 conn.putheader('Transfer-Encoding', 'chunked')
3454 conn.endheaders()
3455 completed = False
3456 try:
3457 for i in range(20000):
3458 conn.send(b"1\r\nZ\r\n")
3459 conn.send(b"0\r\n\r\n")
3460 resp = conn.getresponse()
3461 completed = True
3462 except Exception as e:
3463 pass
3464 conn.close()
3465 if completed:
3466 raise Exception("Too long chunked request did not result in connection reset")
3467
3468 headers = {"Transfer-Encoding": 'chunked'}
3469 conn.request("POST", "hello", "80000000\r\na", headers)
3470 try:
3471 resp = conn.getresponse()
3472 except Exception as e:
3473 pass
3474 conn.close()
3475
3476 conn.request("POST", "hello", "10000000\r\na", headers)
3477 try:
3478 resp = conn.getresponse()
3479 except Exception as e:
3480 pass
3481 conn.close()
3482
3483 @remote_compatible
3484 def test_ap_wps_disabled(dev, apdev):
3485 """WPS operations while WPS is disabled"""
3486 ssid = "test-wps-disabled"
3487 hapd = hostapd.add_ap(apdev[0], {"ssid": ssid})
3488 if "FAIL" not in hapd.request("WPS_PBC"):
3489 raise Exception("WPS_PBC succeeded unexpectedly")
3490 if "FAIL" not in hapd.request("WPS_CANCEL"):
3491 raise Exception("WPS_CANCEL succeeded unexpectedly")
3492
3493 def test_ap_wps_mixed_cred(dev, apdev):
3494 """WPS 2.0 STA merging mixed mode WPA/WPA2 credentials"""
3495 ssid = "test-wps-wep"
3496 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3497 "skip_cred_build": "1", "extra_cred": "wps-mixed-cred"}
3498 hapd = hostapd.add_ap(apdev[0], params)
3499 hapd.request("WPS_PBC")
3500 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3501 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3502 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
3503 if ev is None:
3504 raise Exception("WPS-SUCCESS event timed out")
3505 nets = dev[0].list_networks()
3506 if len(nets) != 1:
3507 raise Exception("Unexpected number of network blocks")
3508 id = nets[0]['id']
3509 proto = dev[0].get_network(id, "proto")
3510 if proto != "WPA RSN":
3511 raise Exception("Unexpected merged proto field value: " + proto)
3512 pairwise = dev[0].get_network(id, "pairwise")
3513 p = pairwise.split()
3514 if "CCMP" not in p or "TKIP" not in p:
3515 raise Exception("Unexpected merged pairwise field value: " + pairwise)
3516
3517 @remote_compatible
3518 def test_ap_wps_while_connected(dev, apdev):
3519 """WPS PBC provisioning while connected to another AP"""
3520 ssid = "test-wps-conf"
3521 hapd = hostapd.add_ap(apdev[0],
3522 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3523 "wpa_passphrase": "12345678", "wpa": "2",
3524 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3525
3526 hostapd.add_ap(apdev[1], {"ssid": "open"})
3527 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3528
3529 logger.info("WPS provisioning step")
3530 hapd.request("WPS_PBC")
3531 dev[0].dump_monitor()
3532 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3533 dev[0].wait_connected(timeout=30)
3534 status = dev[0].get_status()
3535 if status['bssid'] != apdev[0]['bssid']:
3536 raise Exception("Unexpected BSSID")
3537
3538 @remote_compatible
3539 def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
3540 """WPS PBC provisioning while connected to another AP and STA_AUTOCONNECT disabled"""
3541 ssid = "test-wps-conf"
3542 hapd = hostapd.add_ap(apdev[0],
3543 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3544 "wpa_passphrase": "12345678", "wpa": "2",
3545 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3546
3547 hostapd.add_ap(apdev[1], {"ssid": "open"})
3548
3549 try:
3550 dev[0].request("STA_AUTOCONNECT 0")
3551 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3552
3553 logger.info("WPS provisioning step")
3554 hapd.request("WPS_PBC")
3555 dev[0].dump_monitor()
3556 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3557 dev[0].wait_connected(timeout=30)
3558 status = dev[0].get_status()
3559 if status['bssid'] != apdev[0]['bssid']:
3560 raise Exception("Unexpected BSSID")
3561 finally:
3562 dev[0].request("STA_AUTOCONNECT 1")
3563
3564 @remote_compatible
3565 def test_ap_wps_from_event(dev, apdev):
3566 """WPS PBC event on AP to enable PBC"""
3567 ssid = "test-wps-conf"
3568 hapd = hostapd.add_ap(apdev[0],
3569 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3570 "wpa_passphrase": "12345678", "wpa": "2",
3571 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3572 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3573 dev[0].dump_monitor()
3574 hapd.dump_monitor()
3575 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3576
3577 ev = hapd.wait_event(['WPS-ENROLLEE-SEEN'], timeout=15)
3578 if ev is None:
3579 raise Exception("No WPS-ENROLLEE-SEEN event on AP")
3580 vals = ev.split(' ')
3581 if vals[1] != dev[0].p2p_interface_addr():
3582 raise Exception("Unexpected enrollee address: " + vals[1])
3583 if vals[5] != '4':
3584 raise Exception("Unexpected Device Password Id: " + vals[5])
3585 hapd.request("WPS_PBC")
3586 dev[0].wait_connected(timeout=30)
3587
3588 def test_ap_wps_ap_scan_2(dev, apdev):
3589 """AP_SCAN 2 for WPS"""
3590 ssid = "test-wps-conf"
3591 hapd = hostapd.add_ap(apdev[0],
3592 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3593 "wpa_passphrase": "12345678", "wpa": "2",
3594 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3595 hapd.request("WPS_PBC")
3596
3597 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
3598 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
3599 wpas.dump_monitor()
3600
3601 if "OK" not in wpas.request("AP_SCAN 2"):
3602 raise Exception("Failed to set AP_SCAN 2")
3603
3604 wpas.flush_scan_cache()
3605 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
3606 wpas.dump_monitor()
3607 wpas.request("WPS_PBC " + apdev[0]['bssid'])
3608 ev = wpas.wait_event(["WPS-SUCCESS"], timeout=15)
3609 if ev is None:
3610 raise Exception("WPS-SUCCESS event timed out")
3611 wpas.wait_connected(timeout=30)
3612 wpas.dump_monitor()
3613 wpas.request("DISCONNECT")
3614 wpas.wait_disconnected()
3615 id = wpas.list_networks()[0]['id']
3616 pairwise = wpas.get_network(id, "pairwise")
3617 if "CCMP" not in pairwise.split():
3618 raise Exception("Unexpected pairwise parameter value: " + pairwise)
3619 group = wpas.get_network(id, "group")
3620 if "CCMP" not in group.split():
3621 raise Exception("Unexpected group parameter value: " + group)
3622 # Need to select a single cipher for ap_scan=2 testing
3623 wpas.set_network(id, "pairwise", "CCMP")
3624 wpas.set_network(id, "group", "CCMP")
3625 wpas.request("BSS_FLUSH 0")
3626 wpas.dump_monitor()
3627 wpas.request("REASSOCIATE")
3628 wpas.wait_connected(timeout=30)
3629 wpas.dump_monitor()
3630 wpas.request("DISCONNECT")
3631 wpas.wait_disconnected()
3632 wpas.flush_scan_cache()
3633
3634 @remote_compatible
3635 def test_ap_wps_eapol_workaround(dev, apdev):
3636 """EAPOL workaround code path for 802.1X header length mismatch"""
3637 ssid = "test-wps"
3638 hapd = hostapd.add_ap(apdev[0],
3639 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
3640 bssid = apdev[0]['bssid']
3641 hapd.request("SET ext_eapol_frame_io 1")
3642 dev[0].request("SET ext_eapol_frame_io 1")
3643 hapd.request("WPS_PBC")
3644 dev[0].request("WPS_PBC")
3645
3646 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3647 if ev is None:
3648 raise Exception("Timeout on EAPOL-TX from hostapd")
3649
3650 res = dev[0].request("EAPOL_RX " + bssid + " 020000040193000501FFFF")
3651 if "OK" not in res:
3652 raise Exception("EAPOL_RX to wpa_supplicant failed")
3653
3654 def test_ap_wps_iteration(dev, apdev):
3655 """WPS PIN and iterate through APs without selected registrar"""
3656 ssid = "test-wps-conf"
3657 hapd = hostapd.add_ap(apdev[0],
3658 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3659 "wpa_passphrase": "12345678", "wpa": "2",
3660 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3661
3662 ssid2 = "test-wps-conf2"
3663 hapd2 = hostapd.add_ap(apdev[1],
3664 {"ssid": ssid2, "eap_server": "1", "wps_state": "2",
3665 "wpa_passphrase": "12345678", "wpa": "2",
3666 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3667
3668 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3669 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
3670 dev[0].dump_monitor()
3671 pin = dev[0].request("WPS_PIN any")
3672
3673 # Wait for iteration through all WPS APs to happen before enabling any
3674 # Registrar.
3675 for i in range(2):
3676 ev = dev[0].wait_event(["Associated with"], timeout=30)
3677 if ev is None:
3678 raise Exception("No association seen")
3679 ev = dev[0].wait_event(["WPS-M2D"], timeout=10)
3680 if ev is None:
3681 raise Exception("No M2D from AP")
3682 dev[0].wait_disconnected()
3683
3684 # Verify that each AP requested PIN
3685 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3686 if ev is None:
3687 raise Exception("No WPS-PIN-NEEDED event from AP")
3688 ev = hapd2.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3689 if ev is None:
3690 raise Exception("No WPS-PIN-NEEDED event from AP2")
3691
3692 # Provide PIN to one of the APs and verify that connection gets formed
3693 hapd.request("WPS_PIN any " + pin)
3694 dev[0].wait_connected(timeout=30)
3695
3696 def test_ap_wps_iteration_error(dev, apdev):
3697 """WPS AP iteration on no Selected Registrar and error case with an AP"""
3698 ssid = "test-wps-conf-pin"
3699 hapd = hostapd.add_ap(apdev[0],
3700 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3701 "wpa_passphrase": "12345678", "wpa": "2",
3702 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3703 "wps_independent": "1"})
3704 hapd.request("SET ext_eapol_frame_io 1")
3705 bssid = apdev[0]['bssid']
3706 pin = dev[0].wps_read_pin()
3707 dev[0].request("WPS_PIN any " + pin)
3708
3709 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3710 if ev is None:
3711 raise Exception("No EAPOL-TX (EAP-Request/Identity) from hostapd")
3712 dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
3713
3714 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3715 if ev is None:
3716 raise Exception("No EAPOL-TX (EAP-WSC/Start) from hostapd")
3717 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=5)
3718 if ev is None:
3719 raise Exception("No CTRL-EVENT-EAP-STARTED")
3720
3721 # Do not forward any more EAPOL frames to test wpa_supplicant behavior for
3722 # a case with an incorrectly behaving WPS AP.
3723
3724 # Start the real target AP and activate registrar on it.
3725 hapd2 = hostapd.add_ap(apdev[1],
3726 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3727 "wpa_passphrase": "12345678", "wpa": "2",
3728 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3729 "wps_independent": "1"})
3730 hapd2.request("WPS_PIN any " + pin)
3731
3732 dev[0].wait_disconnected(timeout=15)
3733 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
3734 if ev is None:
3735 raise Exception("No CTRL-EVENT-EAP-STARTED for the second AP")
3736 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
3737 if ev is None:
3738 raise Exception("No WPS-CRED-RECEIVED for the second AP")
3739 dev[0].wait_connected(timeout=15)
3740
3741 @remote_compatible
3742 def test_ap_wps_priority(dev, apdev):
3743 """WPS PIN provisioning with configured AP and wps_priority"""
3744 ssid = "test-wps-conf-pin"
3745 hapd = hostapd.add_ap(apdev[0],
3746 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3747 "wpa_passphrase": "12345678", "wpa": "2",
3748 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3749 logger.info("WPS provisioning step")
3750 pin = dev[0].wps_read_pin()
3751 hapd.request("WPS_PIN any " + pin)
3752 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3753 dev[0].dump_monitor()
3754 try:
3755 dev[0].request("SET wps_priority 6")
3756 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3757 dev[0].wait_connected(timeout=30)
3758 netw = dev[0].list_networks()
3759 prio = dev[0].get_network(netw[0]['id'], 'priority')
3760 if prio != '6':
3761 raise Exception("Unexpected network priority: " + prio)
3762 finally:
3763 dev[0].request("SET wps_priority 0")
3764
3765 @remote_compatible
3766 def test_ap_wps_and_non_wps(dev, apdev):
3767 """WPS and non-WPS AP in single hostapd process"""
3768 params = {"ssid": "wps", "eap_server": "1", "wps_state": "1"}
3769 hapd = hostapd.add_ap(apdev[0], params)
3770
3771 params = {"ssid": "no wps"}
3772 hapd2 = hostapd.add_ap(apdev[1], params)
3773
3774 appin = hapd.request("WPS_AP_PIN random")
3775 if "FAIL" in appin:
3776 raise Exception("Could not generate random AP PIN")
3777 if appin not in hapd.request("WPS_AP_PIN get"):
3778 raise Exception("Could not fetch current AP PIN")
3779
3780 if "FAIL" in hapd.request("WPS_PBC"):
3781 raise Exception("WPS_PBC failed")
3782 if "FAIL" in hapd.request("WPS_CANCEL"):
3783 raise Exception("WPS_CANCEL failed")
3784
3785 def test_ap_wps_init_oom(dev, apdev):
3786 """Initial AP configuration and OOM during PSK generation"""
3787 ssid = "test-wps"
3788 params = {"ssid": ssid, "eap_server": "1", "wps_state": "1"}
3789 hapd = hostapd.add_ap(apdev[0], params)
3790
3791 with alloc_fail(hapd, 1, "base64_gen_encode;?base64_encode;wps_build_cred"):
3792 pin = dev[0].wps_read_pin()
3793 hapd.request("WPS_PIN any " + pin)
3794 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3795 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3796 dev[0].wait_disconnected()
3797
3798 hapd.request("WPS_PIN any " + pin)
3799 dev[0].wait_connected(timeout=30)
3800
3801 @remote_compatible
3802 def test_ap_wps_er_oom(dev, apdev):
3803 """WPS ER OOM in XML processing"""
3804 try:
3805 _test_ap_wps_er_oom(dev, apdev)
3806 finally:
3807 dev[0].request("WPS_ER_STOP")
3808 dev[1].request("WPS_CANCEL")
3809 dev[0].request("DISCONNECT")
3810
3811 def _test_ap_wps_er_oom(dev, apdev):
3812 ssid = "wps-er-ap-config"
3813 ap_pin = "12345670"
3814 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3815 hostapd.add_ap(apdev[0],
3816 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3817 "wpa_passphrase": "12345678", "wpa": "2",
3818 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3819 "device_name": "Wireless AP", "manufacturer": "Company",
3820 "model_name": "WAP", "model_number": "123",
3821 "serial_number": "12345", "device_type": "6-0050F204-1",
3822 "os_version": "01020300",
3823 "config_methods": "label push_button",
3824 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
3825
3826 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
3827
3828 with alloc_fail(dev[0], 1,
3829 "base64_gen_decode;?base64_decode;xml_get_base64_item"):
3830 dev[0].request("WPS_ER_START ifname=lo")
3831 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=3)
3832 if ev is not None:
3833 raise Exception("Unexpected AP discovery")
3834
3835 dev[0].request("WPS_ER_STOP")
3836 dev[0].request("WPS_ER_START ifname=lo")
3837 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
3838 if ev is None:
3839 raise Exception("AP discovery timed out")
3840
3841 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3842 with alloc_fail(dev[0], 1,
3843 "base64_gen_decode;?base64_decode;xml_get_base64_item"):
3844 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
3845 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
3846 if ev is None:
3847 raise Exception("PBC scan failed")
3848 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
3849 if ev is None:
3850 raise Exception("Enrollee discovery timed out")
3851
3852 @remote_compatible
3853 def test_ap_wps_er_init_oom(dev, apdev):
3854 """WPS ER and OOM during init"""
3855 try:
3856 _test_ap_wps_er_init_oom(dev, apdev)
3857 finally:
3858 dev[0].request("WPS_ER_STOP")
3859
3860 def _test_ap_wps_er_init_oom(dev, apdev):
3861 with alloc_fail(dev[0], 1, "wps_er_init"):
3862 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3863 raise Exception("WPS_ER_START succeeded during OOM")
3864 with alloc_fail(dev[0], 1, "http_server_init"):
3865 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3866 raise Exception("WPS_ER_START succeeded during OOM")
3867 with alloc_fail(dev[0], 2, "http_server_init"):
3868 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3869 raise Exception("WPS_ER_START succeeded during OOM")
3870 with alloc_fail(dev[0], 1, "eloop_sock_table_add_sock;?eloop_register_sock;wps_er_ssdp_init"):
3871 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3872 raise Exception("WPS_ER_START succeeded during OOM")
3873 with fail_test(dev[0], 1, "os_get_random;wps_er_init"):
3874 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3875 raise Exception("WPS_ER_START succeeded during os_get_random failure")
3876
3877 @remote_compatible
3878 def test_ap_wps_er_init_fail(dev, apdev):
3879 """WPS ER init failure"""
3880 if "FAIL" not in dev[0].request("WPS_ER_START ifname=does-not-exist"):
3881 dev[0].request("WPS_ER_STOP")
3882 raise Exception("WPS_ER_START with non-existing ifname succeeded")
3883
3884 def test_ap_wps_wpa_cli_action(dev, apdev, test_params):
3885 """WPS events and wpa_cli action script"""
3886 logdir = os.path.abspath(test_params['logdir'])
3887 pidfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.pid')
3888 logfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.res')
3889 actionfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.action.sh')
3890
3891 with open(actionfile, 'w') as f:
3892 f.write('#!/bin/sh\n')
3893 f.write('echo $* >> %s\n' % logfile)
3894 # Kill the process and wait some time before returning to allow all the
3895 # pending events to be processed with some of this happening after the
3896 # eloop SIGALRM signal has been scheduled.
3897 f.write('if [ $2 = "WPS-SUCCESS" -a -r %s ]; then kill `cat %s`; sleep 1; fi\n' % (pidfile, pidfile))
3898
3899 os.chmod(actionfile, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC |
3900 stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
3901
3902 ssid = "test-wps-conf"
3903 hapd = hostapd.add_ap(apdev[0],
3904 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3905 "wpa_passphrase": "12345678", "wpa": "2",
3906 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3907
3908 prg = os.path.join(test_params['logdir'],
3909 'alt-wpa_supplicant/wpa_supplicant/wpa_cli')
3910 if not os.path.exists(prg):
3911 prg = '../../wpa_supplicant/wpa_cli'
3912 arg = [prg, '-P', pidfile, '-B', '-i', dev[0].ifname, '-a', actionfile]
3913 subprocess.call(arg)
3914
3915 arg = ['ps', 'ax']
3916 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3917 out = cmd.communicate()[0].decode()
3918 cmd.wait()
3919 logger.debug("Processes:\n" + out)
3920 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) not in out:
3921 raise Exception("Did not see wpa_cli running")
3922
3923 hapd.request("WPS_PIN any 12345670")
3924 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3925 dev[0].dump_monitor()
3926 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3927 dev[0].wait_connected(timeout=30)
3928
3929 for i in range(30):
3930 if not os.path.exists(pidfile):
3931 break
3932 time.sleep(0.1)
3933
3934 if not os.path.exists(logfile):
3935 raise Exception("wpa_cli action results file not found")
3936 with open(logfile, 'r') as f:
3937 res = f.read()
3938 if "WPS-SUCCESS" not in res:
3939 raise Exception("WPS-SUCCESS event not seen in action file")
3940
3941 arg = ['ps', 'ax']
3942 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3943 out = cmd.communicate()[0].decode()
3944 cmd.wait()
3945 logger.debug("Remaining processes:\n" + out)
3946 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) in out:
3947 raise Exception("wpa_cli still running")
3948
3949 if os.path.exists(pidfile):
3950 raise Exception("PID file not removed")
3951
3952 def test_ap_wps_er_ssdp_proto(dev, apdev):
3953 """WPS ER SSDP protocol testing"""
3954 try:
3955 _test_ap_wps_er_ssdp_proto(dev, apdev)
3956 finally:
3957 dev[0].request("WPS_ER_STOP")
3958
3959 def _test_ap_wps_er_ssdp_proto(dev, apdev):
3960 socket.setdefaulttimeout(1)
3961 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
3962 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
3963 sock.bind(("239.255.255.250", 1900))
3964 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo foo"):
3965 raise Exception("Invalid filter accepted")
3966 if "OK" not in dev[0].request("WPS_ER_START ifname=lo 1.2.3.4"):
3967 raise Exception("WPS_ER_START with filter failed")
3968 (msg, addr) = sock.recvfrom(1000)
3969 msg = msg.decode()
3970 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3971 if "M-SEARCH" not in msg:
3972 raise Exception("Not an M-SEARCH")
3973 sock.sendto(b"FOO", addr)
3974 time.sleep(0.1)
3975 dev[0].request("WPS_ER_STOP")
3976
3977 dev[0].request("WPS_ER_START ifname=lo")
3978 (msg, addr) = sock.recvfrom(1000)
3979 msg = msg.decode()
3980 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3981 if "M-SEARCH" not in msg:
3982 raise Exception("Not an M-SEARCH")
3983 sock.sendto(b"FOO", addr)
3984 sock.sendto(b"HTTP/1.1 200 OK\r\nFOO\r\n\r\n", addr)
3985 sock.sendto(b"HTTP/1.1 200 OK\r\nNTS:foo\r\n\r\n", addr)
3986 sock.sendto(b"HTTP/1.1 200 OK\r\nNTS:ssdp:byebye\r\n\r\n", addr)
3987 sock.sendto(b"HTTP/1.1 200 OK\r\ncache-control: foo=1\r\n\r\n", addr)
3988 sock.sendto(b"HTTP/1.1 200 OK\r\ncache-control: max-age=1\r\n\r\n", addr)
3989 sock.sendto(b"HTTP/1.1 200 OK\r\nusn:\r\n\r\n", addr)
3990 sock.sendto(b"HTTP/1.1 200 OK\r\nusn:foo\r\n\r\n", addr)
3991 sock.sendto(b"HTTP/1.1 200 OK\r\nusn: uuid:\r\n\r\n", addr)
3992 sock.sendto(b"HTTP/1.1 200 OK\r\nusn: uuid: \r\n\r\n", addr)
3993 sock.sendto(b"HTTP/1.1 200 OK\r\nusn: uuid: foo\r\n\r\n", addr)
3994 sock.sendto(b"HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\n\r\n", addr)
3995 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)
3996 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)
3997 with alloc_fail(dev[0], 1, "wps_er_ap_add"):
3998 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)
3999 time.sleep(0.1)
4000 with alloc_fail(dev[0], 2, "wps_er_ap_add"):
4001 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)
4002 time.sleep(0.1)
4003
4004 # Add an AP with bogus URL
4005 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)
4006 # Update timeout on AP without updating URL
4007 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)
4008 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4009 if ev is None:
4010 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4011
4012 # Add an AP with a valid URL (but no server listing to it)
4013 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)
4014 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4015 if ev is None:
4016 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4017
4018 sock.close()
4019
4020 wps_event_url = None
4021
4022 def gen_upnp_info(eventSubURL='wps_event', controlURL='wps_control',
4023 udn='uuid:27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'):
4024 payload = '''<?xml version="1.0"?>
4025 <root xmlns="urn:schemas-upnp-org:device-1-0">
4026 <specVersion>
4027 <major>1</major>
4028 <minor>0</minor>
4029 </specVersion>
4030 <device>
4031 <deviceType>urn:schemas-wifialliance-org:device:WFADevice:1</deviceType>
4032 <friendlyName>WPS Access Point</friendlyName>
4033 <manufacturer>Company</manufacturer>
4034 <modelName>WAP</modelName>
4035 <modelNumber>123</modelNumber>
4036 <serialNumber>12345</serialNumber>
4037 '''
4038 if udn:
4039 payload += '<UDN>' + udn + '</UDN>'
4040 payload += '''<serviceList>
4041 <service>
4042 <serviceType>urn:schemas-wifialliance-org:service:WFAWLANConfig:1</serviceType>
4043 <serviceId>urn:wifialliance-org:serviceId:WFAWLANConfig1</serviceId>
4044 <SCPDURL>wps_scpd.xml</SCPDURL>
4045 '''
4046 if controlURL:
4047 payload += '<controlURL>' + controlURL + '</controlURL>\n'
4048 if eventSubURL:
4049 payload += '<eventSubURL>' + eventSubURL + '</eventSubURL>\n'
4050 payload += '''</service>
4051 </serviceList>
4052 </device>
4053 </root>
4054 '''
4055 hdr = 'HTTP/1.1 200 OK\r\n' + \
4056 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4057 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4058 'Connection: close\r\n' + \
4059 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4060 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4061 return (hdr + payload).encode()
4062
4063 def gen_wps_control(payload_override=None):
4064 payload = '''<?xml version="1.0"?>
4065 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4066 <s:Body>
4067 <u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4068 <NewDeviceInfo>EEoAARAQIgABBBBHABAn6oAanlxOc72C+Jy80Q1+ECAABgIAAAADABAaABCJZ7DPtbU3Ust9
4069 Z3wJF07WEDIAwH45D3i1OqB7eJGwTzqeapS71h3KyXncK2xJZ+xqScrlorNEg6LijBJzG2Ca
4070 +FZli0iliDJd397yAx/jk4nFXco3q5ylBSvSw9dhJ5u1xBKSnTilKGlUHPhLP75PUqM3fot9
4071 7zwtFZ4bx6x1sBA6oEe2d0aUJmLumQGCiKEIWlnxs44zego/2tAe81bDzdPBM7o5HH/FUhD+
4072 KoGzFXp51atP+1n9Vta6AkI0Vye99JKLcC6Md9dMJltSVBgd4Xc4lRAEAAIAIxAQAAIADRAN
4073 AAEBEAgAAgAEEEQAAQIQIQAHQ29tcGFueRAjAANXQVAQJAADMTIzEEIABTEyMzQ1EFQACAAG
4074 AFDyBAABEBEAC1dpcmVsZXNzIEFQEDwAAQEQAgACAAAQEgACAAAQCQACAAAQLQAEgQIDABBJ
4075 AAYANyoAASA=
4076 </NewDeviceInfo>
4077 </u:GetDeviceInfoResponse>
4078 </s:Body>
4079 </s:Envelope>
4080 '''
4081 if payload_override:
4082 payload = payload_override
4083 hdr = 'HTTP/1.1 200 OK\r\n' + \
4084 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4085 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4086 'Connection: close\r\n' + \
4087 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4088 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4089 return (hdr + payload).encode()
4090
4091 def gen_wps_event(sid='uuid:7eb3342a-8a5f-47fe-a585-0785bfec6d8a'):
4092 payload = ""
4093 hdr = 'HTTP/1.1 200 OK\r\n' + \
4094 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4095 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4096 'Connection: close\r\n' + \
4097 'Content-Length: ' + str(len(payload)) + '\r\n'
4098 if sid:
4099 hdr += 'SID: ' + sid + '\r\n'
4100 hdr += 'Timeout: Second-1801\r\n' + \
4101 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4102 return (hdr + payload).encode()
4103
4104 class WPSAPHTTPServer(StreamRequestHandler):
4105 def handle(self):
4106 data = self.rfile.readline().decode().strip()
4107 logger.info("HTTP server received: " + data)
4108 while True:
4109 hdr = self.rfile.readline().decode().strip()
4110 if len(hdr) == 0:
4111 break
4112 logger.info("HTTP header: " + hdr)
4113 if "CALLBACK:" in hdr:
4114 global wps_event_url
4115 wps_event_url = hdr.split(' ')[1].strip('<>')
4116
4117 if "GET /foo.xml" in data:
4118 self.handle_upnp_info()
4119 elif "POST /wps_control" in data:
4120 self.handle_wps_control()
4121 elif "SUBSCRIBE /wps_event" in data:
4122 self.handle_wps_event()
4123 else:
4124 self.handle_others(data)
4125
4126 def handle_upnp_info(self):
4127 self.wfile.write(gen_upnp_info())
4128
4129 def handle_wps_control(self):
4130 self.wfile.write(gen_wps_control())
4131
4132 def handle_wps_event(self):
4133 self.wfile.write(gen_wps_event())
4134
4135 def handle_others(self, data):
4136 logger.info("Ignore HTTP request: " + data)
4137
4138 class MyTCPServer(TCPServer):
4139 def __init__(self, addr, handler):
4140 self.allow_reuse_address = True
4141 TCPServer.__init__(self, addr, handler)
4142
4143 def wps_er_start(dev, http_server, max_age=1, wait_m_search=False,
4144 location_url=None):
4145 socket.setdefaulttimeout(1)
4146 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4147 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4148 sock.bind(("239.255.255.250", 1900))
4149 dev.request("WPS_ER_START ifname=lo")
4150 for i in range(100):
4151 (msg, addr) = sock.recvfrom(1000)
4152 msg = msg.decode()
4153 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4154 if "M-SEARCH" in msg:
4155 break
4156 if not wait_m_search:
4157 raise Exception("Not an M-SEARCH")
4158 if i == 99:
4159 raise Exception("No M-SEARCH seen")
4160
4161 # Add an AP with a valid URL and server listing to it
4162 server = MyTCPServer(("127.0.0.1", 12345), http_server)
4163 if not location_url:
4164 location_url = 'http://127.0.0.1:12345/foo.xml'
4165 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)
4166 server.timeout = 1
4167 return server, sock
4168
4169 def wps_er_stop(dev, sock, server, on_alloc_fail=False):
4170 sock.close()
4171 server.server_close()
4172
4173 if on_alloc_fail:
4174 done = False
4175 for i in range(50):
4176 res = dev.request("GET_ALLOC_FAIL")
4177 if res.startswith("0:"):
4178 done = True
4179 break
4180 time.sleep(0.1)
4181 if not done:
4182 raise Exception("No allocation failure reported")
4183 else:
4184 ev = dev.wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4185 if ev is None:
4186 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4187 dev.request("WPS_ER_STOP")
4188
4189 def run_wps_er_proto_test(dev, handler, no_event_url=False, location_url=None):
4190 try:
4191 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
4192 server, sock = wps_er_start(dev, handler, location_url=location_url)
4193 global wps_event_url
4194 wps_event_url = None
4195 server.handle_request()
4196 server.handle_request()
4197 server.handle_request()
4198 server.server_close()
4199 if no_event_url:
4200 if wps_event_url:
4201 raise Exception("Received event URL unexpectedly")
4202 return
4203 if wps_event_url is None:
4204 raise Exception("Did not get event URL")
4205 logger.info("Event URL: " + wps_event_url)
4206 finally:
4207 dev.request("WPS_ER_STOP")
4208
4209 def send_wlanevent(url, uuid, data, no_response=False):
4210 conn = HTTPConnection(url.netloc)
4211 payload = '''<?xml version="1.0" encoding="utf-8"?>
4212 <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4213 <e:property><STAStatus>1</STAStatus></e:property>
4214 <e:property><APStatus>1</APStatus></e:property>
4215 <e:property><WLANEvent>'''
4216 payload += base64.b64encode(data).decode()
4217 payload += '</WLANEvent></e:property></e:propertyset>'
4218 headers = {"Content-type": 'text/xml; charset="utf-8"',
4219 "Server": "Unspecified, UPnP/1.0, Unspecified",
4220 "HOST": url.netloc,
4221 "NT": "upnp:event",
4222 "SID": "uuid:" + uuid,
4223 "SEQ": "0",
4224 "Content-Length": str(len(payload))}
4225 conn.request("NOTIFY", url.path, payload, headers)
4226 if no_response:
4227 try:
4228 conn.getresponse()
4229 except Exception as e:
4230 pass
4231 return
4232 resp = conn.getresponse()
4233 if resp.status != 200:
4234 raise Exception("Unexpected HTTP response: %d" % resp.status)
4235
4236 def test_ap_wps_er_http_proto(dev, apdev):
4237 """WPS ER HTTP protocol testing"""
4238 try:
4239 _test_ap_wps_er_http_proto(dev, apdev)
4240 finally:
4241 dev[0].request("WPS_ER_STOP")
4242
4243 def _test_ap_wps_er_http_proto(dev, apdev):
4244 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
4245 server, sock = wps_er_start(dev[0], WPSAPHTTPServer, max_age=15)
4246 global wps_event_url
4247 wps_event_url = None
4248 server.handle_request()
4249 server.handle_request()
4250 server.handle_request()
4251 server.server_close()
4252 if wps_event_url is None:
4253 raise Exception("Did not get event URL")
4254 logger.info("Event URL: " + wps_event_url)
4255
4256 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
4257 if ev is None:
4258 raise Exception("No WPS-ER-AP-ADD event")
4259 if uuid not in ev:
4260 raise Exception("UUID mismatch")
4261
4262 sock.close()
4263
4264 logger.info("Valid Probe Request notification")
4265 url = urlparse(wps_event_url)
4266 conn = HTTPConnection(url.netloc)
4267 payload = '''<?xml version="1.0" encoding="utf-8"?>
4268 <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4269 <e:property><STAStatus>1</STAStatus></e:property>
4270 <e:property><APStatus>1</APStatus></e:property>
4271 <e:property><WLANEvent>ATAyOjAwOjAwOjAwOjAwOjAwEEoAARAQOgABAhAIAAIxSBBHABA2LbR7pTpRkYj7VFi5hrLk
4272 EFQACAAAAAAAAAAAEDwAAQMQAgACAAAQCQACAAAQEgACAAAQIQABIBAjAAEgECQAASAQEQAI
4273 RGV2aWNlIEEQSQAGADcqAAEg
4274 </WLANEvent></e:property>
4275 </e:propertyset>
4276 '''
4277 headers = {"Content-type": 'text/xml; charset="utf-8"',
4278 "Server": "Unspecified, UPnP/1.0, Unspecified",
4279 "HOST": url.netloc,
4280 "NT": "upnp:event",
4281 "SID": "uuid:" + uuid,
4282 "SEQ": "0",
4283 "Content-Length": str(len(payload))}
4284 conn.request("NOTIFY", url.path, payload, headers)
4285 resp = conn.getresponse()
4286 if resp.status != 200:
4287 raise Exception("Unexpected HTTP response: %d" % resp.status)
4288
4289 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=5)
4290 if ev is None:
4291 raise Exception("No WPS-ER-ENROLLEE-ADD event")
4292 if "362db47b-a53a-5191-88fb-5458b986b2e4" not in ev:
4293 raise Exception("No Enrollee UUID match")
4294
4295 logger.info("Incorrect event URL AP id")
4296 conn = HTTPConnection(url.netloc)
4297 conn.request("NOTIFY", url.path + '123', payload, headers)
4298 resp = conn.getresponse()
4299 if resp.status != 404:
4300 raise Exception("Unexpected HTTP response: %d" % resp.status)
4301
4302 logger.info("Missing AP id")
4303 conn = HTTPConnection(url.netloc)
4304 conn.request("NOTIFY", '/event/' + url.path.split('/')[2],
4305 payload, headers)
4306 time.sleep(0.1)
4307
4308 logger.info("Incorrect event URL event id")
4309 conn = HTTPConnection(url.netloc)
4310 conn.request("NOTIFY", '/event/123456789/123', payload, headers)
4311 time.sleep(0.1)
4312
4313 logger.info("Incorrect event URL prefix")
4314 conn = HTTPConnection(url.netloc)
4315 conn.request("NOTIFY", '/foobar/123456789/123', payload, headers)
4316 resp = conn.getresponse()
4317 if resp.status != 404:
4318 raise Exception("Unexpected HTTP response: %d" % resp.status)
4319
4320 logger.info("Unsupported request")
4321 conn = HTTPConnection(url.netloc)
4322 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4323 resp = conn.getresponse()
4324 if resp.status != 501:
4325 raise Exception("Unexpected HTTP response: %d" % resp.status)
4326
4327 logger.info("Unsupported request and OOM")
4328 with alloc_fail(dev[0], 1, "wps_er_http_req"):
4329 conn = HTTPConnection(url.netloc)
4330 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4331 time.sleep(0.5)
4332
4333 logger.info("Too short WLANEvent")
4334 data = b'\x00'
4335 send_wlanevent(url, uuid, data)
4336
4337 logger.info("Invalid WLANEventMAC")
4338 data = b'\x00qwertyuiopasdfghjklzxcvbnm'
4339 send_wlanevent(url, uuid, data)
4340
4341 logger.info("Unknown WLANEventType")
4342 data = b'\xff02:00:00:00:00:00'
4343 send_wlanevent(url, uuid, data)
4344
4345 logger.info("Probe Request notification without any attributes")
4346 data = b'\x0102:00:00:00:00:00'
4347 send_wlanevent(url, uuid, data)
4348
4349 logger.info("Probe Request notification with invalid attribute")
4350 data = b'\x0102:00:00:00:00:00\xff'
4351 send_wlanevent(url, uuid, data)
4352
4353 logger.info("EAP message without any attributes")
4354 data = b'\x0202:00:00:00:00:00'
4355 send_wlanevent(url, uuid, data)
4356
4357 logger.info("EAP message with invalid attribute")
4358 data = b'\x0202:00:00:00:00:00\xff'
4359 send_wlanevent(url, uuid, data)
4360
4361 logger.info("EAP message from new STA and not M1")
4362 data = b'\x0202:ff:ff:ff:ff:ff' + b'\x10\x22\x00\x01\x05'
4363 send_wlanevent(url, uuid, data)
4364
4365 logger.info("EAP message: M1")
4366 data = b'\x0202:00:00:00:00:00'
4367 data += b'\x10\x22\x00\x01\x04'
4368 data += b'\x10\x47\x00\x10' + 16 * b'\x00'
4369 data += b'\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4370 data += b'\x10\x1a\x00\x10' + 16 * b'\x00'
4371 data += b'\x10\x32\x00\xc0' + 192 * b'\x00'
4372 data += b'\x10\x04\x00\x02\x00\x00'
4373 data += b'\x10\x10\x00\x02\x00\x00'
4374 data += b'\x10\x0d\x00\x01\x00'
4375 data += b'\x10\x08\x00\x02\x00\x00'
4376 data += b'\x10\x44\x00\x01\x00'
4377 data += b'\x10\x21\x00\x00'
4378 data += b'\x10\x23\x00\x00'
4379 data += b'\x10\x24\x00\x00'
4380 data += b'\x10\x42\x00\x00'
4381 data += b'\x10\x54\x00\x08' + 8 * b'\x00'
4382 data += b'\x10\x11\x00\x00'
4383 data += b'\x10\x3c\x00\x01\x00'
4384 data += b'\x10\x02\x00\x02\x00\x00'
4385 data += b'\x10\x12\x00\x02\x00\x00'
4386 data += b'\x10\x09\x00\x02\x00\x00'
4387 data += b'\x10\x2d\x00\x04\x00\x00\x00\x00'
4388 m1 = data
4389 send_wlanevent(url, uuid, data)
4390
4391 logger.info("EAP message: WSC_ACK")
4392 data = b'\x0202:00:00:00:00:00' + b'\x10\x22\x00\x01\x0d'
4393 send_wlanevent(url, uuid, data)
4394
4395 logger.info("EAP message: M1")
4396 send_wlanevent(url, uuid, m1)
4397
4398 logger.info("EAP message: WSC_NACK")
4399 data = b'\x0202:00:00:00:00:00' + b'\x10\x22\x00\x01\x0e'
4400 send_wlanevent(url, uuid, data)
4401
4402 logger.info("EAP message: M1 - Too long attribute values")
4403 data = b'\x0202:00:00:00:00:00'
4404 data += b'\x10\x11\x00\x21' + 33 * b'\x00'
4405 data += b'\x10\x45\x00\x21' + 33 * b'\x00'
4406 data += b'\x10\x42\x00\x21' + 33 * b'\x00'
4407 data += b'\x10\x24\x00\x21' + 33 * b'\x00'
4408 data += b'\x10\x23\x00\x21' + 33 * b'\x00'
4409 data += b'\x10\x21\x00\x41' + 65 * b'\x00'
4410 data += b'\x10\x49\x00\x09\x00\x37\x2a\x05\x02\x00\x00\x05\x00'
4411 send_wlanevent(url, uuid, data)
4412
4413 logger.info("EAP message: M1 missing UUID-E")
4414 data = b'\x0202:00:00:00:00:00'
4415 data += b'\x10\x22\x00\x01\x04'
4416 send_wlanevent(url, uuid, data)
4417
4418 logger.info("EAP message: M1 missing MAC Address")
4419 data += b'\x10\x47\x00\x10' + 16 * b'\x00'
4420 send_wlanevent(url, uuid, data)
4421
4422 logger.info("EAP message: M1 missing Enrollee Nonce")
4423 data += b'\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4424 send_wlanevent(url, uuid, data)
4425
4426 logger.info("EAP message: M1 missing Public Key")
4427 data += b'\x10\x1a\x00\x10' + 16 * b'\x00'
4428 send_wlanevent(url, uuid, data)
4429
4430 logger.info("EAP message: M1 missing Authentication Type flags")
4431 data += b'\x10\x32\x00\xc0' + 192 * b'\x00'
4432 send_wlanevent(url, uuid, data)
4433
4434 logger.info("EAP message: M1 missing Encryption Type Flags")
4435 data += b'\x10\x04\x00\x02\x00\x00'
4436 send_wlanevent(url, uuid, data)
4437
4438 logger.info("EAP message: M1 missing Connection Type flags")
4439 data += b'\x10\x10\x00\x02\x00\x00'
4440 send_wlanevent(url, uuid, data)
4441
4442 logger.info("EAP message: M1 missing Config Methods")
4443 data += b'\x10\x0d\x00\x01\x00'
4444 send_wlanevent(url, uuid, data)
4445
4446 logger.info("EAP message: M1 missing Wi-Fi Protected Setup State")
4447 data += b'\x10\x08\x00\x02\x00\x00'
4448 send_wlanevent(url, uuid, data)
4449
4450 logger.info("EAP message: M1 missing Manufacturer")
4451 data += b'\x10\x44\x00\x01\x00'
4452 send_wlanevent(url, uuid, data)
4453
4454 logger.info("EAP message: M1 missing Model Name")
4455 data += b'\x10\x21\x00\x00'
4456 send_wlanevent(url, uuid, data)
4457
4458 logger.info("EAP message: M1 missing Model Number")
4459 data += b'\x10\x23\x00\x00'
4460 send_wlanevent(url, uuid, data)
4461
4462 logger.info("EAP message: M1 missing Serial Number")
4463 data += b'\x10\x24\x00\x00'
4464 send_wlanevent(url, uuid, data)
4465
4466 logger.info("EAP message: M1 missing Primary Device Type")
4467 data += b'\x10\x42\x00\x00'
4468 send_wlanevent(url, uuid, data)
4469
4470 logger.info("EAP message: M1 missing Device Name")
4471 data += b'\x10\x54\x00\x08' + 8 * b'\x00'
4472 send_wlanevent(url, uuid, data)
4473
4474 logger.info("EAP message: M1 missing RF Bands")
4475 data += b'\x10\x11\x00\x00'
4476 send_wlanevent(url, uuid, data)
4477
4478 logger.info("EAP message: M1 missing Association State")
4479 data += b'\x10\x3c\x00\x01\x00'
4480 send_wlanevent(url, uuid, data)
4481
4482 logger.info("EAP message: M1 missing Device Password ID")
4483 data += b'\x10\x02\x00\x02\x00\x00'
4484 send_wlanevent(url, uuid, data)
4485
4486 logger.info("EAP message: M1 missing Configuration Error")
4487 data += b'\x10\x12\x00\x02\x00\x00'
4488 send_wlanevent(url, uuid, data)
4489
4490 logger.info("EAP message: M1 missing OS Version")
4491 data += b'\x10\x09\x00\x02\x00\x00'
4492 send_wlanevent(url, uuid, data)
4493
4494 logger.info("Check max concurrent requests")
4495 addr = (url.hostname, url.port)
4496 socks = {}
4497 for i in range(20):
4498 socks[i] = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4499 socket.IPPROTO_TCP)
4500 socks[i].settimeout(10)
4501 socks[i].connect(addr)
4502 for i in range(20):
4503 socks[i].send(b"GET / HTTP/1.1\r\n\r\n")
4504 count = 0
4505 for i in range(20):
4506 try:
4507 res = socks[i].recv(100).decode()
4508 if "HTTP/1" in res:
4509 count += 1
4510 else:
4511 logger.info("recv[%d]: len=%d" % (i, len(res)))
4512 except:
4513 pass
4514 socks[i].close()
4515 logger.info("%d concurrent HTTP GET operations returned response" % count)
4516 if count < 8:
4517 raise Exception("Too few concurrent HTTP connections accepted")
4518
4519 logger.info("OOM in HTTP server")
4520 for func in ["http_request_init", "httpread_create",
4521 "eloop_register_timeout;httpread_create",
4522 "eloop_sock_table_add_sock;?eloop_register_sock;httpread_create",
4523 "httpread_hdr_analyze"]:
4524 with alloc_fail(dev[0], 1, func):
4525 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4526 socket.IPPROTO_TCP)
4527 sock.connect(addr)
4528 sock.send(b"GET / HTTP/1.1\r\n\r\n")
4529 try:
4530 sock.recv(100)
4531 except:
4532 pass
4533 sock.close()
4534
4535 logger.info("Invalid HTTP header")
4536 for req in [" GET / HTTP/1.1\r\n\r\n",
4537 "HTTP/1.1 200 OK\r\n\r\n",
4538 "HTTP/\r\n\r\n",
4539 "GET %%a%aa% HTTP/1.1\r\n\r\n",
4540 "GET / HTTP/1.1\r\n FOO\r\n\r\n",
4541 "NOTIFY / HTTP/1.1\r\n" + 4097*'a' + '\r\n\r\n',
4542 "NOTIFY / HTTP/1.1\r\n\r\n" + 8193*'a',
4543 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n foo\r\n",
4544 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n1\r\nfoo\r\n",
4545 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\n",
4546 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\naa\ra\r\n\ra"]:
4547 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4548 socket.IPPROTO_TCP)
4549 sock.settimeout(0.1)
4550 sock.connect(addr)
4551 sock.send(req.encode())
4552 try:
4553 sock.recv(100)
4554 except:
4555 pass
4556 sock.close()
4557
4558 with alloc_fail(dev[0], 2, "httpread_read_handler"):
4559 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4560 socket.IPPROTO_TCP)
4561 sock.connect(addr)
4562 sock.send(b"NOTIFY / HTTP/1.1\r\n\r\n" + 4500 * b'a')
4563 try:
4564 sock.recv(100)
4565 except:
4566 pass
4567 sock.close()
4568
4569 conn = HTTPConnection(url.netloc)
4570 payload = '<foo'
4571 headers = {"Content-type": 'text/xml; charset="utf-8"',
4572 "Server": "Unspecified, UPnP/1.0, Unspecified",
4573 "HOST": url.netloc,
4574 "NT": "upnp:event",
4575 "SID": "uuid:" + uuid,
4576 "SEQ": "0",
4577 "Content-Length": str(len(payload))}
4578 conn.request("NOTIFY", url.path, payload, headers)
4579 resp = conn.getresponse()
4580 if resp.status != 200:
4581 raise Exception("Unexpected HTTP response: %d" % resp.status)
4582
4583 conn = HTTPConnection(url.netloc)
4584 payload = '<WLANEvent foo></WLANEvent>'
4585 headers = {"Content-type": 'text/xml; charset="utf-8"',
4586 "Server": "Unspecified, UPnP/1.0, Unspecified",
4587 "HOST": url.netloc,
4588 "NT": "upnp:event",
4589 "SID": "uuid:" + uuid,
4590 "SEQ": "0",
4591 "Content-Length": str(len(payload))}
4592 conn.request("NOTIFY", url.path, payload, headers)
4593 resp = conn.getresponse()
4594 if resp.status != 200:
4595 raise Exception("Unexpected HTTP response: %d" % resp.status)
4596
4597 with alloc_fail(dev[0], 1, "xml_get_first_item"):
4598 send_wlanevent(url, uuid, b'')
4599
4600 with alloc_fail(dev[0], 1, "wpabuf_alloc_ext_data;xml_get_base64_item"):
4601 send_wlanevent(url, uuid, b'foo')
4602
4603 for func in ["wps_init",
4604 "wps_process_manufacturer",
4605 "wps_process_model_name",
4606 "wps_process_model_number",
4607 "wps_process_serial_number",
4608 "wps_process_dev_name"]:
4609 with alloc_fail(dev[0], 1, func):
4610 send_wlanevent(url, uuid, m1)
4611
4612 with alloc_fail(dev[0], 1, "wps_er_http_resp_ok"):
4613 send_wlanevent(url, uuid, m1, no_response=True)
4614
4615 with alloc_fail(dev[0], 1, "wps_er_http_resp_not_found"):
4616 url2 = urlparse(wps_event_url.replace('/event/', '/notfound/'))
4617 send_wlanevent(url2, uuid, m1, no_response=True)
4618
4619 logger.info("EAP message: M1")
4620 data = b'\x0202:11:22:00:00:00'
4621 data += b'\x10\x22\x00\x01\x04'
4622 data += b'\x10\x47\x00\x10' + 16 * b'\x00'
4623 data += b'\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4624 data += b'\x10\x1a\x00\x10' + 16 * b'\x00'
4625 data += b'\x10\x32\x00\xc0' + 192 * b'\x00'
4626 data += b'\x10\x04\x00\x02\x00\x00'
4627 data += b'\x10\x10\x00\x02\x00\x00'
4628 data += b'\x10\x0d\x00\x01\x00'
4629 data += b'\x10\x08\x00\x02\x00\x00'
4630 data += b'\x10\x44\x00\x01\x00'
4631 data += b'\x10\x21\x00\x00'
4632 data += b'\x10\x23\x00\x00'
4633 data += b'\x10\x24\x00\x00'
4634 data += b'\x10\x42\x00\x00'
4635 data += b'\x10\x54\x00\x08' + 8 * b'\x00'
4636 data += b'\x10\x11\x00\x00'
4637 data += b'\x10\x3c\x00\x01\x00'
4638 data += b'\x10\x02\x00\x02\x00\x00'
4639 data += b'\x10\x12\x00\x02\x00\x00'
4640 data += b'\x10\x09\x00\x02\x00\x00'
4641 data += b'\x10\x2d\x00\x04\x00\x00\x00\x00'
4642 dev[0].dump_monitor()
4643 with alloc_fail(dev[0], 1, "wps_er_add_sta_data"):
4644 send_wlanevent(url, uuid, data)
4645 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=0.1)
4646 if ev is not None:
4647 raise Exception("Unexpected enrollee add event")
4648 send_wlanevent(url, uuid, data)
4649 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=2)
4650 if ev is None:
4651 raise Exception("Enrollee add event not seen")
4652
4653 with alloc_fail(dev[0], 1,
4654 "base64_gen_encode;?base64_encode;wps_er_soap_hdr"):
4655 send_wlanevent(url, uuid, data)
4656
4657 with alloc_fail(dev[0], 1, "wpabuf_alloc;wps_er_soap_hdr"):
4658 send_wlanevent(url, uuid, data)
4659
4660 with alloc_fail(dev[0], 1, "http_client_url_parse;wps_er_sta_send_msg"):
4661 send_wlanevent(url, uuid, data)
4662
4663 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_sta_send_msg"):
4664 send_wlanevent(url, uuid, data)
4665
4666 def test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
4667 """WPS ER HTTP protocol testing - no eventSubURL"""
4668 class WPSAPHTTPServer_no_event_sub_url(WPSAPHTTPServer):
4669 def handle_upnp_info(self):
4670 self.wfile.write(gen_upnp_info(eventSubURL=None))
4671 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_event_sub_url,
4672 no_event_url=True)
4673
4674 def test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev):
4675 """WPS ER HTTP protocol testing - DNS name in eventSubURL"""
4676 class WPSAPHTTPServer_event_sub_url_dns(WPSAPHTTPServer):
4677 def handle_upnp_info(self):
4678 self.wfile.write(gen_upnp_info(eventSubURL='http://example.com/wps_event'))
4679 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_event_sub_url_dns,
4680 no_event_url=True)
4681
4682 def test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4683 """WPS ER HTTP protocol testing - subscribe OOM"""
4684 try:
4685 _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev)
4686 finally:
4687 dev[0].request("WPS_ER_STOP")
4688
4689 def _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4690 tests = [(1, "http_client_url_parse"),
4691 (1, "wpabuf_alloc;wps_er_subscribe"),
4692 (1, "http_client_addr"),
4693 (1, "eloop_sock_table_add_sock;?eloop_register_sock;http_client_addr"),
4694 (1, "eloop_register_timeout;http_client_addr")]
4695 for count, func in tests:
4696 with alloc_fail(dev[0], count, func):
4697 server, sock = wps_er_start(dev[0], WPSAPHTTPServer)
4698 server.handle_request()
4699 server.handle_request()
4700 wps_er_stop(dev[0], sock, server, on_alloc_fail=True)
4701
4702 def test_ap_wps_er_http_proto_no_sid(dev, apdev):
4703 """WPS ER HTTP protocol testing - no SID"""
4704 class WPSAPHTTPServer_no_sid(WPSAPHTTPServer):
4705 def handle_wps_event(self):
4706 self.wfile.write(gen_wps_event(sid=None))
4707 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_sid)
4708
4709 def test_ap_wps_er_http_proto_invalid_sid_no_uuid(dev, apdev):
4710 """WPS ER HTTP protocol testing - invalid SID - no UUID"""
4711 class WPSAPHTTPServer_invalid_sid_no_uuid(WPSAPHTTPServer):
4712 def handle_wps_event(self):
4713 self.wfile.write(gen_wps_event(sid='FOO'))
4714 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_no_uuid)
4715
4716 def test_ap_wps_er_http_proto_invalid_sid_uuid(dev, apdev):
4717 """WPS ER HTTP protocol testing - invalid SID UUID"""
4718 class WPSAPHTTPServer_invalid_sid_uuid(WPSAPHTTPServer):
4719 def handle_wps_event(self):
4720 self.wfile.write(gen_wps_event(sid='uuid:FOO'))
4721 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_uuid)
4722
4723 def test_ap_wps_er_http_proto_subscribe_failing(dev, apdev):
4724 """WPS ER HTTP protocol testing - SUBSCRIBE failing"""
4725 class WPSAPHTTPServer_fail_subscribe(WPSAPHTTPServer):
4726 def handle_wps_event(self):
4727 payload = ""
4728 hdr = 'HTTP/1.1 404 Not Found\r\n' + \
4729 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4730 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4731 'Connection: close\r\n' + \
4732 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4733 'Timeout: Second-1801\r\n' + \
4734 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4735 self.wfile.write((hdr + payload).encode())
4736 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_fail_subscribe)
4737
4738 def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4739 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4740 class WPSAPHTTPServer_subscribe_invalid_response(WPSAPHTTPServer):
4741 def handle_wps_event(self):
4742 payload = ""
4743 hdr = 'HTTP/1.1 FOO\r\n' + \
4744 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4745 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4746 'Connection: close\r\n' + \
4747 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4748 'Timeout: Second-1801\r\n' + \
4749 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4750 self.wfile.write((hdr + payload).encode())
4751 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_subscribe_invalid_response)
4752
4753 def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4754 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4755 class WPSAPHTTPServer_invalid_m1(WPSAPHTTPServer):
4756 def handle_wps_control(self):
4757 payload = '''<?xml version="1.0"?>
4758 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4759 <s:Body>
4760 <u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4761 <NewDeviceInfo>Rk9P</NewDeviceInfo>
4762 </u:GetDeviceInfoResponse>
4763 </s:Body>
4764 </s:Envelope>
4765 '''
4766 self.wfile.write(gen_wps_control(payload_override=payload))
4767 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_m1, no_event_url=True)
4768
4769 def test_ap_wps_er_http_proto_upnp_info_no_device(dev, apdev):
4770 """WPS ER HTTP protocol testing - No device in UPnP info"""
4771 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4772 def handle_upnp_info(self):
4773 payload = '''<?xml version="1.0"?>
4774 <root xmlns="urn:schemas-upnp-org:device-1-0">
4775 <specVersion>
4776 <major>1</major>
4777 <minor>0</minor>
4778 </specVersion>
4779 </root>
4780 '''
4781 hdr = 'HTTP/1.1 200 OK\r\n' + \
4782 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4783 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4784 'Connection: close\r\n' + \
4785 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4786 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4787 self.wfile.write((hdr + payload).encode())
4788 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4789
4790 def test_ap_wps_er_http_proto_upnp_info_no_device_type(dev, apdev):
4791 """WPS ER HTTP protocol testing - No deviceType in UPnP info"""
4792 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4793 def handle_upnp_info(self):
4794 payload = '''<?xml version="1.0"?>
4795 <root xmlns="urn:schemas-upnp-org:device-1-0">
4796 <specVersion>
4797 <major>1</major>
4798 <minor>0</minor>
4799 </specVersion>
4800 <device>
4801 </device>
4802 </root>
4803 '''
4804 hdr = 'HTTP/1.1 200 OK\r\n' + \
4805 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4806 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4807 'Connection: close\r\n' + \
4808 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4809 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4810 self.wfile.write((hdr + payload).encode())
4811 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4812
4813 def test_ap_wps_er_http_proto_upnp_info_invalid_udn_uuid(dev, apdev):
4814 """WPS ER HTTP protocol testing - Invalid UDN UUID"""
4815 class WPSAPHTTPServer_invalid_udn_uuid(WPSAPHTTPServer):
4816 def handle_upnp_info(self):
4817 self.wfile.write(gen_upnp_info(udn='uuid:foo'))
4818 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_udn_uuid)
4819
4820 def test_ap_wps_er_http_proto_no_control_url(dev, apdev):
4821 """WPS ER HTTP protocol testing - no controlURL"""
4822 class WPSAPHTTPServer_no_control_url(WPSAPHTTPServer):
4823 def handle_upnp_info(self):
4824 self.wfile.write(gen_upnp_info(controlURL=None))
4825 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_control_url,
4826 no_event_url=True)
4827
4828 def test_ap_wps_er_http_proto_control_url_dns(dev, apdev):
4829 """WPS ER HTTP protocol testing - DNS name in controlURL"""
4830 class WPSAPHTTPServer_control_url_dns(WPSAPHTTPServer):
4831 def handle_upnp_info(self):
4832 self.wfile.write(gen_upnp_info(controlURL='http://example.com/wps_control'))
4833 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_control_url_dns,
4834 no_event_url=True)
4835
4836 def test_ap_wps_http_timeout(dev, apdev):
4837 """WPS AP/ER and HTTP timeout"""
4838 try:
4839 _test_ap_wps_http_timeout(dev, apdev)
4840 finally:
4841 dev[0].request("WPS_ER_STOP")
4842
4843 def _test_ap_wps_http_timeout(dev, apdev):
4844 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
4845 add_ssdp_ap(apdev[0], ap_uuid)
4846
4847 location = ssdp_get_location(ap_uuid)
4848 url = urlparse(location)
4849 addr = (url.hostname, url.port)
4850 logger.debug("Open HTTP connection to hostapd, but do not complete request")
4851 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4852 socket.IPPROTO_TCP)
4853 sock.connect(addr)
4854 sock.send(b"G")
4855
4856 class DummyServer(StreamRequestHandler):
4857 def handle(self):
4858 logger.debug("DummyServer - start 31 sec wait")
4859 time.sleep(31)
4860 logger.debug("DummyServer - wait done")
4861
4862 logger.debug("Start WPS ER")
4863 server, sock2 = wps_er_start(dev[0], DummyServer, max_age=40,
4864 wait_m_search=True)
4865
4866 logger.debug("Start server to accept, but not complete, HTTP connection from WPS ER")
4867 # This will wait for 31 seconds..
4868 server.handle_request()
4869
4870 logger.debug("Complete HTTP connection with hostapd (that should have already closed the connection)")
4871 try:
4872 sock.send("ET / HTTP/1.1\r\n\r\n")
4873 res = sock.recv(100)
4874 sock.close()
4875 except:
4876 pass
4877
4878 def test_ap_wps_er_url_parse(dev, apdev):
4879 """WPS ER and URL parsing special cases"""
4880 try:
4881 _test_ap_wps_er_url_parse(dev, apdev)
4882 finally:
4883 dev[0].request("WPS_ER_STOP")
4884
4885 def _test_ap_wps_er_url_parse(dev, apdev):
4886 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4887 sock.settimeout(1)
4888 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4889 sock.bind(("239.255.255.250", 1900))
4890 dev[0].request("WPS_ER_START ifname=lo")
4891 (msg, addr) = sock.recvfrom(1000)
4892 msg = msg.decode()
4893 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4894 if "M-SEARCH" not in msg:
4895 raise Exception("Not an M-SEARCH")
4896 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)
4897 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4898 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)
4899 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4900 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)
4901 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4902
4903 sock.close()
4904
4905 def test_ap_wps_er_link_update(dev, apdev):
4906 """WPS ER and link update special cases"""
4907 class WPSAPHTTPServer_link_update(WPSAPHTTPServer):
4908 def handle_upnp_info(self):
4909 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4910 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update)
4911
4912 class WPSAPHTTPServer_link_update2(WPSAPHTTPServer):
4913 def handle_others(self, data):
4914 if "GET / " in data:
4915 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4916 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update2,
4917 location_url='http://127.0.0.1:12345')
4918
4919 def test_ap_wps_er_http_client(dev, apdev):
4920 """WPS ER and HTTP client special cases"""
4921 with alloc_fail(dev[0], 1, "http_link_update"):
4922 run_wps_er_proto_test(dev[0], WPSAPHTTPServer)
4923
4924 with alloc_fail(dev[0], 1, "wpabuf_alloc;http_client_url"):
4925 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4926
4927 with alloc_fail(dev[0], 1, "httpread_create;http_client_tx_ready"):
4928 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4929
4930 class WPSAPHTTPServer_req_as_resp(WPSAPHTTPServer):
4931 def handle_upnp_info(self):
4932 self.wfile.write(b"GET / HTTP/1.1\r\n\r\n")
4933 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_req_as_resp,
4934 no_event_url=True)
4935
4936 def test_ap_wps_init_oom(dev, apdev):
4937 """wps_init OOM cases"""
4938 ssid = "test-wps"
4939 appin = "12345670"
4940 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
4941 "ap_pin": appin}
4942 hapd = hostapd.add_ap(apdev[0], params)
4943 pin = dev[0].wps_read_pin()
4944
4945 with alloc_fail(hapd, 1, "wps_init"):
4946 hapd.request("WPS_PIN any " + pin)
4947 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4948 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4949 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4950 if ev is None:
4951 raise Exception("No EAP failure reported")
4952 dev[0].request("WPS_CANCEL")
4953
4954 with alloc_fail(dev[0], 2, "wps_init"):
4955 hapd.request("WPS_PIN any " + pin)
4956 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4957 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4958 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4959 if ev is None:
4960 raise Exception("No EAP failure reported")
4961 dev[0].request("WPS_CANCEL")
4962
4963 with alloc_fail(dev[0], 2, "wps_init"):
4964 hapd.request("WPS_PBC")
4965 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4966 dev[0].request("WPS_PBC %s" % (apdev[0]['bssid']))
4967 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4968 if ev is None:
4969 raise Exception("No EAP failure reported")
4970 dev[0].request("WPS_CANCEL")
4971
4972 dev[0].dump_monitor()
4973 new_ssid = "wps-new-ssid"
4974 new_passphrase = "1234567890"
4975 with alloc_fail(dev[0], 3, "wps_init"):
4976 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
4977 new_passphrase, no_wait=True)
4978 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4979 if ev is None:
4980 raise Exception("No EAP failure reported")
4981
4982 dev[0].flush_scan_cache()
4983
4984 @remote_compatible
4985 def test_ap_wps_invalid_assoc_req_elem(dev, apdev):
4986 """WPS and invalid IE in Association Request frame"""
4987 ssid = "test-wps"
4988 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
4989 hapd = hostapd.add_ap(apdev[0], params)
4990 pin = "12345670"
4991 hapd.request("WPS_PIN any " + pin)
4992 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4993 try:
4994 dev[0].request("VENDOR_ELEM_ADD 13 dd050050f20410")
4995 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4996 for i in range(5):
4997 ev = hapd.wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=10)
4998 if ev and "vendor=14122" in ev:
4999 break
5000 if ev is None or "vendor=14122" not in ev:
5001 raise Exception("EAP-WSC not started")
5002 dev[0].request("WPS_CANCEL")
5003 finally:
5004 dev[0].request("VENDOR_ELEM_REMOVE 13 *")
5005
5006 def test_ap_wps_pbc_pin_mismatch(dev, apdev):
5007 """WPS PBC/PIN mismatch"""
5008 ssid = "test-wps"
5009 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
5010 hapd = hostapd.add_ap(apdev[0], params)
5011 hapd.request("SET wps_version_number 0x10")
5012 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5013 hapd.request("WPS_PBC")
5014 pin = dev[0].wps_read_pin()
5015 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5016 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5017 if ev is None:
5018 raise Exception("Scan did not complete")
5019 dev[0].request("WPS_CANCEL")
5020
5021 hapd.request("WPS_CANCEL")
5022 dev[0].flush_scan_cache()
5023
5024 @remote_compatible
5025 def test_ap_wps_ie_invalid(dev, apdev):
5026 """WPS PIN attempt with AP that has invalid WSC IE"""
5027 ssid = "test-wps"
5028 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5029 "vendor_elements": "dd050050f20410"}
5030 hapd = hostapd.add_ap(apdev[0], params)
5031 params = {'ssid': "another", "vendor_elements": "dd050050f20410"}
5032 hostapd.add_ap(apdev[1], params)
5033 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5034 pin = dev[0].wps_read_pin()
5035 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5036 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5037 if ev is None:
5038 raise Exception("Scan did not complete")
5039 dev[0].request("WPS_CANCEL")
5040
5041 @remote_compatible
5042 def test_ap_wps_scan_prio_order(dev, apdev):
5043 """WPS scan priority ordering"""
5044 ssid = "test-wps"
5045 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
5046 hapd = hostapd.add_ap(apdev[0], params)
5047 params = {'ssid': "another", "vendor_elements": "dd050050f20410"}
5048 hostapd.add_ap(apdev[1], params)
5049 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5050 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
5051 pin = dev[0].wps_read_pin()
5052 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5053 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5054 if ev is None:
5055 raise Exception("Scan did not complete")
5056 dev[0].request("WPS_CANCEL")
5057
5058 def test_ap_wps_probe_req_ie_oom(dev, apdev):
5059 """WPS ProbeReq IE OOM"""
5060 ssid = "test-wps"
5061 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
5062 hapd = hostapd.add_ap(apdev[0], params)
5063 pin = dev[0].wps_read_pin()
5064 hapd.request("WPS_PIN any " + pin)
5065 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5066 with alloc_fail(dev[0], 1, "wps_build_probe_req_ie"):
5067 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5068 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5069 if ev is None:
5070 raise Exception("Association not seen")
5071 dev[0].request("WPS_CANCEL")
5072 dev[0].wait_disconnected()
5073
5074 with alloc_fail(dev[0], 1, "wps_ie_encapsulate"):
5075 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5076 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5077 if ev is None:
5078 raise Exception("Association not seen")
5079 dev[0].request("WPS_CANCEL")
5080 hapd.disable()
5081 dev[0].request("REMOVE_NETWORK all")
5082 dev[0].wait_disconnected()
5083 time.sleep(0.2)
5084 dev[0].flush_scan_cache()
5085
5086 def test_ap_wps_assoc_req_ie_oom(dev, apdev):
5087 """WPS AssocReq IE OOM"""
5088 ssid = "test-wps"
5089 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
5090 hapd = hostapd.add_ap(apdev[0], params)
5091 pin = dev[0].wps_read_pin()
5092 hapd.request("WPS_PIN any " + pin)
5093 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5094 with alloc_fail(dev[0], 1, "wps_build_assoc_req_ie"):
5095 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5096 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5097 if ev is None:
5098 raise Exception("Association not seen")
5099 dev[0].request("WPS_CANCEL")
5100
5101 def test_ap_wps_assoc_resp_ie_oom(dev, apdev):
5102 """WPS AssocResp IE OOM"""
5103 ssid = "test-wps"
5104 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
5105 hapd = hostapd.add_ap(apdev[0], params)
5106 pin = dev[0].wps_read_pin()
5107 hapd.request("WPS_PIN any " + pin)
5108 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5109 with alloc_fail(hapd, 1, "wps_build_assoc_resp_ie"):
5110 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5111 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5112 if ev is None:
5113 raise Exception("Association not seen")
5114 dev[0].request("WPS_CANCEL")
5115
5116 @remote_compatible
5117 def test_ap_wps_bss_info_errors(dev, apdev):
5118 """WPS BSS info errors"""
5119 params = {"ssid": "1",
5120 "vendor_elements": "dd0e0050f20410440001ff101100010a"}
5121 hostapd.add_ap(apdev[0], params)
5122 params = {'ssid': "2", "vendor_elements": "dd050050f20410"}
5123 hostapd.add_ap(apdev[1], params)
5124 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5125 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
5126 bss = dev[0].get_bss(apdev[0]['bssid'])
5127 logger.info("BSS: " + str(bss))
5128 if "wps_state" in bss:
5129 raise Exception("Unexpected wps_state in BSS info")
5130 if 'wps_device_name' not in bss:
5131 raise Exception("No wps_device_name in BSS info")
5132 if bss['wps_device_name'] != '_':
5133 raise Exception("Unexpected wps_device_name value")
5134 bss = dev[0].get_bss(apdev[1]['bssid'])
5135 logger.info("BSS: " + str(bss))
5136
5137 with alloc_fail(dev[0], 1, "=wps_attr_text"):
5138 bss = dev[0].get_bss(apdev[0]['bssid'])
5139 logger.info("BSS(OOM): " + str(bss))
5140
5141 def wps_run_pbc_fail_ap(apdev, dev, hapd):
5142 hapd.request("WPS_PBC")
5143 dev.scan_for_bss(apdev['bssid'], freq="2412")
5144 dev.request("WPS_PBC " + apdev['bssid'])
5145 ev = dev.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5146 if ev is None:
5147 raise Exception("No EAP failure reported")
5148 dev.request("WPS_CANCEL")
5149 dev.wait_disconnected()
5150 for i in range(5):
5151 try:
5152 dev.flush_scan_cache()
5153 break
5154 except Exception as e:
5155 if str(e).startswith("Failed to trigger scan"):
5156 # Try again
5157 time.sleep(1)
5158 else:
5159 raise
5160
5161 def wps_run_pbc_fail(apdev, dev):
5162 hapd = wps_start_ap(apdev)
5163 wps_run_pbc_fail_ap(apdev, dev, hapd)
5164
5165 @remote_compatible
5166 def test_ap_wps_pk_oom(dev, apdev):
5167 """WPS and public key OOM"""
5168 with alloc_fail(dev[0], 1, "wps_build_public_key"):
5169 wps_run_pbc_fail(apdev[0], dev[0])
5170
5171 @remote_compatible
5172 def test_ap_wps_pk_oom_ap(dev, apdev):
5173 """WPS and public key OOM on AP"""
5174 hapd = wps_start_ap(apdev[0])
5175 with alloc_fail(hapd, 1, "wps_build_public_key"):
5176 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5177
5178 @remote_compatible
5179 def test_ap_wps_encr_oom_ap(dev, apdev):
5180 """WPS and encrypted settings decryption OOM on AP"""
5181 hapd = wps_start_ap(apdev[0])
5182 pin = dev[0].wps_read_pin()
5183 hapd.request("WPS_PIN any " + pin)
5184 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5185 with alloc_fail(hapd, 1, "wps_decrypt_encr_settings"):
5186 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
5187 ev = hapd.wait_event(["WPS-FAIL"], timeout=10)
5188 if ev is None:
5189 raise Exception("No WPS-FAIL reported")
5190 dev[0].request("WPS_CANCEL")
5191 dev[0].wait_disconnected()
5192
5193 @remote_compatible
5194 def test_ap_wps_encr_no_random_ap(dev, apdev):
5195 """WPS and no random data available for encryption on AP"""
5196 hapd = wps_start_ap(apdev[0])
5197 with fail_test(hapd, 1, "os_get_random;wps_build_encr_settings"):
5198 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5199
5200 @remote_compatible
5201 def test_ap_wps_e_hash_no_random_sta(dev, apdev):
5202 """WPS and no random data available for e-hash on STA"""
5203 with fail_test(dev[0], 1, "os_get_random;wps_build_e_hash"):
5204 wps_run_pbc_fail(apdev[0], dev[0])
5205
5206 @remote_compatible
5207 def test_ap_wps_m1_no_random(dev, apdev):
5208 """WPS and no random for M1 on STA"""
5209 with fail_test(dev[0], 1, "os_get_random;wps_build_m1"):
5210 wps_run_pbc_fail(apdev[0], dev[0])
5211
5212 @remote_compatible
5213 def test_ap_wps_m1_oom(dev, apdev):
5214 """WPS and OOM for M1 on STA"""
5215 with alloc_fail(dev[0], 1, "wps_build_m1"):
5216 wps_run_pbc_fail(apdev[0], dev[0])
5217
5218 @remote_compatible
5219 def test_ap_wps_m3_oom(dev, apdev):
5220 """WPS and OOM for M3 on STA"""
5221 with alloc_fail(dev[0], 1, "wps_build_m3"):
5222 wps_run_pbc_fail(apdev[0], dev[0])
5223
5224 @remote_compatible
5225 def test_ap_wps_m5_oom(dev, apdev):
5226 """WPS and OOM for M5 on STA"""
5227 hapd = wps_start_ap(apdev[0])
5228 hapd.request("WPS_PBC")
5229 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5230 for i in range(1, 3):
5231 with alloc_fail(dev[0], i, "wps_build_m5"):
5232 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5233 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5234 if ev is None:
5235 raise Exception("No EAP failure reported")
5236 dev[0].request("WPS_CANCEL")
5237 dev[0].wait_disconnected()
5238 dev[0].flush_scan_cache()
5239
5240 @remote_compatible
5241 def test_ap_wps_m5_no_random(dev, apdev):
5242 """WPS and no random for M5 on STA"""
5243 with fail_test(dev[0], 1,
5244 "os_get_random;wps_build_encr_settings;wps_build_m5"):
5245 wps_run_pbc_fail(apdev[0], dev[0])
5246
5247 @remote_compatible
5248 def test_ap_wps_m7_oom(dev, apdev):
5249 """WPS and OOM for M7 on STA"""
5250 hapd = wps_start_ap(apdev[0])
5251 hapd.request("WPS_PBC")
5252 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5253 for i in range(1, 3):
5254 with alloc_fail(dev[0], i, "wps_build_m7"):
5255 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5256 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5257 if ev is None:
5258 raise Exception("No EAP failure reported")
5259 dev[0].request("WPS_CANCEL")
5260 dev[0].wait_disconnected()
5261 dev[0].flush_scan_cache()
5262
5263 @remote_compatible
5264 def test_ap_wps_m7_no_random(dev, apdev):
5265 """WPS and no random for M7 on STA"""
5266 with fail_test(dev[0], 1,
5267 "os_get_random;wps_build_encr_settings;wps_build_m7"):
5268 wps_run_pbc_fail(apdev[0], dev[0])
5269
5270 @remote_compatible
5271 def test_ap_wps_wsc_done_oom(dev, apdev):
5272 """WPS and OOM for WSC_Done on STA"""
5273 with alloc_fail(dev[0], 1, "wps_build_wsc_done"):
5274 wps_run_pbc_fail(apdev[0], dev[0])
5275
5276 def test_ap_wps_random_psk_fail(dev, apdev):
5277 """WPS and no random for PSK on AP"""
5278 ssid = "test-wps"
5279 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
5280 appin = "12345670"
5281 try:
5282 os.remove(pskfile)
5283 except:
5284 pass
5285
5286 try:
5287 with open(pskfile, "w") as f:
5288 f.write("# WPA PSKs\n")
5289
5290 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5291 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
5292 "rsn_pairwise": "CCMP", "ap_pin": appin,
5293 "wpa_psk_file": pskfile}
5294 hapd = hostapd.add_ap(apdev[0], params)
5295
5296 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5297 with fail_test(hapd, 1, "os_get_random;wps_build_cred_network_key"):
5298 dev[0].request("WPS_REG " + apdev[0]['bssid'] + " " + appin)
5299 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5300 if ev is None:
5301 raise Exception("No EAP failure reported")
5302 dev[0].request("WPS_CANCEL")
5303 dev[0].wait_disconnected()
5304
5305 with fail_test(hapd, 1, "os_get_random;wps_build_cred"):
5306 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5307
5308 with alloc_fail(hapd, 1, "wps_build_cred"):
5309 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5310
5311 with alloc_fail(hapd, 2, "wps_build_cred"):
5312 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5313 finally:
5314 os.remove(pskfile)
5315
5316 def wps_ext_eap_identity_req(dev, hapd, bssid):
5317 logger.debug("EAP-Identity/Request")
5318 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5319 if ev is None:
5320 raise Exception("Timeout on EAPOL-TX from hostapd")
5321 res = dev.request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
5322 if "OK" not in res:
5323 raise Exception("EAPOL_RX to wpa_supplicant failed")
5324
5325 def wps_ext_eap_identity_resp(hapd, dev, addr):
5326 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
5327 if ev is None:
5328 raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
5329 res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
5330 if "OK" not in res:
5331 raise Exception("EAPOL_RX to hostapd failed")
5332
5333 def wps_ext_eap_wsc(dst, src, src_addr, msg):
5334 logger.debug(msg)
5335 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5336 if ev is None:
5337 raise Exception("Timeout on EAPOL-TX")
5338 res = dst.request("EAPOL_RX " + src_addr + " " + ev.split(' ')[2])
5339 if "OK" not in res:
5340 raise Exception("EAPOL_RX failed")
5341
5342 def wps_start_ext(apdev, dev, pbc=False, pin=None):
5343 addr = dev.own_addr()
5344 bssid = apdev['bssid']
5345 ssid = "test-wps-conf"
5346 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5347 "wpa_passphrase": "12345678", "wpa": "2",
5348 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
5349 hapd = hostapd.add_ap(apdev, params)
5350
5351 if pbc:
5352 hapd.request("WPS_PBC")
5353 else:
5354 if pin is None:
5355 pin = dev.wps_read_pin()
5356 hapd.request("WPS_PIN any " + pin)
5357 dev.scan_for_bss(bssid, freq="2412")
5358 hapd.request("SET ext_eapol_frame_io 1")
5359 dev.request("SET ext_eapol_frame_io 1")
5360
5361 if pbc:
5362 dev.request("WPS_PBC " + bssid)
5363 else:
5364 dev.request("WPS_PIN " + bssid + " " + pin)
5365 return addr, bssid, hapd
5366
5367 def wps_auth_corrupt(dst, src, addr):
5368 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5369 if ev is None:
5370 raise Exception("Timeout on EAPOL-TX")
5371 src.request("SET ext_eapol_frame_io 0")
5372 dst.request("SET ext_eapol_frame_io 0")
5373 msg = ev.split(' ')[2]
5374 if msg[-24:-16] != '10050008':
5375 raise Exception("Could not find Authenticator attribute")
5376 # Corrupt Authenticator value
5377 msg = msg[:-1] + '%x' % ((int(msg[-1], 16) + 1) % 16)
5378 res = dst.request("EAPOL_RX " + addr + " " + msg)
5379 if "OK" not in res:
5380 raise Exception("EAPOL_RX failed")
5381
5382 def wps_fail_finish(hapd, dev, fail_str):
5383 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5384 if ev is None:
5385 raise Exception("WPS-FAIL not indicated")
5386 if fail_str not in ev:
5387 raise Exception("Unexpected WPS-FAIL value: " + ev)
5388 dev.request("WPS_CANCEL")
5389 dev.wait_disconnected()
5390
5391 def wps_auth_corrupt_from_ap(dev, hapd, bssid, fail_str):
5392 wps_auth_corrupt(dev, hapd, bssid)
5393 wps_fail_finish(hapd, dev, fail_str)
5394
5395 def wps_auth_corrupt_to_ap(dev, hapd, addr, fail_str):
5396 wps_auth_corrupt(hapd, dev, addr)
5397 wps_fail_finish(hapd, dev, fail_str)
5398
5399 def test_ap_wps_authenticator_mismatch_m2(dev, apdev):
5400 """WPS and Authenticator attribute mismatch in M2"""
5401 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5402 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5403 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5404 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5405 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5406 logger.debug("M2")
5407 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=5")
5408
5409 def test_ap_wps_authenticator_mismatch_m3(dev, apdev):
5410 """WPS and Authenticator attribute mismatch in M3"""
5411 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5412 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5413 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5414 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5415 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5416 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5417 logger.debug("M3")
5418 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=7")
5419
5420 def test_ap_wps_authenticator_mismatch_m4(dev, apdev):
5421 """WPS and Authenticator attribute mismatch in M4"""
5422 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5423 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5424 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5425 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5426 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5427 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5428 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5429 logger.debug("M4")
5430 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=8")
5431
5432 def test_ap_wps_authenticator_mismatch_m5(dev, apdev):
5433 """WPS and Authenticator attribute mismatch in M5"""
5434 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5435 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5436 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5437 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5438 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5439 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5440 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5441 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5442 logger.debug("M5")
5443 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=9")
5444
5445 def test_ap_wps_authenticator_mismatch_m6(dev, apdev):
5446 """WPS and Authenticator attribute mismatch in M6"""
5447 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5448 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5449 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5450 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5451 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5452 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5453 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5454 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5455 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5456 logger.debug("M6")
5457 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=10")
5458
5459 def test_ap_wps_authenticator_mismatch_m7(dev, apdev):
5460 """WPS and Authenticator attribute mismatch in M7"""
5461 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5462 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5463 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5464 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5465 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5466 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5467 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5468 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5469 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5470 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5471 logger.debug("M7")
5472 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=11")
5473
5474 def test_ap_wps_authenticator_mismatch_m8(dev, apdev):
5475 """WPS and Authenticator attribute mismatch in M8"""
5476 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5477 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5478 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5479 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5480 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5481 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5482 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5483 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5484 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5485 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5486 wps_ext_eap_wsc(hapd, dev[0], addr, "M7")
5487 logger.debug("M8")
5488 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=12")
5489
5490 def test_ap_wps_authenticator_missing_m2(dev, apdev):
5491 """WPS and Authenticator attribute missing from M2"""
5492 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5493 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5494 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5495 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5496 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5497 logger.debug("M2")
5498 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5499 if ev is None:
5500 raise Exception("Timeout on EAPOL-TX")
5501 hapd.request("SET ext_eapol_frame_io 0")
5502 dev[0].request("SET ext_eapol_frame_io 0")
5503 msg = ev.split(' ')[2]
5504 if msg[-24:-16] != '10050008':
5505 raise Exception("Could not find Authenticator attribute")
5506 # Remove Authenticator value
5507 msg = msg[:-24]
5508 mlen = "%04x" % (int(msg[4:8], 16) - 12)
5509 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:]
5510 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5511 if "OK" not in res:
5512 raise Exception("EAPOL_RX failed")
5513 wps_fail_finish(hapd, dev[0], "msg=5")
5514
5515 def test_ap_wps_m2_dev_passwd_id_p2p(dev, apdev):
5516 """WPS and M2 with different Device Password ID (P2P)"""
5517 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5518 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5519 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5520 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5521 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5522 logger.debug("M2")
5523 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5524 if ev is None:
5525 raise Exception("Timeout on EAPOL-TX")
5526 hapd.request("SET ext_eapol_frame_io 0")
5527 dev[0].request("SET ext_eapol_frame_io 0")
5528 msg = ev.split(' ')[2]
5529 if msg[722:730] != '10120002':
5530 raise Exception("Could not find Device Password ID attribute")
5531 # Replace Device Password ID value. This will fail Authenticator check, but
5532 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5533 # log.
5534 msg = msg[0:730] + "0005" + msg[734:]
5535 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5536 if "OK" not in res:
5537 raise Exception("EAPOL_RX failed")
5538 wps_fail_finish(hapd, dev[0], "msg=5")
5539
5540 def test_ap_wps_m2_dev_passwd_id_change_pin_to_pbc(dev, apdev):
5541 """WPS and M2 with different Device Password ID (PIN to PBC)"""
5542 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5543 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5544 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5545 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5546 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5547 logger.debug("M2")
5548 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5549 if ev is None:
5550 raise Exception("Timeout on EAPOL-TX")
5551 hapd.request("SET ext_eapol_frame_io 0")
5552 dev[0].request("SET ext_eapol_frame_io 0")
5553 msg = ev.split(' ')[2]
5554 if msg[722:730] != '10120002':
5555 raise Exception("Could not find Device Password ID attribute")
5556 # Replace Device Password ID value (PIN --> PBC). This will be rejected.
5557 msg = msg[0:730] + "0004" + msg[734:]
5558 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5559 if "OK" not in res:
5560 raise Exception("EAPOL_RX failed")
5561 wps_fail_finish(hapd, dev[0], "msg=5")
5562
5563 def test_ap_wps_m2_dev_passwd_id_change_pbc_to_pin(dev, apdev):
5564 """WPS and M2 with different Device Password ID (PBC to PIN)"""
5565 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5566 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5567 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5568 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5569 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5570 logger.debug("M2")
5571 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5572 if ev is None:
5573 raise Exception("Timeout on EAPOL-TX")
5574 hapd.request("SET ext_eapol_frame_io 0")
5575 dev[0].request("SET ext_eapol_frame_io 0")
5576 msg = ev.split(' ')[2]
5577 if msg[722:730] != '10120002':
5578 raise Exception("Could not find Device Password ID attribute")
5579 # Replace Device Password ID value. This will fail Authenticator check, but
5580 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5581 # log.
5582 msg = msg[0:730] + "0000" + msg[734:]
5583 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5584 if "OK" not in res:
5585 raise Exception("EAPOL_RX failed")
5586 wps_fail_finish(hapd, dev[0], "msg=5")
5587 dev[0].flush_scan_cache()
5588
5589 def test_ap_wps_m2_missing_dev_passwd_id(dev, apdev):
5590 """WPS and M2 without Device Password ID"""
5591 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5592 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5593 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5594 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5595 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5596 logger.debug("M2")
5597 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5598 if ev is None:
5599 raise Exception("Timeout on EAPOL-TX")
5600 hapd.request("SET ext_eapol_frame_io 0")
5601 dev[0].request("SET ext_eapol_frame_io 0")
5602 msg = ev.split(' ')[2]
5603 if msg[722:730] != '10120002':
5604 raise Exception("Could not find Device Password ID attribute")
5605 # Remove Device Password ID value. This will fail Authenticator check, but
5606 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5607 # log.
5608 mlen = "%04x" % (int(msg[4:8], 16) - 6)
5609 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:722] + msg[734:]
5610 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5611 if "OK" not in res:
5612 raise Exception("EAPOL_RX failed")
5613 wps_fail_finish(hapd, dev[0], "msg=5")
5614
5615 def test_ap_wps_m2_missing_registrar_nonce(dev, apdev):
5616 """WPS and M2 without Registrar Nonce"""
5617 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5618 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5619 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5620 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5621 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5622 logger.debug("M2")
5623 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5624 if ev is None:
5625 raise Exception("Timeout on EAPOL-TX")
5626 hapd.request("SET ext_eapol_frame_io 0")
5627 dev[0].request("SET ext_eapol_frame_io 0")
5628 msg = ev.split(' ')[2]
5629 if msg[96:104] != '10390010':
5630 raise Exception("Could not find Registrar Nonce attribute")
5631 # Remove Registrar Nonce. This will fail Authenticator check, but
5632 # allows the code path in wps_process_registrar_nonce() to be checked from
5633 # the debug log.
5634 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5635 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:96] + msg[136:]
5636 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5637 if "OK" not in res:
5638 raise Exception("EAPOL_RX failed")
5639 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5640 if ev is None:
5641 raise Exception("Disconnect event not seen")
5642 dev[0].request("WPS_CANCEL")
5643 dev[0].flush_scan_cache()
5644
5645 def test_ap_wps_m2_missing_enrollee_nonce(dev, apdev):
5646 """WPS and M2 without Enrollee Nonce"""
5647 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5648 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5649 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5650 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5651 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5652 logger.debug("M2")
5653 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5654 if ev is None:
5655 raise Exception("Timeout on EAPOL-TX")
5656 hapd.request("SET ext_eapol_frame_io 0")
5657 dev[0].request("SET ext_eapol_frame_io 0")
5658 msg = ev.split(' ')[2]
5659 if msg[56:64] != '101a0010':
5660 raise Exception("Could not find enrollee Nonce attribute")
5661 # Remove Enrollee Nonce. This will fail Authenticator check, but
5662 # allows the code path in wps_process_enrollee_nonce() to be checked from
5663 # the debug log.
5664 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5665 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:56] + msg[96:]
5666 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5667 if "OK" not in res:
5668 raise Exception("EAPOL_RX failed")
5669 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5670 if ev is None:
5671 raise Exception("Disconnect event not seen")
5672 dev[0].request("WPS_CANCEL")
5673 dev[0].flush_scan_cache()
5674
5675 def test_ap_wps_m2_missing_uuid_r(dev, apdev):
5676 """WPS and M2 without UUID-R"""
5677 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5678 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5679 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5680 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5681 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5682 logger.debug("M2")
5683 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5684 if ev is None:
5685 raise Exception("Timeout on EAPOL-TX")
5686 hapd.request("SET ext_eapol_frame_io 0")
5687 dev[0].request("SET ext_eapol_frame_io 0")
5688 msg = ev.split(' ')[2]
5689 if msg[136:144] != '10480010':
5690 raise Exception("Could not find enrollee Nonce attribute")
5691 # Remove UUID-R. This will fail Authenticator check, but allows the code
5692 # path in wps_process_uuid_r() to be checked from the debug log.
5693 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5694 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:136] + msg[176:]
5695 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5696 if "OK" not in res:
5697 raise Exception("EAPOL_RX failed")
5698 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5699 if ev is None:
5700 raise Exception("Disconnect event not seen")
5701 dev[0].request("WPS_CANCEL")
5702 dev[0].flush_scan_cache()
5703
5704 def test_ap_wps_m2_invalid(dev, apdev):
5705 """WPS and M2 parsing failure"""
5706 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5707 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5708 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5709 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5710 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5711 logger.debug("M2")
5712 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5713 if ev is None:
5714 raise Exception("Timeout on EAPOL-TX")
5715 hapd.request("SET ext_eapol_frame_io 0")
5716 dev[0].request("SET ext_eapol_frame_io 0")
5717 msg = ev.split(' ')[2]
5718 if msg[136:144] != '10480010':
5719 raise Exception("Could not find enrollee Nonce attribute")
5720 # Remove UUID-R. This will fail Authenticator check, but allows the code
5721 # path in wps_process_uuid_r() to be checked from the debug log.
5722 mlen = "%04x" % (int(msg[4:8], 16) - 1)
5723 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:-2]
5724 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5725 if "OK" not in res:
5726 raise Exception("EAPOL_RX failed")
5727 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5728 if ev is None:
5729 raise Exception("Disconnect event not seen")
5730 dev[0].request("WPS_CANCEL")
5731 dev[0].flush_scan_cache()
5732
5733 def test_ap_wps_m2_missing_msg_type(dev, apdev):
5734 """WPS and M2 without Message Type"""
5735 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5736 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5737 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5738 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5739 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5740 logger.debug("M2")
5741 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5742 if ev is None:
5743 raise Exception("Timeout on EAPOL-TX")
5744 hapd.request("SET ext_eapol_frame_io 0")
5745 dev[0].request("SET ext_eapol_frame_io 0")
5746 msg = ev.split(' ')[2]
5747 if msg[46:54] != '10220001':
5748 raise Exception("Could not find Message Type attribute")
5749 # Remove Message Type. This will fail Authenticator check, but allows the
5750 # code path in wps_process_wsc_msg() to be checked from the debug log.
5751 mlen = "%04x" % (int(msg[4:8], 16) - 5)
5752 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:46] + msg[56:]
5753 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5754 if "OK" not in res:
5755 raise Exception("EAPOL_RX failed")
5756 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5757 if ev is None:
5758 raise Exception("Disconnect event not seen")
5759 dev[0].request("WPS_CANCEL")
5760 dev[0].flush_scan_cache()
5761
5762 def test_ap_wps_m2_unknown_msg_type(dev, apdev):
5763 """WPS and M2 but unknown Message Type"""
5764 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5765 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5766 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5767 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5768 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5769 logger.debug("M2")
5770 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5771 if ev is None:
5772 raise Exception("Timeout on EAPOL-TX")
5773 hapd.request("SET ext_eapol_frame_io 0")
5774 dev[0].request("SET ext_eapol_frame_io 0")
5775 msg = ev.split(' ')[2]
5776 if msg[46:54] != '10220001':
5777 raise Exception("Could not find Message Type attribute")
5778 # Replace Message Type value. This will be rejected.
5779 msg = msg[0:54] + "00" + msg[56:]
5780 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5781 if "OK" not in res:
5782 raise Exception("EAPOL_RX failed")
5783 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5784 if ev is None:
5785 raise Exception("Disconnect event not seen")
5786 dev[0].request("WPS_CANCEL")
5787 dev[0].flush_scan_cache()
5788
5789 def test_ap_wps_m2_unknown_opcode(dev, apdev):
5790 """WPS and M2 but unknown opcode"""
5791 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5792 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5793 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5794 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5795 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5796 logger.debug("M2")
5797 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5798 if ev is None:
5799 raise Exception("Timeout on EAPOL-TX")
5800 hapd.request("SET ext_eapol_frame_io 0")
5801 dev[0].request("SET ext_eapol_frame_io 0")
5802 msg = ev.split(' ')[2]
5803 # Replace opcode. This will be discarded in EAP-WSC processing.
5804 msg = msg[0:32] + "00" + msg[34:]
5805 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5806 if "OK" not in res:
5807 raise Exception("EAPOL_RX failed")
5808 dev[0].request("WPS_CANCEL")
5809 dev[0].wait_disconnected()
5810 dev[0].flush_scan_cache()
5811
5812 def test_ap_wps_m2_unknown_opcode2(dev, apdev):
5813 """WPS and M2 but unknown opcode (WSC_Start)"""
5814 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5815 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5816 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5817 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5818 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5819 logger.debug("M2")
5820 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5821 if ev is None:
5822 raise Exception("Timeout on EAPOL-TX")
5823 hapd.request("SET ext_eapol_frame_io 0")
5824 dev[0].request("SET ext_eapol_frame_io 0")
5825 msg = ev.split(' ')[2]
5826 # Replace opcode. This will be discarded in EAP-WSC processing.
5827 msg = msg[0:32] + "01" + msg[34:]
5828 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5829 if "OK" not in res:
5830 raise Exception("EAPOL_RX failed")
5831 dev[0].request("WPS_CANCEL")
5832 dev[0].wait_disconnected()
5833 dev[0].flush_scan_cache()
5834
5835 def test_ap_wps_m2_unknown_opcode3(dev, apdev):
5836 """WPS and M2 but unknown opcode (WSC_Done)"""
5837 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5838 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5839 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5840 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5841 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5842 logger.debug("M2")
5843 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5844 if ev is None:
5845 raise Exception("Timeout on EAPOL-TX")
5846 hapd.request("SET ext_eapol_frame_io 0")
5847 dev[0].request("SET ext_eapol_frame_io 0")
5848 msg = ev.split(' ')[2]
5849 # Replace opcode. This will be discarded in WPS Enrollee processing.
5850 msg = msg[0:32] + "05" + msg[34:]
5851 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5852 if "OK" not in res:
5853 raise Exception("EAPOL_RX failed")
5854 dev[0].request("WPS_CANCEL")
5855 dev[0].wait_disconnected()
5856 dev[0].flush_scan_cache()
5857
5858 def wps_m2_but_other(dev, apdev, title, msgtype):
5859 addr, bssid, hapd = wps_start_ext(apdev, dev)
5860 wps_ext_eap_identity_req(dev, hapd, bssid)
5861 wps_ext_eap_identity_resp(hapd, dev, addr)
5862 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5863 wps_ext_eap_wsc(hapd, dev, addr, "M1")
5864 logger.debug(title)
5865 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5866 if ev is None:
5867 raise Exception("Timeout on EAPOL-TX")
5868 hapd.request("SET ext_eapol_frame_io 0")
5869 dev.request("SET ext_eapol_frame_io 0")
5870 msg = ev.split(' ')[2]
5871 if msg[46:54] != '10220001':
5872 raise Exception("Could not find Message Type attribute")
5873 # Replace Message Type value. This will be rejected.
5874 msg = msg[0:54] + msgtype + msg[56:]
5875 res = dev.request("EAPOL_RX " + bssid + " " + msg)
5876 if "OK" not in res:
5877 raise Exception("EAPOL_RX failed")
5878 ev = dev.wait_event(["WPS-FAIL"], timeout=5)
5879 if ev is None:
5880 raise Exception("WPS-FAIL event not seen")
5881 dev.request("WPS_CANCEL")
5882 dev.wait_disconnected()
5883
5884 def wps_m4_but_other(dev, apdev, title, msgtype):
5885 addr, bssid, hapd = wps_start_ext(apdev, dev)
5886 wps_ext_eap_identity_req(dev, hapd, bssid)
5887 wps_ext_eap_identity_resp(hapd, dev, addr)
5888 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5889 wps_ext_eap_wsc(hapd, dev, addr, "M1")
5890 wps_ext_eap_wsc(dev, hapd, bssid, "M2")
5891 wps_ext_eap_wsc(hapd, dev, addr, "M3")
5892 logger.debug(title)
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.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] + msgtype + msg[56:]
5903 res = dev.request("EAPOL_RX " + bssid + " " + msg)
5904 if "OK" not in res:
5905 raise Exception("EAPOL_RX failed")
5906 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5907 if ev is None:
5908 raise Exception("WPS-FAIL event not seen")
5909 dev.request("WPS_CANCEL")
5910 dev.wait_disconnected()
5911
5912 def test_ap_wps_m2_msg_type_m4(dev, apdev):
5913 """WPS and M2 but Message Type M4"""
5914 wps_m2_but_other(dev[0], apdev[0], "M2/M4", "08")
5915
5916 def test_ap_wps_m2_msg_type_m6(dev, apdev):
5917 """WPS and M2 but Message Type M6"""
5918 wps_m2_but_other(dev[0], apdev[0], "M2/M6", "0a")
5919
5920 def test_ap_wps_m2_msg_type_m8(dev, apdev):
5921 """WPS and M2 but Message Type M8"""
5922 wps_m2_but_other(dev[0], apdev[0], "M2/M8", "0c")
5923
5924 def test_ap_wps_m4_msg_type_m2(dev, apdev):
5925 """WPS and M4 but Message Type M2"""
5926 wps_m4_but_other(dev[0], apdev[0], "M4/M2", "05")
5927
5928 def test_ap_wps_m4_msg_type_m2d(dev, apdev):
5929 """WPS and M4 but Message Type M2D"""
5930 wps_m4_but_other(dev[0], apdev[0], "M4/M2D", "06")
5931
5932 @remote_compatible
5933 def test_ap_wps_config_methods(dev, apdev):
5934 """WPS configuration method parsing"""
5935 ssid = "test-wps-conf"
5936 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5937 "wpa_passphrase": "12345678", "wpa": "2",
5938 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5939 "config_methods": "ethernet display ext_nfc_token int_nfc_token physical_display physical_push_button"}
5940 hapd = hostapd.add_ap(apdev[0], params)
5941 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5942 "wpa_passphrase": "12345678", "wpa": "2",
5943 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5944 "config_methods": "display push_button"}
5945 hapd2 = hostapd.add_ap(apdev[1], params)
5946
5947 def test_ap_wps_set_selected_registrar_proto(dev, apdev):
5948 """WPS UPnP SetSelectedRegistrar protocol testing"""
5949 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
5950 hapd = add_ssdp_ap(apdev[0], ap_uuid)
5951
5952 location = ssdp_get_location(ap_uuid)
5953 urls = upnp_get_urls(location)
5954 eventurl = urlparse(urls['event_sub_url'])
5955 ctrlurl = urlparse(urls['control_url'])
5956 url = urlparse(location)
5957 conn = HTTPConnection(url.netloc)
5958
5959 class WPSERHTTPServer(StreamRequestHandler):
5960 def handle(self):
5961 data = self.rfile.readline().strip()
5962 logger.debug(data)
5963 self.wfile.write(gen_wps_event())
5964
5965 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
5966 server.timeout = 1
5967
5968 headers = {"callback": '<http://127.0.0.1:12345/event>',
5969 "NT": "upnp:event",
5970 "timeout": "Second-1234"}
5971 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
5972 resp = conn.getresponse()
5973 if resp.status != 200:
5974 raise Exception("Unexpected HTTP response: %d" % resp.status)
5975 sid = resp.getheader("sid")
5976 logger.debug("Subscription SID " + sid)
5977 server.handle_request()
5978
5979 tests = [(500, "10"),
5980 (200, "104a000110" + "1041000101" + "101200020000" +
5981 "105300023148" +
5982 "1049002c00372a0001200124111111111111222222222222333333333333444444444444555555555555666666666666" +
5983 "10480010362db47ba53a519188fb5458b986b2e4"),
5984 (200, "104a000110" + "1041000100" + "101200020000" +
5985 "105300020000"),
5986 (200, "104a000110" + "1041000100"),
5987 (200, "104a000110")]
5988 for status, test in tests:
5989 tlvs = binascii.unhexlify(test)
5990 newmsg = base64.b64encode(tlvs).decode()
5991 msg = '<?xml version="1.0"?>\n'
5992 msg += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
5993 msg += '<s:Body>'
5994 msg += '<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">'
5995 msg += '<NewMessage>'
5996 msg += newmsg
5997 msg += "</NewMessage></u:SetSelectedRegistrar></s:Body></s:Envelope>"
5998 headers = {"Content-type": 'text/xml; charset="utf-8"'}
5999 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
6000 conn.request("POST", ctrlurl.path, msg, headers)
6001 resp = conn.getresponse()
6002 if resp.status != status:
6003 raise Exception("Unexpected HTTP response: %d (expected %d)" % (resp.status, status))
6004
6005 def test_ap_wps_adv_oom(dev, apdev):
6006 """WPS AP and advertisement OOM"""
6007 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
6008 hapd = add_ssdp_ap(apdev[0], ap_uuid)
6009
6010 with alloc_fail(hapd, 1, "=msearchreply_state_machine_start"):
6011 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
6012 no_recv=True)
6013 time.sleep(0.2)
6014
6015 with alloc_fail(hapd, 1, "eloop_register_timeout;msearchreply_state_machine_start"):
6016 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
6017 no_recv=True)
6018 time.sleep(0.2)
6019
6020 with alloc_fail(hapd, 1,
6021 "next_advertisement;advertisement_state_machine_stop"):
6022 hapd.disable()
6023
6024 with alloc_fail(hapd, 1, "ssdp_listener_start"):
6025 if "FAIL" not in hapd.request("ENABLE"):
6026 raise Exception("ENABLE succeeded during OOM")
6027
6028 def test_wps_config_methods(dev):
6029 """WPS config method update"""
6030 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
6031 wpas.interface_add("wlan5")
6032 if "OK" not in wpas.request("SET config_methods display label"):
6033 raise Exception("Failed to set config_methods")
6034 if wpas.request("GET config_methods").strip() != "display label":
6035 raise Exception("config_methods were not updated")
6036 if "OK" not in wpas.request("SET config_methods "):
6037 raise Exception("Failed to clear config_methods")
6038 if wpas.request("GET config_methods").strip() != "":
6039 raise Exception("config_methods were not cleared")
6040
6041 WPS_VENDOR_ID_WFA = 14122
6042 WPS_VENDOR_TYPE = 1
6043
6044 # EAP-WSC Op-Code values
6045 WSC_Start = 0x01
6046 WSC_ACK = 0x02
6047 WSC_NACK = 0x03
6048 WSC_MSG = 0x04
6049 WSC_Done = 0x05
6050 WSC_FRAG_ACK = 0x06
6051
6052 ATTR_AP_CHANNEL = 0x1001
6053 ATTR_ASSOC_STATE = 0x1002
6054 ATTR_AUTH_TYPE = 0x1003
6055 ATTR_AUTH_TYPE_FLAGS = 0x1004
6056 ATTR_AUTHENTICATOR = 0x1005
6057 ATTR_CONFIG_METHODS = 0x1008
6058 ATTR_CONFIG_ERROR = 0x1009
6059 ATTR_CONFIRM_URL4 = 0x100a
6060 ATTR_CONFIRM_URL6 = 0x100b
6061 ATTR_CONN_TYPE = 0x100c
6062 ATTR_CONN_TYPE_FLAGS = 0x100d
6063 ATTR_CRED = 0x100e
6064 ATTR_ENCR_TYPE = 0x100f
6065 ATTR_ENCR_TYPE_FLAGS = 0x1010
6066 ATTR_DEV_NAME = 0x1011
6067 ATTR_DEV_PASSWORD_ID = 0x1012
6068 ATTR_E_HASH1 = 0x1014
6069 ATTR_E_HASH2 = 0x1015
6070 ATTR_E_SNONCE1 = 0x1016
6071 ATTR_E_SNONCE2 = 0x1017
6072 ATTR_ENCR_SETTINGS = 0x1018
6073 ATTR_ENROLLEE_NONCE = 0x101a
6074 ATTR_FEATURE_ID = 0x101b
6075 ATTR_IDENTITY = 0x101c
6076 ATTR_IDENTITY_PROOF = 0x101d
6077 ATTR_KEY_WRAP_AUTH = 0x101e
6078 ATTR_KEY_ID = 0x101f
6079 ATTR_MAC_ADDR = 0x1020
6080 ATTR_MANUFACTURER = 0x1021
6081 ATTR_MSG_TYPE = 0x1022
6082 ATTR_MODEL_NAME = 0x1023
6083 ATTR_MODEL_NUMBER = 0x1024
6084 ATTR_NETWORK_INDEX = 0x1026
6085 ATTR_NETWORK_KEY = 0x1027
6086 ATTR_NETWORK_KEY_INDEX = 0x1028
6087 ATTR_NEW_DEVICE_NAME = 0x1029
6088 ATTR_NEW_PASSWORD = 0x102a
6089 ATTR_OOB_DEVICE_PASSWORD = 0x102c
6090 ATTR_OS_VERSION = 0x102d
6091 ATTR_POWER_LEVEL = 0x102f
6092 ATTR_PSK_CURRENT = 0x1030
6093 ATTR_PSK_MAX = 0x1031
6094 ATTR_PUBLIC_KEY = 0x1032
6095 ATTR_RADIO_ENABLE = 0x1033
6096 ATTR_REBOOT = 0x1034
6097 ATTR_REGISTRAR_CURRENT = 0x1035
6098 ATTR_REGISTRAR_ESTABLISHED = 0x1036
6099 ATTR_REGISTRAR_LIST = 0x1037
6100 ATTR_REGISTRAR_MAX = 0x1038
6101 ATTR_REGISTRAR_NONCE = 0x1039
6102 ATTR_REQUEST_TYPE = 0x103a
6103 ATTR_RESPONSE_TYPE = 0x103b
6104 ATTR_RF_BANDS = 0x103c
6105 ATTR_R_HASH1 = 0x103d
6106 ATTR_R_HASH2 = 0x103e
6107 ATTR_R_SNONCE1 = 0x103f
6108 ATTR_R_SNONCE2 = 0x1040
6109 ATTR_SELECTED_REGISTRAR = 0x1041
6110 ATTR_SERIAL_NUMBER = 0x1042
6111 ATTR_WPS_STATE = 0x1044
6112 ATTR_SSID = 0x1045
6113 ATTR_TOTAL_NETWORKS = 0x1046
6114 ATTR_UUID_E = 0x1047
6115 ATTR_UUID_R = 0x1048
6116 ATTR_VENDOR_EXT = 0x1049
6117 ATTR_VERSION = 0x104a
6118 ATTR_X509_CERT_REQ = 0x104b
6119 ATTR_X509_CERT = 0x104c
6120 ATTR_EAP_IDENTITY = 0x104d
6121 ATTR_MSG_COUNTER = 0x104e
6122 ATTR_PUBKEY_HASH = 0x104f
6123 ATTR_REKEY_KEY = 0x1050
6124 ATTR_KEY_LIFETIME = 0x1051
6125 ATTR_PERMITTED_CFG_METHODS = 0x1052
6126 ATTR_SELECTED_REGISTRAR_CONFIG_METHODS = 0x1053
6127 ATTR_PRIMARY_DEV_TYPE = 0x1054
6128 ATTR_SECONDARY_DEV_TYPE_LIST = 0x1055
6129 ATTR_PORTABLE_DEV = 0x1056
6130 ATTR_AP_SETUP_LOCKED = 0x1057
6131 ATTR_APPLICATION_EXT = 0x1058
6132 ATTR_EAP_TYPE = 0x1059
6133 ATTR_IV = 0x1060
6134 ATTR_KEY_PROVIDED_AUTO = 0x1061
6135 ATTR_802_1X_ENABLED = 0x1062
6136 ATTR_APPSESSIONKEY = 0x1063
6137 ATTR_WEPTRANSMITKEY = 0x1064
6138 ATTR_REQUESTED_DEV_TYPE = 0x106a
6139
6140 # Message Type
6141 WPS_Beacon = 0x01
6142 WPS_ProbeRequest = 0x02
6143 WPS_ProbeResponse = 0x03
6144 WPS_M1 = 0x04
6145 WPS_M2 = 0x05
6146 WPS_M2D = 0x06
6147 WPS_M3 = 0x07
6148 WPS_M4 = 0x08
6149 WPS_M5 = 0x09
6150 WPS_M6 = 0x0a
6151 WPS_M7 = 0x0b
6152 WPS_M8 = 0x0c
6153 WPS_WSC_ACK = 0x0d
6154 WPS_WSC_NACK = 0x0e
6155 WPS_WSC_DONE = 0x0f
6156
6157 def get_wsc_msg(dev):
6158 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
6159 if ev is None:
6160 raise Exception("Timeout on EAPOL-TX")
6161 data = binascii.unhexlify(ev.split(' ')[2])
6162 msg = {}
6163
6164 # Parse EAPOL header
6165 if len(data) < 4:
6166 raise Exception("No room for EAPOL header")
6167 version, type, length = struct.unpack('>BBH', data[0:4])
6168 msg['eapol_version'] = version
6169 msg['eapol_type'] = type
6170 msg['eapol_length'] = length
6171 data = data[4:]
6172 if length != len(data):
6173 raise Exception("EAPOL header length mismatch (%d != %d)" % (length, len(data)))
6174 if type != 0:
6175 raise Exception("Unexpected EAPOL header type: %d" % type)
6176
6177 # Parse EAP header
6178 if len(data) < 4:
6179 raise Exception("No room for EAP header")
6180 code, identifier, length = struct.unpack('>BBH', data[0:4])
6181 msg['eap_code'] = code
6182 msg['eap_identifier'] = identifier
6183 msg['eap_length'] = length
6184 data = data[4:]
6185 if msg['eapol_length'] != msg['eap_length']:
6186 raise Exception("EAP header length mismatch (%d != %d)" % (msg['eapol_length'], length))
6187
6188 # Parse EAP expanded header
6189 if len(data) < 1:
6190 raise Exception("No EAP type included")
6191 msg['eap_type'], = struct.unpack('B', data[0:1])
6192 data = data[1:]
6193
6194 if msg['eap_type'] == 254:
6195 if len(data) < 3 + 4:
6196 raise Exception("Truncated EAP expanded header")
6197 msg['eap_vendor_id'], msg['eap_vendor_type'] = struct.unpack('>LL', b'\x00' + data[0:7])
6198 data = data[7:]
6199 else:
6200 raise Exception("Unexpected EAP type")
6201
6202 if msg['eap_vendor_id'] != WPS_VENDOR_ID_WFA:
6203 raise Exception("Unexpected Vendor-Id")
6204 if msg['eap_vendor_type'] != WPS_VENDOR_TYPE:
6205 raise Exception("Unexpected Vendor-Type")
6206
6207 # Parse EAP-WSC header
6208 if len(data) < 2:
6209 raise Exception("Truncated EAP-WSC header")
6210 msg['wsc_opcode'], msg['wsc_flags'] = struct.unpack('BB', data[0:2])
6211 data = data[2:]
6212
6213 # Parse WSC attributes
6214 msg['raw_attrs'] = data
6215 attrs = {}
6216 while len(data) > 0:
6217 if len(data) < 4:
6218 raise Exception("Truncated attribute header")
6219 attr, length = struct.unpack('>HH', data[0:4])
6220 data = data[4:]
6221 if length > len(data):
6222 raise Exception("Truncated attribute 0x%04x" % attr)
6223 attrs[attr] = data[0:length]
6224 data = data[length:]
6225 msg['wsc_attrs'] = attrs
6226
6227 if ATTR_MSG_TYPE in attrs:
6228 msg['wsc_msg_type'], = struct.unpack('B', attrs[ATTR_MSG_TYPE])
6229
6230 return msg
6231
6232 def recv_wsc_msg(dev, opcode, msg_type):
6233 msg = get_wsc_msg(dev)
6234 if msg['wsc_opcode'] != opcode or msg['wsc_msg_type'] != msg_type:
6235 raise Exception("Unexpected Op-Code/MsgType")
6236 return msg, msg['wsc_attrs'], msg['raw_attrs']
6237
6238 def build_wsc_attr(attr, payload):
6239 _payload = payload if type(payload) == bytes else payload.encode()
6240 return struct.pack('>HH', attr, len(_payload)) + _payload
6241
6242 def build_attr_msg_type(msg_type):
6243 return build_wsc_attr(ATTR_MSG_TYPE, struct.pack('B', msg_type))
6244
6245 def build_eap_wsc(eap_code, eap_id, payload, opcode=WSC_MSG):
6246 length = 4 + 8 + 2 + len(payload)
6247 # EAPOL header
6248 msg = struct.pack('>BBH', 2, 0, length)
6249 # EAP header
6250 msg += struct.pack('>BBH', eap_code, eap_id, length)
6251 # EAP expanded header for EAP-WSC
6252 msg += struct.pack('B', 254)
6253 msg += struct.pack('>L', WPS_VENDOR_ID_WFA)[1:4]
6254 msg += struct.pack('>L', WPS_VENDOR_TYPE)
6255 # EAP-WSC header
6256 msg += struct.pack('BB', opcode, 0)
6257 # WSC attributes
6258 msg += payload
6259 return msg
6260
6261 def build_eap_success(eap_id):
6262 length = 4
6263 # EAPOL header
6264 msg = struct.pack('>BBH', 2, 0, length)
6265 # EAP header
6266 msg += struct.pack('>BBH', 3, eap_id, length)
6267 return msg
6268
6269 def build_eap_failure(eap_id):
6270 length = 4
6271 # EAPOL header
6272 msg = struct.pack('>BBH', 2, 0, length)
6273 # EAP header
6274 msg += struct.pack('>BBH', 4, eap_id, length)
6275 return msg
6276
6277 def send_wsc_msg(dev, src, msg):
6278 res = dev.request("EAPOL_RX " + src + " " + binascii.hexlify(msg).decode())
6279 if "OK" not in res:
6280 raise Exception("EAPOL_RX failed")
6281
6282 group_5_prime = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF
6283 group_5_generator = 2
6284
6285 def wsc_kdf(key, label, bits):
6286 result = b''
6287 i = 1
6288 while len(result) * 8 < bits:
6289 data = struct.pack('>L', i) + label.encode() + struct.pack('>L', bits)
6290 m = hmac.new(key, data, hashlib.sha256)
6291 result += m.digest()
6292 i += 1
6293 return result[0:bits // 8]
6294
6295 def wsc_keys(kdk):
6296 keys = wsc_kdf(kdk, "Wi-Fi Easy and Secure Key Derivation", 640)
6297 authkey = keys[0:32]
6298 keywrapkey = keys[32:48]
6299 emsk = keys[48:80]
6300 return authkey, keywrapkey, emsk
6301
6302 def wsc_dev_pw_half_psk(authkey, dev_pw):
6303 m = hmac.new(authkey, dev_pw.encode(), hashlib.sha256)
6304 return m.digest()[0:16]
6305
6306 def wsc_dev_pw_psk(authkey, dev_pw):
6307 dev_pw_1 = dev_pw[0:len(dev_pw) // 2]
6308 dev_pw_2 = dev_pw[len(dev_pw) // 2:]
6309 psk1 = wsc_dev_pw_half_psk(authkey, dev_pw_1)
6310 psk2 = wsc_dev_pw_half_psk(authkey, dev_pw_2)
6311 return psk1, psk2
6312
6313 def build_attr_authenticator(authkey, prev_msg, curr_msg):
6314 m = hmac.new(authkey, prev_msg + curr_msg, hashlib.sha256)
6315 auth = m.digest()[0:8]
6316 return build_wsc_attr(ATTR_AUTHENTICATOR, auth)
6317
6318 def build_attr_encr_settings(authkey, keywrapkey, data):
6319 m = hmac.new(authkey, data, hashlib.sha256)
6320 kwa = m.digest()[0:8]
6321 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6322 iv = 16*b'\x99'
6323 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6324 pad_len = 16 - len(data) % 16
6325 ps = pad_len * struct.pack('B', pad_len)
6326 data += ps
6327 wrapped = aes.encrypt(data)
6328 return build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6329
6330 def decrypt_attr_encr_settings(authkey, keywrapkey, data):
6331 if len(data) < 32 or len(data) % 16 != 0:
6332 raise Exception("Unexpected Encrypted Settings length: %d" % len(data))
6333 iv = data[0:16]
6334 encr = data[16:]
6335 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6336 decrypted = aes.decrypt(encr)
6337 pad_len, = struct.unpack('B', decrypted[-1:])
6338 if pad_len > len(decrypted):
6339 raise Exception("Invalid padding in Encrypted Settings")
6340 for i in range(-pad_len, -1):
6341 if decrypted[i] != decrypted[-1]:
6342 raise Exception("Invalid PS value in Encrypted Settings")
6343
6344 decrypted = decrypted[0:len(decrypted) - pad_len]
6345 if len(decrypted) < 12:
6346 raise Exception("Truncated Encrypted Settings plaintext")
6347 kwa = decrypted[-12:]
6348 attr, length = struct.unpack(">HH", kwa[0:4])
6349 if attr != ATTR_KEY_WRAP_AUTH or length != 8:
6350 raise Exception("Invalid KWA header")
6351 kwa = kwa[4:]
6352 decrypted = decrypted[0:len(decrypted) - 12]
6353
6354 m = hmac.new(authkey, decrypted, hashlib.sha256)
6355 calc_kwa = m.digest()[0:8]
6356 if kwa != calc_kwa:
6357 raise Exception("KWA mismatch")
6358
6359 return decrypted
6360
6361 def zeropad_str(val, pad_len):
6362 while len(val) < pad_len * 2:
6363 val = '0' + val
6364 return val
6365
6366 def wsc_dh_init():
6367 # For now, use a hardcoded private key. In theory, this is supposed to be
6368 # randomly selected.
6369 own_private = 0x123456789
6370 own_public = pow(group_5_generator, own_private, group_5_prime)
6371 pk = binascii.unhexlify(zeropad_str(format(own_public, '02x'), 192))
6372 return own_private, pk
6373
6374 def wsc_dh_kdf(peer_pk, own_private, mac_addr, e_nonce, r_nonce):
6375 peer_public = int(binascii.hexlify(peer_pk), 16)
6376 if peer_public < 2 or peer_public >= group_5_prime:
6377 raise Exception("Invalid peer public key")
6378 if pow(peer_public, (group_5_prime - 1) // 2, group_5_prime) != 1:
6379 raise Exception("Unexpected Legendre symbol for peer public key")
6380
6381 shared_secret = pow(peer_public, own_private, group_5_prime)
6382 ss = zeropad_str(format(shared_secret, "02x"), 192)
6383 logger.debug("DH shared secret: " + ss)
6384
6385 dhkey = hashlib.sha256(binascii.unhexlify(ss)).digest()
6386 logger.debug("DHKey: " + binascii.hexlify(dhkey).decode())
6387
6388 m = hmac.new(dhkey, e_nonce + mac_addr + r_nonce, hashlib.sha256)
6389 kdk = m.digest()
6390 logger.debug("KDK: " + binascii.hexlify(kdk).decode())
6391 authkey, keywrapkey, emsk = wsc_keys(kdk)
6392 logger.debug("AuthKey: " + binascii.hexlify(authkey).decode())
6393 logger.debug("KeyWrapKey: " + binascii.hexlify(keywrapkey).decode())
6394 logger.debug("EMSK: " + binascii.hexlify(emsk).decode())
6395 return authkey, keywrapkey
6396
6397 def wsc_dev_pw_hash(authkey, dev_pw, e_pk, r_pk):
6398 psk1, psk2 = wsc_dev_pw_psk(authkey, dev_pw)
6399 logger.debug("PSK1: " + binascii.hexlify(psk1).decode())
6400 logger.debug("PSK2: " + binascii.hexlify(psk2).decode())
6401
6402 # Note: Secret values are supposed to be random, but hardcoded values are
6403 # fine for testing.
6404 s1 = 16*b'\x77'
6405 m = hmac.new(authkey, s1 + psk1 + e_pk + r_pk, hashlib.sha256)
6406 hash1 = m.digest()
6407 logger.debug("Hash1: " + binascii.hexlify(hash1).decode())
6408
6409 s2 = 16*b'\x88'
6410 m = hmac.new(authkey, s2 + psk2 + e_pk + r_pk, hashlib.sha256)
6411 hash2 = m.digest()
6412 logger.debug("Hash2: " + binascii.hexlify(hash2).decode())
6413 return s1, s2, hash1, hash2
6414
6415 def build_m1(eap_id, uuid_e, mac_addr, e_nonce, e_pk,
6416 manufacturer='', model_name='', config_methods='\x00\x00'):
6417 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6418 attrs += build_attr_msg_type(WPS_M1)
6419 attrs += build_wsc_attr(ATTR_UUID_E, uuid_e)
6420 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6421 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6422 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, e_pk)
6423 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6424 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6425 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6426 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, config_methods)
6427 attrs += build_wsc_attr(ATTR_WPS_STATE, '\x00')
6428 attrs += build_wsc_attr(ATTR_MANUFACTURER, manufacturer)
6429 attrs += build_wsc_attr(ATTR_MODEL_NAME, model_name)
6430 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6431 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6432 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6433 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6434 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6435 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6436 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, '\x00\x00')
6437 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6438 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6439 m1 = build_eap_wsc(2, eap_id, attrs)
6440 return m1, attrs
6441
6442 def build_m2(authkey, m1, eap_id, e_nonce, r_nonce, uuid_r, r_pk,
6443 dev_pw_id='\x00\x00', eap_code=1):
6444 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6445 attrs += build_attr_msg_type(WPS_M2)
6446 if e_nonce:
6447 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6448 if r_nonce:
6449 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6450 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6451 if r_pk:
6452 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, r_pk)
6453 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6454 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6455 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6456 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6457 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6458 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6459 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6460 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6461 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6462 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6463 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6464 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6465 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6466 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6467 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6468 attrs += build_attr_authenticator(authkey, m1, attrs)
6469 m2 = build_eap_wsc(eap_code, eap_id, attrs)
6470 return m2, attrs
6471
6472 def build_m2d(m1, eap_id, e_nonce, r_nonce, uuid_r, dev_pw_id=None, eap_code=1):
6473 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6474 attrs += build_attr_msg_type(WPS_M2D)
6475 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6476 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6477 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6478 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6479 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6480 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6481 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6482 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6483 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6484 #attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6485 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6486 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6487 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6488 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6489 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6490 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6491 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6492 if dev_pw_id:
6493 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6494 m2d = build_eap_wsc(eap_code, eap_id, attrs)
6495 return m2d, attrs
6496
6497 def build_ack(eap_id, e_nonce, r_nonce, msg_type=WPS_WSC_ACK, eap_code=1):
6498 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6499 if msg_type is not None:
6500 attrs += build_attr_msg_type(msg_type)
6501 if e_nonce:
6502 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6503 if r_nonce:
6504 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6505 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_ACK)
6506 return msg, attrs
6507
6508 def build_nack(eap_id, e_nonce, r_nonce, config_error='\x00\x00',
6509 msg_type=WPS_WSC_NACK, eap_code=1):
6510 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6511 if msg_type is not None:
6512 attrs += build_attr_msg_type(msg_type)
6513 if e_nonce:
6514 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6515 if r_nonce:
6516 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6517 if config_error:
6518 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, config_error)
6519 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_NACK)
6520 return msg, attrs
6521
6522 def test_wps_ext(dev, apdev):
6523 """WPS against external implementation"""
6524 pin = "12345670"
6525 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6526 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6527 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6528
6529 logger.debug("Receive WSC/Start from AP")
6530 msg = get_wsc_msg(hapd)
6531 if msg['wsc_opcode'] != WSC_Start:
6532 raise Exception("Unexpected Op-Code for WSC/Start")
6533 wsc_start_id = msg['eap_identifier']
6534
6535 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6536 uuid_e = 16*b'\x11'
6537 e_nonce = 16*b'\x22'
6538 own_private, e_pk = wsc_dh_init()
6539
6540 logger.debug("Send M1 to AP")
6541 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
6542 e_nonce, e_pk)
6543 send_wsc_msg(hapd, addr, m1)
6544
6545 logger.debug("Receive M2 from AP")
6546 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
6547
6548 authkey, keywrapkey = wsc_dh_kdf(m2_attrs[ATTR_PUBLIC_KEY], own_private,
6549 mac_addr, e_nonce,
6550 m2_attrs[ATTR_REGISTRAR_NONCE])
6551 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk,
6552 m2_attrs[ATTR_PUBLIC_KEY])
6553
6554 logger.debug("Send M3 to AP")
6555 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6556 attrs += build_attr_msg_type(WPS_M3)
6557 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6558 m2_attrs[ATTR_REGISTRAR_NONCE])
6559 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
6560 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
6561 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
6562 raw_m3_attrs = attrs
6563 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6564 send_wsc_msg(hapd, addr, m3)
6565
6566 logger.debug("Receive M4 from AP")
6567 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
6568
6569 logger.debug("Send M5 to AP")
6570 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6571 attrs += build_attr_msg_type(WPS_M5)
6572 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6573 m2_attrs[ATTR_REGISTRAR_NONCE])
6574 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
6575 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6576 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
6577 raw_m5_attrs = attrs
6578 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6579 send_wsc_msg(hapd, addr, m5)
6580
6581 logger.debug("Receive M6 from AP")
6582 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
6583
6584 logger.debug("Send M7 to AP")
6585 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6586 attrs += build_attr_msg_type(WPS_M7)
6587 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6588 m2_attrs[ATTR_REGISTRAR_NONCE])
6589 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
6590 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6591 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
6592 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6593 raw_m7_attrs = attrs
6594 send_wsc_msg(hapd, addr, m7)
6595
6596 logger.debug("Receive M8 from AP")
6597 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
6598 m8_cred = decrypt_attr_encr_settings(authkey, keywrapkey,
6599 m8_attrs[ATTR_ENCR_SETTINGS])
6600 logger.debug("M8 Credential: " + binascii.hexlify(m8_cred).decode())
6601
6602 logger.debug("Prepare WSC_Done")
6603 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6604 attrs += build_attr_msg_type(WPS_WSC_DONE)
6605 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6606 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6607 m2_attrs[ATTR_REGISTRAR_NONCE])
6608 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
6609 # Do not send WSC_Done yet to allow exchangw with STA complete before the
6610 # AP disconnects.
6611
6612 uuid_r = 16*b'\x33'
6613 r_nonce = 16*b'\x44'
6614
6615 eap_id = wsc_start_id
6616 logger.debug("Send WSC/Start to STA")
6617 wsc_start = build_eap_wsc(1, eap_id, b'', opcode=WSC_Start)
6618 send_wsc_msg(dev[0], bssid, wsc_start)
6619 eap_id = (eap_id + 1) % 256
6620
6621 logger.debug("Receive M1 from STA")
6622 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6623
6624 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6625 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6626 r_nonce)
6627 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
6628 m1_attrs[ATTR_PUBLIC_KEY],
6629 e_pk)
6630
6631 logger.debug("Send M2 to STA")
6632 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6633 m1_attrs[ATTR_ENROLLEE_NONCE],
6634 r_nonce, uuid_r, e_pk)
6635 send_wsc_msg(dev[0], bssid, m2)
6636 eap_id = (eap_id + 1) % 256
6637
6638 logger.debug("Receive M3 from STA")
6639 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6640
6641 logger.debug("Send M4 to STA")
6642 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6643 attrs += build_attr_msg_type(WPS_M4)
6644 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6645 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6646 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6647 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6648 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6649 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6650 raw_m4_attrs = attrs
6651 m4 = build_eap_wsc(1, eap_id, attrs)
6652 send_wsc_msg(dev[0], bssid, m4)
6653 eap_id = (eap_id + 1) % 256
6654
6655 logger.debug("Receive M5 from STA")
6656 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6657
6658 logger.debug("Send M6 to STA")
6659 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6660 attrs += build_attr_msg_type(WPS_M6)
6661 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6662 m1_attrs[ATTR_ENROLLEE_NONCE])
6663 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6664 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6665 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6666 raw_m6_attrs = attrs
6667 m6 = build_eap_wsc(1, eap_id, attrs)
6668 send_wsc_msg(dev[0], bssid, m6)
6669 eap_id = (eap_id + 1) % 256
6670
6671 logger.debug("Receive M7 from STA")
6672 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6673
6674 logger.debug("Send M8 to STA")
6675 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6676 attrs += build_attr_msg_type(WPS_M8)
6677 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6678 m1_attrs[ATTR_ENROLLEE_NONCE])
6679 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6680 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6681 raw_m8_attrs = attrs
6682 m8 = build_eap_wsc(1, eap_id, attrs)
6683 send_wsc_msg(dev[0], bssid, m8)
6684 eap_id = (eap_id + 1) % 256
6685
6686 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=5)
6687 if ev is None:
6688 raise Exception("wpa_supplicant did not report credential")
6689
6690 logger.debug("Receive WSC_Done from STA")
6691 msg = get_wsc_msg(dev[0])
6692 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6693 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6694
6695 logger.debug("Send WSC_Done to AP")
6696 hapd.request("SET ext_eapol_frame_io 0")
6697 dev[0].request("SET ext_eapol_frame_io 0")
6698 send_wsc_msg(hapd, addr, wsc_done)
6699
6700 ev = hapd.wait_event(["WPS-REG-SUCCESS"], timeout=5)
6701 if ev is None:
6702 raise Exception("hostapd did not report WPS success")
6703
6704 dev[0].wait_connected()
6705
6706 def wps_start_kwa(dev, apdev):
6707 pin = "12345670"
6708 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6709 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6710 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6711 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6712
6713 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6714 uuid_r = 16*b'\x33'
6715 r_nonce = 16*b'\x44'
6716 own_private, e_pk = wsc_dh_init()
6717
6718 logger.debug("Receive M1 from STA")
6719 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6720 eap_id = (msg['eap_identifier'] + 1) % 256
6721
6722 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6723 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6724 r_nonce)
6725 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
6726 m1_attrs[ATTR_PUBLIC_KEY],
6727 e_pk)
6728
6729 logger.debug("Send M2 to STA")
6730 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6731 m1_attrs[ATTR_ENROLLEE_NONCE],
6732 r_nonce, uuid_r, e_pk)
6733 send_wsc_msg(dev[0], bssid, m2)
6734 eap_id = (eap_id + 1) % 256
6735
6736 logger.debug("Receive M3 from STA")
6737 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6738
6739 logger.debug("Send M4 to STA")
6740 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6741 attrs += build_attr_msg_type(WPS_M4)
6742 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6743 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6744 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6745
6746 return r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs
6747
6748 def wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id):
6749 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6750 m4 = build_eap_wsc(1, eap_id, attrs)
6751 send_wsc_msg(dev[0], bssid, m4)
6752 eap_id = (eap_id + 1) % 256
6753
6754 logger.debug("Receive M5 from STA")
6755 msg = get_wsc_msg(dev[0])
6756 if msg['wsc_opcode'] != WSC_NACK:
6757 raise Exception("Unexpected message - expected WSC_Nack")
6758
6759 dev[0].request("WPS_CANCEL")
6760 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6761 dev[0].wait_disconnected()
6762
6763 def test_wps_ext_kwa_proto_no_kwa(dev, apdev):
6764 """WPS and KWA error: No KWA attribute"""
6765 r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs = wps_start_kwa(dev, apdev)
6766 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6767 # Encrypted Settings without KWA
6768 iv = 16*b'\x99'
6769 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6770 pad_len = 16 - len(data) % 16
6771 ps = pad_len * struct.pack('B', pad_len)
6772 data += ps
6773 wrapped = aes.encrypt(data)
6774 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6775 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6776
6777 def test_wps_ext_kwa_proto_data_after_kwa(dev, apdev):
6778 """WPS and KWA error: Data after KWA"""
6779 r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs = wps_start_kwa(dev, apdev)
6780 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6781 # Encrypted Settings and data after KWA
6782 m = hmac.new(authkey, data, hashlib.sha256)
6783 kwa = m.digest()[0:8]
6784 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6785 data += build_wsc_attr(ATTR_VENDOR_EXT, "1234567890")
6786 iv = 16*b'\x99'
6787 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6788 pad_len = 16 - len(data) % 16
6789 ps = pad_len * struct.pack('B', pad_len)
6790 data += ps
6791 wrapped = aes.encrypt(data)
6792 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6793 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6794
6795 def test_wps_ext_kwa_proto_kwa_mismatch(dev, apdev):
6796 """WPS and KWA error: KWA mismatch"""
6797 r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs = wps_start_kwa(dev, apdev)
6798 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6799 # Encrypted Settings and KWA with incorrect value
6800 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, 8*'\x00')
6801 iv = 16*b'\x99'
6802 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6803 pad_len = 16 - len(data) % 16
6804 ps = pad_len * struct.pack('B', pad_len)
6805 data += ps
6806 wrapped = aes.encrypt(data)
6807 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6808 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6809
6810 def wps_run_cred_proto(dev, apdev, m8_cred, connect=False, no_connect=False):
6811 pin = "12345670"
6812 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6813 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6814 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6815 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6816
6817 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6818 uuid_r = 16*b'\x33'
6819 r_nonce = 16*b'\x44'
6820 own_private, e_pk = wsc_dh_init()
6821
6822 logger.debug("Receive M1 from STA")
6823 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6824 eap_id = (msg['eap_identifier'] + 1) % 256
6825
6826 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6827 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6828 r_nonce)
6829 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
6830 m1_attrs[ATTR_PUBLIC_KEY],
6831 e_pk)
6832
6833 logger.debug("Send M2 to STA")
6834 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6835 m1_attrs[ATTR_ENROLLEE_NONCE],
6836 r_nonce, uuid_r, e_pk)
6837 send_wsc_msg(dev[0], bssid, m2)
6838 eap_id = (eap_id + 1) % 256
6839
6840 logger.debug("Receive M3 from STA")
6841 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6842
6843 logger.debug("Send M4 to STA")
6844 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6845 attrs += build_attr_msg_type(WPS_M4)
6846 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6847 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6848 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6849 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6850 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6851 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6852 raw_m4_attrs = attrs
6853 m4 = build_eap_wsc(1, eap_id, attrs)
6854 send_wsc_msg(dev[0], bssid, m4)
6855 eap_id = (eap_id + 1) % 256
6856
6857 logger.debug("Receive M5 from STA")
6858 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6859
6860 logger.debug("Send M6 to STA")
6861 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6862 attrs += build_attr_msg_type(WPS_M6)
6863 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6864 m1_attrs[ATTR_ENROLLEE_NONCE])
6865 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6866 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6867 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6868 raw_m6_attrs = attrs
6869 m6 = build_eap_wsc(1, eap_id, attrs)
6870 send_wsc_msg(dev[0], bssid, m6)
6871 eap_id = (eap_id + 1) % 256
6872
6873 logger.debug("Receive M7 from STA")
6874 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6875
6876 logger.debug("Send M8 to STA")
6877 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6878 attrs += build_attr_msg_type(WPS_M8)
6879 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6880 m1_attrs[ATTR_ENROLLEE_NONCE])
6881 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6882 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6883 raw_m8_attrs = attrs
6884 m8 = build_eap_wsc(1, eap_id, attrs)
6885 send_wsc_msg(dev[0], bssid, m8)
6886 eap_id = (eap_id + 1) % 256
6887
6888 if no_connect:
6889 logger.debug("Receive WSC_Done from STA")
6890 msg = get_wsc_msg(dev[0])
6891 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6892 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6893
6894 hapd.request("SET ext_eapol_frame_io 0")
6895 dev[0].request("SET ext_eapol_frame_io 0")
6896
6897 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6898
6899 dev[0].wait_disconnected()
6900 dev[0].request("REMOVE_NETWORK all")
6901 elif connect:
6902 logger.debug("Receive WSC_Done from STA")
6903 msg = get_wsc_msg(dev[0])
6904 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6905 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6906
6907 hapd.request("SET ext_eapol_frame_io 0")
6908 dev[0].request("SET ext_eapol_frame_io 0")
6909
6910 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6911
6912 dev[0].wait_connected()
6913 else:
6914 # Verify STA NACK's the credential
6915 msg = get_wsc_msg(dev[0])
6916 if msg['wsc_opcode'] != WSC_NACK:
6917 raise Exception("Unexpected message - expected WSC_Nack")
6918 dev[0].request("WPS_CANCEL")
6919 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6920 dev[0].wait_disconnected()
6921
6922 def build_cred(nw_idx='\x01', ssid='test-wps-conf', auth_type='\x00\x20',
6923 encr_type='\x00\x08', nw_key="12345678",
6924 mac_addr='\x00\x00\x00\x00\x00\x00'):
6925 attrs = b''
6926 if nw_idx is not None:
6927 attrs += build_wsc_attr(ATTR_NETWORK_INDEX, nw_idx)
6928 if ssid is not None:
6929 attrs += build_wsc_attr(ATTR_SSID, ssid)
6930 if auth_type is not None:
6931 attrs += build_wsc_attr(ATTR_AUTH_TYPE, auth_type)
6932 if encr_type is not None:
6933 attrs += build_wsc_attr(ATTR_ENCR_TYPE, encr_type)
6934 if nw_key is not None:
6935 attrs += build_wsc_attr(ATTR_NETWORK_KEY, nw_key)
6936 if mac_addr is not None:
6937 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6938 return build_wsc_attr(ATTR_CRED, attrs)
6939
6940 def test_wps_ext_cred_proto_success(dev, apdev):
6941 """WPS and Credential: success"""
6942 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6943 m8_cred = build_cred(mac_addr=mac_addr)
6944 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6945
6946 def test_wps_ext_cred_proto_mac_addr_mismatch(dev, apdev):
6947 """WPS and Credential: MAC Address mismatch"""
6948 m8_cred = build_cred()
6949 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6950
6951 def test_wps_ext_cred_proto_zero_padding(dev, apdev):
6952 """WPS and Credential: zeropadded attributes"""
6953 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6954 m8_cred = build_cred(mac_addr=mac_addr, ssid='test-wps-conf\x00',
6955 nw_key="12345678\x00")
6956 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6957
6958 def test_wps_ext_cred_proto_ssid_missing(dev, apdev):
6959 """WPS and Credential: SSID missing"""
6960 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6961 m8_cred = build_cred(mac_addr=mac_addr, ssid=None)
6962 wps_run_cred_proto(dev, apdev, m8_cred)
6963
6964 def test_wps_ext_cred_proto_ssid_zero_len(dev, apdev):
6965 """WPS and Credential: Zero-length SSID"""
6966 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6967 m8_cred = build_cred(mac_addr=mac_addr, ssid="")
6968 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6969
6970 def test_wps_ext_cred_proto_auth_type_missing(dev, apdev):
6971 """WPS and Credential: Auth Type missing"""
6972 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6973 m8_cred = build_cred(mac_addr=mac_addr, auth_type=None)
6974 wps_run_cred_proto(dev, apdev, m8_cred)
6975
6976 def test_wps_ext_cred_proto_encr_type_missing(dev, apdev):
6977 """WPS and Credential: Encr Type missing"""
6978 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6979 m8_cred = build_cred(mac_addr=mac_addr, encr_type=None)
6980 wps_run_cred_proto(dev, apdev, m8_cred)
6981
6982 def test_wps_ext_cred_proto_network_key_missing(dev, apdev):
6983 """WPS and Credential: Network Key missing"""
6984 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6985 m8_cred = build_cred(mac_addr=mac_addr, nw_key=None)
6986 wps_run_cred_proto(dev, apdev, m8_cred)
6987
6988 def test_wps_ext_cred_proto_network_key_missing_open(dev, apdev):
6989 """WPS and Credential: Network Key missing (open)"""
6990 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6991 m8_cred = build_cred(mac_addr=mac_addr, auth_type='\x00\x01',
6992 encr_type='\x00\x01', nw_key=None, ssid="foo")
6993 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6994
6995 def test_wps_ext_cred_proto_mac_addr_missing(dev, apdev):
6996 """WPS and Credential: MAC Address missing"""
6997 m8_cred = build_cred(mac_addr=None)
6998 wps_run_cred_proto(dev, apdev, m8_cred)
6999
7000 def test_wps_ext_cred_proto_invalid_encr_type(dev, apdev):
7001 """WPS and Credential: Invalid Encr Type"""
7002 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7003 m8_cred = build_cred(mac_addr=mac_addr, encr_type='\x00\x00')
7004 wps_run_cred_proto(dev, apdev, m8_cred)
7005
7006 def test_wps_ext_cred_proto_missing_cred(dev, apdev):
7007 """WPS and Credential: Missing Credential"""
7008 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7009 m8_cred = b''
7010 wps_run_cred_proto(dev, apdev, m8_cred)
7011
7012 def test_wps_ext_proto_m2_no_public_key(dev, apdev):
7013 """WPS and no Public Key in M2"""
7014 pin = "12345670"
7015 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7016 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7017 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7018 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7019
7020 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7021 uuid_r = 16*b'\x33'
7022 r_nonce = 16*b'\x44'
7023 own_private, e_pk = wsc_dh_init()
7024
7025 logger.debug("Receive M1 from STA")
7026 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7027 eap_id = (msg['eap_identifier'] + 1) % 256
7028
7029 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7030 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7031 r_nonce)
7032 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7033 m1_attrs[ATTR_PUBLIC_KEY],
7034 e_pk)
7035
7036 logger.debug("Send M2 to STA")
7037 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7038 m1_attrs[ATTR_ENROLLEE_NONCE],
7039 r_nonce, uuid_r, None)
7040 send_wsc_msg(dev[0], bssid, m2)
7041 eap_id = (eap_id + 1) % 256
7042
7043 # Verify STA NACK's the credential
7044 msg = get_wsc_msg(dev[0])
7045 if msg['wsc_opcode'] != WSC_NACK:
7046 raise Exception("Unexpected message - expected WSC_Nack")
7047 dev[0].request("WPS_CANCEL")
7048 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7049 dev[0].wait_disconnected()
7050
7051 def test_wps_ext_proto_m2_invalid_public_key(dev, apdev):
7052 """WPS and invalid Public Key in M2"""
7053 pin = "12345670"
7054 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7055 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7056 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7057 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7058
7059 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7060 uuid_r = 16*b'\x33'
7061 r_nonce = 16*b'\x44'
7062 own_private, e_pk = wsc_dh_init()
7063
7064 logger.debug("Receive M1 from STA")
7065 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7066 eap_id = (msg['eap_identifier'] + 1) % 256
7067
7068 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7069 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7070 r_nonce)
7071 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7072 m1_attrs[ATTR_PUBLIC_KEY],
7073 e_pk)
7074
7075 logger.debug("Send M2 to STA")
7076 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7077 m1_attrs[ATTR_ENROLLEE_NONCE],
7078 r_nonce, uuid_r, 192*b'\xff')
7079 send_wsc_msg(dev[0], bssid, m2)
7080 eap_id = (eap_id + 1) % 256
7081
7082 # Verify STA NACK's the credential
7083 msg = get_wsc_msg(dev[0])
7084 if msg['wsc_opcode'] != WSC_NACK:
7085 raise Exception("Unexpected message - expected WSC_Nack")
7086 dev[0].request("WPS_CANCEL")
7087 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7088 dev[0].wait_disconnected()
7089
7090 def test_wps_ext_proto_m2_public_key_oom(dev, apdev):
7091 """WPS and Public Key OOM in M2"""
7092 pin = "12345670"
7093 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7094 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7095 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7096 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7097
7098 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7099 uuid_r = 16*b'\x33'
7100 r_nonce = 16*b'\x44'
7101 own_private, e_pk = wsc_dh_init()
7102
7103 logger.debug("Receive M1 from STA")
7104 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7105 eap_id = (msg['eap_identifier'] + 1) % 256
7106
7107 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7108 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7109 r_nonce)
7110 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7111 m1_attrs[ATTR_PUBLIC_KEY],
7112 e_pk)
7113
7114 logger.debug("Send M2 to STA")
7115 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7116 m1_attrs[ATTR_ENROLLEE_NONCE],
7117 r_nonce, uuid_r, e_pk)
7118 with alloc_fail(dev[0], 1, "wpabuf_alloc_copy;wps_process_pubkey"):
7119 send_wsc_msg(dev[0], bssid, m2)
7120 eap_id = (eap_id + 1) % 256
7121
7122 # Verify STA NACK's the credential
7123 msg = get_wsc_msg(dev[0])
7124 if msg['wsc_opcode'] != WSC_NACK:
7125 raise Exception("Unexpected message - expected WSC_Nack")
7126 dev[0].request("WPS_CANCEL")
7127 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7128 dev[0].wait_disconnected()
7129
7130 def test_wps_ext_proto_nack_m3(dev, apdev):
7131 """WPS and NACK M3"""
7132 pin = "12345670"
7133 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7134 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7135 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7136 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7137
7138 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7139 uuid_r = 16*b'\x33'
7140 r_nonce = 16*b'\x44'
7141 own_private, e_pk = wsc_dh_init()
7142
7143 logger.debug("Receive M1 from STA")
7144 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7145 eap_id = (msg['eap_identifier'] + 1) % 256
7146
7147 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7148 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7149 r_nonce)
7150 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7151 m1_attrs[ATTR_PUBLIC_KEY],
7152 e_pk)
7153
7154 logger.debug("Send M2 to STA")
7155 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7156 m1_attrs[ATTR_ENROLLEE_NONCE],
7157 r_nonce, uuid_r, e_pk)
7158 send_wsc_msg(dev[0], bssid, m2)
7159 eap_id = (eap_id + 1) % 256
7160
7161 logger.debug("Receive M3 from STA")
7162 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7163
7164 logger.debug("Send NACK to STA")
7165 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7166 r_nonce, config_error='\x01\x23')
7167 send_wsc_msg(dev[0], bssid, msg)
7168 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7169 if ev is None:
7170 raise Exception("Failure not reported")
7171 if "msg=7 config_error=291" not in ev:
7172 raise Exception("Unexpected failure reason: " + ev)
7173
7174 def test_wps_ext_proto_nack_m5(dev, apdev):
7175 """WPS and NACK M5"""
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, e_pk)
7202 send_wsc_msg(dev[0], bssid, m2)
7203 eap_id = (eap_id + 1) % 256
7204
7205 logger.debug("Receive M3 from STA")
7206 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7207
7208 logger.debug("Send M4 to STA")
7209 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7210 attrs += build_attr_msg_type(WPS_M4)
7211 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7212 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7213 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7214 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7215 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7216 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7217 raw_m4_attrs = attrs
7218 m4 = build_eap_wsc(1, eap_id, attrs)
7219 send_wsc_msg(dev[0], bssid, m4)
7220 eap_id = (eap_id + 1) % 256
7221
7222 logger.debug("Receive M5 from STA")
7223 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7224
7225 logger.debug("Send NACK to STA")
7226 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7227 r_nonce, config_error='\x01\x24')
7228 send_wsc_msg(dev[0], bssid, msg)
7229 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7230 if ev is None:
7231 raise Exception("Failure not reported")
7232 if "msg=9 config_error=292" not in ev:
7233 raise Exception("Unexpected failure reason: " + ev)
7234
7235 def wps_nack_m3(dev, apdev):
7236 pin = "00000000"
7237 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
7238 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7239 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7240 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7241
7242 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7243 uuid_r = 16*b'\x33'
7244 r_nonce = 16*b'\x44'
7245 own_private, e_pk = wsc_dh_init()
7246
7247 logger.debug("Receive M1 from STA")
7248 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7249 eap_id = (msg['eap_identifier'] + 1) % 256
7250
7251 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7252 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7253 r_nonce)
7254 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7255 m1_attrs[ATTR_PUBLIC_KEY],
7256 e_pk)
7257
7258 logger.debug("Send M2 to STA")
7259 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7260 m1_attrs[ATTR_ENROLLEE_NONCE],
7261 r_nonce, uuid_r, e_pk, dev_pw_id='\x00\x04')
7262 send_wsc_msg(dev[0], bssid, m2)
7263 eap_id = (eap_id + 1) % 256
7264
7265 logger.debug("Receive M3 from STA")
7266 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7267 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid
7268
7269 def test_wps_ext_proto_nack_m3_no_config_error(dev, apdev):
7270 """WPS and NACK M3 missing Config Error"""
7271 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7272 logger.debug("Send NACK to STA")
7273 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, config_error=None)
7274 send_wsc_msg(dev[0], bssid, msg)
7275 dev[0].request("WPS_CANCEL")
7276 dev[0].wait_disconnected()
7277 dev[0].flush_scan_cache()
7278
7279 def test_wps_ext_proto_nack_m3_no_e_nonce(dev, apdev):
7280 """WPS and NACK M3 missing E-Nonce"""
7281 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7282 logger.debug("Send NACK to STA")
7283 msg, attrs = build_nack(eap_id, None, r_nonce)
7284 send_wsc_msg(dev[0], bssid, msg)
7285 dev[0].request("WPS_CANCEL")
7286 dev[0].wait_disconnected()
7287 dev[0].flush_scan_cache()
7288
7289 def test_wps_ext_proto_nack_m3_e_nonce_mismatch(dev, apdev):
7290 """WPS and NACK M3 E-Nonce mismatch"""
7291 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7292 logger.debug("Send NACK to STA")
7293 msg, attrs = build_nack(eap_id, 16*'\x00', r_nonce)
7294 send_wsc_msg(dev[0], bssid, msg)
7295 dev[0].request("WPS_CANCEL")
7296 dev[0].wait_disconnected()
7297 dev[0].flush_scan_cache()
7298
7299 def test_wps_ext_proto_nack_m3_no_r_nonce(dev, apdev):
7300 """WPS and NACK M3 missing R-Nonce"""
7301 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7302 logger.debug("Send NACK to STA")
7303 msg, attrs = build_nack(eap_id, e_nonce, None)
7304 send_wsc_msg(dev[0], bssid, msg)
7305 dev[0].request("WPS_CANCEL")
7306 dev[0].wait_disconnected()
7307 dev[0].flush_scan_cache()
7308
7309 def test_wps_ext_proto_nack_m3_r_nonce_mismatch(dev, apdev):
7310 """WPS and NACK M3 R-Nonce mismatch"""
7311 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7312 logger.debug("Send NACK to STA")
7313 msg, attrs = build_nack(eap_id, e_nonce, 16*'\x00')
7314 send_wsc_msg(dev[0], bssid, msg)
7315 dev[0].request("WPS_CANCEL")
7316 dev[0].wait_disconnected()
7317 dev[0].flush_scan_cache()
7318
7319 def test_wps_ext_proto_nack_m3_no_msg_type(dev, apdev):
7320 """WPS and NACK M3 no Message Type"""
7321 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7322 logger.debug("Send NACK to STA")
7323 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=None)
7324 send_wsc_msg(dev[0], bssid, msg)
7325 dev[0].request("WPS_CANCEL")
7326 dev[0].wait_disconnected()
7327 dev[0].flush_scan_cache()
7328
7329 def test_wps_ext_proto_nack_m3_invalid_msg_type(dev, apdev):
7330 """WPS and NACK M3 invalid Message Type"""
7331 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7332 logger.debug("Send NACK to STA")
7333 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=123)
7334 send_wsc_msg(dev[0], bssid, msg)
7335 dev[0].request("WPS_CANCEL")
7336 dev[0].wait_disconnected()
7337 dev[0].flush_scan_cache()
7338
7339 def test_wps_ext_proto_nack_m3_invalid_attr(dev, apdev):
7340 """WPS and NACK M3 invalid attribute"""
7341 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7342 logger.debug("Send NACK to STA")
7343 attrs = b'\x10\x10\x00'
7344 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_NACK)
7345 send_wsc_msg(dev[0], bssid, msg)
7346 dev[0].request("WPS_CANCEL")
7347 dev[0].wait_disconnected()
7348 dev[0].flush_scan_cache()
7349
7350 def test_wps_ext_proto_ack_m3_no_e_nonce(dev, apdev):
7351 """WPS and ACK M3 missing E-Nonce"""
7352 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7353 logger.debug("Send NACK to STA")
7354 msg, attrs = build_ack(eap_id, None, r_nonce)
7355 send_wsc_msg(dev[0], bssid, msg)
7356 dev[0].request("WPS_CANCEL")
7357 dev[0].wait_disconnected()
7358 dev[0].flush_scan_cache()
7359
7360 def test_wps_ext_proto_ack_m3_e_nonce_mismatch(dev, apdev):
7361 """WPS and ACK M3 E-Nonce mismatch"""
7362 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7363 logger.debug("Send NACK to STA")
7364 msg, attrs = build_ack(eap_id, 16*'\x00', r_nonce)
7365 send_wsc_msg(dev[0], bssid, msg)
7366 dev[0].request("WPS_CANCEL")
7367 dev[0].wait_disconnected()
7368 dev[0].flush_scan_cache()
7369
7370 def test_wps_ext_proto_ack_m3_no_r_nonce(dev, apdev):
7371 """WPS and ACK M3 missing R-Nonce"""
7372 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7373 logger.debug("Send NACK to STA")
7374 msg, attrs = build_ack(eap_id, e_nonce, None)
7375 send_wsc_msg(dev[0], bssid, msg)
7376 dev[0].request("WPS_CANCEL")
7377 dev[0].wait_disconnected()
7378 dev[0].flush_scan_cache()
7379
7380 def test_wps_ext_proto_ack_m3_r_nonce_mismatch(dev, apdev):
7381 """WPS and ACK M3 R-Nonce mismatch"""
7382 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7383 logger.debug("Send NACK to STA")
7384 msg, attrs = build_ack(eap_id, e_nonce, 16*'\x00')
7385 send_wsc_msg(dev[0], bssid, msg)
7386 dev[0].request("WPS_CANCEL")
7387 dev[0].wait_disconnected()
7388 dev[0].flush_scan_cache()
7389
7390 def test_wps_ext_proto_ack_m3_no_msg_type(dev, apdev):
7391 """WPS and ACK M3 no Message Type"""
7392 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7393 logger.debug("Send NACK to STA")
7394 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=None)
7395 send_wsc_msg(dev[0], bssid, msg)
7396 dev[0].request("WPS_CANCEL")
7397 dev[0].wait_disconnected()
7398 dev[0].flush_scan_cache()
7399
7400 def test_wps_ext_proto_ack_m3_invalid_msg_type(dev, apdev):
7401 """WPS and ACK M3 invalid Message Type"""
7402 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7403 logger.debug("Send NACK to STA")
7404 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=123)
7405 send_wsc_msg(dev[0], bssid, msg)
7406 dev[0].request("WPS_CANCEL")
7407 dev[0].wait_disconnected()
7408 dev[0].flush_scan_cache()
7409
7410 def test_wps_ext_proto_ack_m3_invalid_attr(dev, apdev):
7411 """WPS and ACK M3 invalid attribute"""
7412 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7413 logger.debug("Send ACK to STA")
7414 attrs = b'\x10\x10\x00'
7415 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_ACK)
7416 send_wsc_msg(dev[0], bssid, msg)
7417 dev[0].request("WPS_CANCEL")
7418 dev[0].wait_disconnected()
7419 dev[0].flush_scan_cache()
7420
7421 def test_wps_ext_proto_ack_m3(dev, apdev):
7422 """WPS and ACK M3"""
7423 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7424 logger.debug("Send ACK to STA")
7425 msg, attrs = build_ack(eap_id, e_nonce, r_nonce)
7426 send_wsc_msg(dev[0], bssid, msg)
7427 dev[0].request("WPS_CANCEL")
7428 dev[0].wait_disconnected()
7429 dev[0].flush_scan_cache()
7430
7431 def wps_to_m3_helper(dev, apdev):
7432 pin = "12345670"
7433 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7434 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7435 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7436 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7437
7438 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7439 uuid_r = 16*b'\x33'
7440 r_nonce = 16*b'\x44'
7441 own_private, e_pk = wsc_dh_init()
7442
7443 logger.debug("Receive M1 from STA")
7444 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7445 eap_id = (msg['eap_identifier'] + 1) % 256
7446
7447 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7448 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7449 r_nonce)
7450 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7451 m1_attrs[ATTR_PUBLIC_KEY],
7452 e_pk)
7453
7454 logger.debug("Send M2 to STA")
7455 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7456 m1_attrs[ATTR_ENROLLEE_NONCE],
7457 r_nonce, uuid_r, e_pk)
7458 send_wsc_msg(dev[0], bssid, m2)
7459 eap_id = (eap_id + 1) % 256
7460
7461 logger.debug("Receive M3 from STA")
7462 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7463 return eap_id, m1_attrs, r_nonce, bssid, r_hash1, r_hash2, r_s1, r_s2, raw_m3_attrs, authkey, keywrapkey
7464
7465 def wps_to_m3(dev, apdev):
7466 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)
7467 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s1, raw_m3_attrs, authkey, keywrapkey
7468
7469 def wps_to_m5(dev, apdev):
7470 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)
7471
7472 logger.debug("Send M4 to STA")
7473 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7474 attrs += build_attr_msg_type(WPS_M4)
7475 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7476 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7477 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7478 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7479 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7480 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7481 raw_m4_attrs = attrs
7482 m4 = build_eap_wsc(1, eap_id, attrs)
7483 send_wsc_msg(dev[0], bssid, m4)
7484 eap_id = (eap_id + 1) % 256
7485
7486 logger.debug("Receive M5 from STA")
7487 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7488
7489 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s2, raw_m5_attrs, authkey, keywrapkey
7490
7491 def test_wps_ext_proto_m4_missing_r_hash1(dev, apdev):
7492 """WPS and no R-Hash1 in M4"""
7493 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7494
7495 logger.debug("Send M4 to STA")
7496 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7497 attrs += build_attr_msg_type(WPS_M4)
7498 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7499 #attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7500 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7501 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7502 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7503 attrs += build_attr_authenticator(authkey, m3, attrs)
7504 m4 = build_eap_wsc(1, eap_id, attrs)
7505 send_wsc_msg(dev[0], bssid, m4)
7506 eap_id = (eap_id + 1) % 256
7507
7508 logger.debug("Receive M5 (NACK) from STA")
7509 msg = get_wsc_msg(dev[0])
7510 if msg['wsc_opcode'] != WSC_NACK:
7511 raise Exception("Unexpected message - expected WSC_Nack")
7512
7513 dev[0].request("WPS_CANCEL")
7514 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7515 dev[0].wait_disconnected()
7516
7517 def test_wps_ext_proto_m4_missing_r_hash2(dev, apdev):
7518 """WPS and no R-Hash2 in M4"""
7519 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7520
7521 logger.debug("Send M4 to STA")
7522 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7523 attrs += build_attr_msg_type(WPS_M4)
7524 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7525 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7526 #attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7527 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7528 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7529 attrs += build_attr_authenticator(authkey, m3, attrs)
7530 m4 = build_eap_wsc(1, eap_id, attrs)
7531 send_wsc_msg(dev[0], bssid, m4)
7532 eap_id = (eap_id + 1) % 256
7533
7534 logger.debug("Receive M5 (NACK) from STA")
7535 msg = get_wsc_msg(dev[0])
7536 if msg['wsc_opcode'] != WSC_NACK:
7537 raise Exception("Unexpected message - expected WSC_Nack")
7538
7539 dev[0].request("WPS_CANCEL")
7540 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7541 dev[0].wait_disconnected()
7542
7543 def test_wps_ext_proto_m4_missing_r_snonce1(dev, apdev):
7544 """WPS and no R-SNonce1 in M4"""
7545 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7546
7547 logger.debug("Send M4 to STA")
7548 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7549 attrs += build_attr_msg_type(WPS_M4)
7550 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7551 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7552 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7553 #data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7554 data = b''
7555 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7556 attrs += build_attr_authenticator(authkey, m3, attrs)
7557 m4 = build_eap_wsc(1, eap_id, attrs)
7558 send_wsc_msg(dev[0], bssid, m4)
7559 eap_id = (eap_id + 1) % 256
7560
7561 logger.debug("Receive M5 (NACK) from STA")
7562 msg = get_wsc_msg(dev[0])
7563 if msg['wsc_opcode'] != WSC_NACK:
7564 raise Exception("Unexpected message - expected WSC_Nack")
7565
7566 dev[0].request("WPS_CANCEL")
7567 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7568 dev[0].wait_disconnected()
7569
7570 def test_wps_ext_proto_m4_invalid_pad_string(dev, apdev):
7571 """WPS and invalid pad string in M4"""
7572 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7573
7574 logger.debug("Send M4 to STA")
7575 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7576 attrs += build_attr_msg_type(WPS_M4)
7577 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7578 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7579 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7580 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7581
7582 m = hmac.new(authkey, data, hashlib.sha256)
7583 kwa = m.digest()[0:8]
7584 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7585 iv = 16*b'\x99'
7586 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7587 pad_len = 16 - len(data) % 16
7588 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', pad_len - 1)
7589 data += ps
7590 wrapped = aes.encrypt(data)
7591 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7592
7593 attrs += build_attr_authenticator(authkey, m3, attrs)
7594 m4 = build_eap_wsc(1, eap_id, attrs)
7595 send_wsc_msg(dev[0], bssid, m4)
7596 eap_id = (eap_id + 1) % 256
7597
7598 logger.debug("Receive M5 (NACK) from STA")
7599 msg = get_wsc_msg(dev[0])
7600 if msg['wsc_opcode'] != WSC_NACK:
7601 raise Exception("Unexpected message - expected WSC_Nack")
7602
7603 dev[0].request("WPS_CANCEL")
7604 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7605 dev[0].wait_disconnected()
7606
7607 def test_wps_ext_proto_m4_invalid_pad_value(dev, apdev):
7608 """WPS and invalid pad value in M4"""
7609 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7610
7611 logger.debug("Send M4 to STA")
7612 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7613 attrs += build_attr_msg_type(WPS_M4)
7614 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7615 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7616 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7617 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7618
7619 m = hmac.new(authkey, data, hashlib.sha256)
7620 kwa = m.digest()[0:8]
7621 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7622 iv = 16*b'\x99'
7623 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7624 pad_len = 16 - len(data) % 16
7625 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', 255)
7626 data += ps
7627 wrapped = aes.encrypt(data)
7628 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7629
7630 attrs += build_attr_authenticator(authkey, m3, attrs)
7631 m4 = build_eap_wsc(1, eap_id, attrs)
7632 send_wsc_msg(dev[0], bssid, m4)
7633 eap_id = (eap_id + 1) % 256
7634
7635 logger.debug("Receive M5 (NACK) from STA")
7636 msg = get_wsc_msg(dev[0])
7637 if msg['wsc_opcode'] != WSC_NACK:
7638 raise Exception("Unexpected message - expected WSC_Nack")
7639
7640 dev[0].request("WPS_CANCEL")
7641 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7642 dev[0].wait_disconnected()
7643
7644 def test_wps_ext_proto_m4_no_encr_settings(dev, apdev):
7645 """WPS and no Encr Settings in M4"""
7646 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7647
7648 logger.debug("Send M4 to STA")
7649 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7650 attrs += build_attr_msg_type(WPS_M4)
7651 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7652 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7653 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7654 attrs += build_attr_authenticator(authkey, m3, attrs)
7655 m4 = build_eap_wsc(1, eap_id, attrs)
7656 send_wsc_msg(dev[0], bssid, m4)
7657 eap_id = (eap_id + 1) % 256
7658
7659 logger.debug("Receive M5 (NACK) from STA")
7660 msg = get_wsc_msg(dev[0])
7661 if msg['wsc_opcode'] != WSC_NACK:
7662 raise Exception("Unexpected message - expected WSC_Nack")
7663
7664 dev[0].request("WPS_CANCEL")
7665 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7666 dev[0].wait_disconnected()
7667
7668 def test_wps_ext_proto_m6_missing_r_snonce2(dev, apdev):
7669 """WPS and no R-SNonce2 in M6"""
7670 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7671
7672 logger.debug("Send M6 to STA")
7673 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7674 attrs += build_attr_msg_type(WPS_M6)
7675 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7676 #data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7677 data = b''
7678 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7679 attrs += build_attr_authenticator(authkey, m5, attrs)
7680 m6 = build_eap_wsc(1, eap_id, attrs)
7681 send_wsc_msg(dev[0], bssid, m6)
7682 eap_id = (eap_id + 1) % 256
7683
7684 logger.debug("Receive M7 (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_m6_no_encr_settings(dev, apdev):
7694 """WPS and no Encr Settings in M6"""
7695 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7696
7697 logger.debug("Send M6 to STA")
7698 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7699 attrs += build_attr_msg_type(WPS_M6)
7700 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7701 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7702 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7703 attrs += build_attr_authenticator(authkey, m5, attrs)
7704 m6 = build_eap_wsc(1, eap_id, attrs)
7705 send_wsc_msg(dev[0], bssid, m6)
7706 eap_id = (eap_id + 1) % 256
7707
7708 logger.debug("Receive M7 (NACK) from STA")
7709 msg = get_wsc_msg(dev[0])
7710 if msg['wsc_opcode'] != WSC_NACK:
7711 raise Exception("Unexpected message - expected WSC_Nack")
7712
7713 dev[0].request("WPS_CANCEL")
7714 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7715 dev[0].wait_disconnected()
7716
7717 def test_wps_ext_proto_m8_no_encr_settings(dev, apdev):
7718 """WPS and no Encr Settings in M6"""
7719 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7720
7721 logger.debug("Send M6 to STA")
7722 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7723 attrs += build_attr_msg_type(WPS_M6)
7724 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7725 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7726 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7727 attrs += build_attr_authenticator(authkey, m5, attrs)
7728 raw_m6_attrs = attrs
7729 m6 = build_eap_wsc(1, eap_id, attrs)
7730 send_wsc_msg(dev[0], bssid, m6)
7731 eap_id = (eap_id + 1) % 256
7732
7733 logger.debug("Receive M7 from STA")
7734 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
7735
7736 logger.debug("Send M8 to STA")
7737 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7738 attrs += build_attr_msg_type(WPS_M8)
7739 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7740 #attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
7741 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7742 raw_m8_attrs = attrs
7743 m8 = build_eap_wsc(1, eap_id, attrs)
7744 send_wsc_msg(dev[0], bssid, m8)
7745
7746 logger.debug("Receive WSC_Done (NACK) from STA")
7747 msg = get_wsc_msg(dev[0])
7748 if msg['wsc_opcode'] != WSC_NACK:
7749 raise Exception("Unexpected message - expected WSC_Nack")
7750
7751 dev[0].request("WPS_CANCEL")
7752 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7753 dev[0].wait_disconnected()
7754
7755 def wps_start_ext_reg(apdev, dev):
7756 addr = dev.own_addr()
7757 bssid = apdev['bssid']
7758 ssid = "test-wps-conf"
7759 appin = "12345670"
7760 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
7761 "wpa_passphrase": "12345678", "wpa": "2",
7762 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
7763 "ap_pin": appin}
7764 hapd = hostapd.add_ap(apdev, params)
7765
7766 dev.scan_for_bss(bssid, freq="2412")
7767 hapd.request("SET ext_eapol_frame_io 1")
7768 dev.request("SET ext_eapol_frame_io 1")
7769
7770 dev.request("WPS_REG " + bssid + " " + appin)
7771
7772 return addr, bssid, hapd
7773
7774 def wps_run_ap_settings_proto(dev, apdev, ap_settings, success):
7775 addr, bssid, hapd = wps_start_ext_reg(apdev[0], dev[0])
7776 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7777 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7778
7779 logger.debug("Receive M1 from AP")
7780 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7781 mac_addr = m1_attrs[ATTR_MAC_ADDR]
7782 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7783 e_pk = m1_attrs[ATTR_PUBLIC_KEY]
7784
7785 appin = '12345670'
7786 uuid_r = 16*b'\x33'
7787 r_nonce = 16*b'\x44'
7788 own_private, r_pk = wsc_dh_init()
7789 authkey, keywrapkey = wsc_dh_kdf(e_pk, own_private, mac_addr, e_nonce,
7790 r_nonce)
7791 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, appin, e_pk, r_pk)
7792
7793 logger.debug("Send M2 to AP")
7794 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, msg['eap_identifier'],
7795 e_nonce, r_nonce, uuid_r, r_pk, eap_code=2)
7796 send_wsc_msg(hapd, addr, m2)
7797
7798 logger.debug("Receive M3 from AP")
7799 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M3)
7800
7801 logger.debug("Send M4 to AP")
7802 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7803 attrs += build_attr_msg_type(WPS_M4)
7804 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7805 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7806 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7807 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7808 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7809 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7810 raw_m4_attrs = attrs
7811 m4 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7812 send_wsc_msg(hapd, addr, m4)
7813
7814 logger.debug("Receive M5 from AP")
7815 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M5)
7816
7817 logger.debug("Send M6 to STA")
7818 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7819 attrs += build_attr_msg_type(WPS_M6)
7820 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7821 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7822 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7823 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
7824 raw_m6_attrs = attrs
7825 m6 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7826 send_wsc_msg(hapd, addr, m6)
7827
7828 logger.debug("Receive M7 from AP")
7829 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M7)
7830
7831 logger.debug("Send M8 to STA")
7832 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7833 attrs += build_attr_msg_type(WPS_M8)
7834 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7835 if ap_settings:
7836 attrs += build_attr_encr_settings(authkey, keywrapkey, ap_settings)
7837 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7838 raw_m8_attrs = attrs
7839 m8 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7840 send_wsc_msg(hapd, addr, m8)
7841
7842 if success:
7843 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
7844 if ev is None:
7845 raise Exception("New AP settings not reported")
7846 logger.debug("Receive WSC_Done from AP")
7847 msg = get_wsc_msg(hapd)
7848 if msg['wsc_opcode'] != WSC_Done:
7849 raise Exception("Unexpected message - expected WSC_Done")
7850
7851 logger.debug("Send WSC_ACK to AP")
7852 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
7853 eap_code=2)
7854 send_wsc_msg(hapd, addr, ack)
7855 dev[0].wait_disconnected()
7856 else:
7857 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
7858 if ev is None:
7859 raise Exception("WPS failure not reported")
7860 logger.debug("Receive WSC_NACK from AP")
7861 msg = get_wsc_msg(hapd)
7862 if msg['wsc_opcode'] != WSC_NACK:
7863 raise Exception("Unexpected message - expected WSC_NACK")
7864
7865 logger.debug("Send WSC_NACK to AP")
7866 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7867 eap_code=2)
7868 send_wsc_msg(hapd, addr, nack)
7869 dev[0].wait_disconnected()
7870
7871 def test_wps_ext_ap_settings_success(dev, apdev):
7872 """WPS and AP Settings: success"""
7873 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7874 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7875 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7876 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7877 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7878 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7879 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7880
7881 @remote_compatible
7882 def test_wps_ext_ap_settings_missing(dev, apdev):
7883 """WPS and AP Settings: missing"""
7884 wps_run_ap_settings_proto(dev, apdev, None, False)
7885
7886 @remote_compatible
7887 def test_wps_ext_ap_settings_mac_addr_mismatch(dev, apdev):
7888 """WPS and AP Settings: MAC Address mismatch"""
7889 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7890 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7891 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7892 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7893 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7894 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, '\x00\x00\x00\x00\x00\x00')
7895 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7896
7897 @remote_compatible
7898 def test_wps_ext_ap_settings_mac_addr_missing(dev, apdev):
7899 """WPS and AP Settings: missing MAC Address"""
7900 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7901 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7902 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7903 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7904 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7905 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7906
7907 @remote_compatible
7908 def test_wps_ext_ap_settings_reject_encr_type(dev, apdev):
7909 """WPS and AP Settings: reject Encr Type"""
7910 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7911 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7912 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7913 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x00')
7914 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7915 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7916 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7917
7918 @remote_compatible
7919 def test_wps_ext_ap_settings_m2d(dev, apdev):
7920 """WPS and AP Settings: M2D"""
7921 addr, bssid, hapd = wps_start_ext_reg(apdev[0], dev[0])
7922 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7923 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7924
7925 logger.debug("Receive M1 from AP")
7926 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7927 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7928
7929 r_nonce = 16*'\x44'
7930 uuid_r = 16*'\x33'
7931
7932 logger.debug("Send M2D to AP")
7933 m2d, raw_m2d_attrs = build_m2d(raw_m1_attrs, msg['eap_identifier'],
7934 e_nonce, r_nonce, uuid_r,
7935 dev_pw_id='\x00\x00', eap_code=2)
7936 send_wsc_msg(hapd, addr, m2d)
7937
7938 ev = hapd.wait_event(["WPS-M2D"], timeout=5)
7939 if ev is None:
7940 raise Exception("M2D not reported")
7941
7942 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7943
7944 def wps_wait_ap_nack(hapd, dev, e_nonce, r_nonce):
7945 logger.debug("Receive WSC_NACK from AP")
7946 msg = get_wsc_msg(hapd)
7947 if msg['wsc_opcode'] != WSC_NACK:
7948 raise Exception("Unexpected message - expected WSC_NACK")
7949
7950 logger.debug("Send WSC_NACK to AP")
7951 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7952 eap_code=2)
7953 send_wsc_msg(hapd, dev.own_addr(), nack)
7954 dev.wait_disconnected()
7955
7956 @remote_compatible
7957 def test_wps_ext_m3_missing_e_hash1(dev, apdev):
7958 """WPS proto: M3 missing E-Hash1"""
7959 pin = "12345670"
7960 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7961 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7962 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7963
7964 logger.debug("Receive WSC/Start from AP")
7965 msg = get_wsc_msg(hapd)
7966 if msg['wsc_opcode'] != WSC_Start:
7967 raise Exception("Unexpected Op-Code for WSC/Start")
7968
7969 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7970 uuid_e = 16*b'\x11'
7971 e_nonce = 16*b'\x22'
7972 own_private, e_pk = wsc_dh_init()
7973
7974 logger.debug("Send M1 to AP")
7975 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7976 e_nonce, e_pk)
7977 send_wsc_msg(hapd, addr, m1)
7978
7979 logger.debug("Receive M2 from AP")
7980 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7981 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7982 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7983
7984 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7985 r_nonce)
7986 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7987
7988 logger.debug("Send M3 to AP")
7989 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7990 attrs += build_attr_msg_type(WPS_M3)
7991 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7992 #attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7993 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7994 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7995 raw_m3_attrs = attrs
7996 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7997 send_wsc_msg(hapd, addr, m3)
7998
7999 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8000
8001 @remote_compatible
8002 def test_wps_ext_m3_missing_e_hash2(dev, apdev):
8003 """WPS proto: M3 missing E-Hash2"""
8004 pin = "12345670"
8005 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8006 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8007 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8008
8009 logger.debug("Receive WSC/Start from AP")
8010 msg = get_wsc_msg(hapd)
8011 if msg['wsc_opcode'] != WSC_Start:
8012 raise Exception("Unexpected Op-Code for WSC/Start")
8013
8014 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8015 uuid_e = 16*b'\x11'
8016 e_nonce = 16*b'\x22'
8017 own_private, e_pk = wsc_dh_init()
8018
8019 logger.debug("Send M1 to AP")
8020 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8021 e_nonce, e_pk)
8022 send_wsc_msg(hapd, addr, m1)
8023
8024 logger.debug("Receive M2 from AP")
8025 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8026 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8027 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8028
8029 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8030 r_nonce)
8031 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8032
8033 logger.debug("Send M3 to AP")
8034 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8035 attrs += build_attr_msg_type(WPS_M3)
8036 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8037 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8038 #attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8039 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8040 raw_m3_attrs = attrs
8041 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8042 send_wsc_msg(hapd, addr, m3)
8043
8044 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8045
8046 @remote_compatible
8047 def test_wps_ext_m5_missing_e_snonce1(dev, apdev):
8048 """WPS proto: M5 missing E-SNonce1"""
8049 pin = "12345670"
8050 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8051 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8052 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8053
8054 logger.debug("Receive WSC/Start from AP")
8055 msg = get_wsc_msg(hapd)
8056 if msg['wsc_opcode'] != WSC_Start:
8057 raise Exception("Unexpected Op-Code for WSC/Start")
8058
8059 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8060 uuid_e = 16*b'\x11'
8061 e_nonce = 16*b'\x22'
8062 own_private, e_pk = wsc_dh_init()
8063
8064 logger.debug("Send M1 to AP")
8065 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8066 e_nonce, e_pk)
8067 send_wsc_msg(hapd, addr, m1)
8068
8069 logger.debug("Receive M2 from AP")
8070 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8071 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8072 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8073
8074 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8075 r_nonce)
8076 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8077
8078 logger.debug("Send M3 to AP")
8079 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8080 attrs += build_attr_msg_type(WPS_M3)
8081 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8082 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8083 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8084 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8085 raw_m3_attrs = attrs
8086 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8087 send_wsc_msg(hapd, addr, m3)
8088
8089 logger.debug("Receive M4 from AP")
8090 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8091
8092 logger.debug("Send M5 to AP")
8093 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8094 attrs += build_attr_msg_type(WPS_M5)
8095 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8096 #data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8097 data = b''
8098 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8099 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8100 raw_m5_attrs = attrs
8101 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8102 send_wsc_msg(hapd, addr, m5)
8103
8104 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8105
8106 @remote_compatible
8107 def test_wps_ext_m5_e_snonce1_mismatch(dev, apdev):
8108 """WPS proto: M5 E-SNonce1 mismatch"""
8109 pin = "12345670"
8110 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8111 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8112 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8113
8114 logger.debug("Receive WSC/Start from AP")
8115 msg = get_wsc_msg(hapd)
8116 if msg['wsc_opcode'] != WSC_Start:
8117 raise Exception("Unexpected Op-Code for WSC/Start")
8118
8119 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8120 uuid_e = 16*b'\x11'
8121 e_nonce = 16*b'\x22'
8122 own_private, e_pk = wsc_dh_init()
8123
8124 logger.debug("Send M1 to AP")
8125 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8126 e_nonce, e_pk)
8127 send_wsc_msg(hapd, addr, m1)
8128
8129 logger.debug("Receive M2 from AP")
8130 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8131 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8132 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8133
8134 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8135 r_nonce)
8136 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8137
8138 logger.debug("Send M3 to AP")
8139 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8140 attrs += build_attr_msg_type(WPS_M3)
8141 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8142 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8143 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8144 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8145 raw_m3_attrs = attrs
8146 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8147 send_wsc_msg(hapd, addr, m3)
8148
8149 logger.debug("Receive M4 from AP")
8150 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8151
8152 logger.debug("Send M5 to AP")
8153 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8154 attrs += build_attr_msg_type(WPS_M5)
8155 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8156 data = build_wsc_attr(ATTR_E_SNONCE1, 16*'\x00')
8157 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8158 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8159 raw_m5_attrs = attrs
8160 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8161 send_wsc_msg(hapd, addr, m5)
8162
8163 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8164
8165 def test_wps_ext_m7_missing_e_snonce2(dev, apdev):
8166 """WPS proto: M7 missing E-SNonce2"""
8167 pin = "12345670"
8168 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8169 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8170 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8171
8172 logger.debug("Receive WSC/Start from AP")
8173 msg = get_wsc_msg(hapd)
8174 if msg['wsc_opcode'] != WSC_Start:
8175 raise Exception("Unexpected Op-Code for WSC/Start")
8176
8177 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8178 uuid_e = 16*b'\x11'
8179 e_nonce = 16*b'\x22'
8180 own_private, e_pk = wsc_dh_init()
8181
8182 logger.debug("Send M1 to AP")
8183 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8184 e_nonce, e_pk)
8185 send_wsc_msg(hapd, addr, m1)
8186
8187 logger.debug("Receive M2 from AP")
8188 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8189 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8190 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8191
8192 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8193 r_nonce)
8194 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8195
8196 logger.debug("Send M3 to AP")
8197 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8198 attrs += build_attr_msg_type(WPS_M3)
8199 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8200 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8201 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8202 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8203 raw_m3_attrs = attrs
8204 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8205 send_wsc_msg(hapd, addr, m3)
8206
8207 logger.debug("Receive M4 from AP")
8208 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8209
8210 logger.debug("Send M5 to AP")
8211 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8212 attrs += build_attr_msg_type(WPS_M5)
8213 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8214 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8215 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8216 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8217 raw_m5_attrs = attrs
8218 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8219 send_wsc_msg(hapd, addr, m5)
8220
8221 logger.debug("Receive M6 from AP")
8222 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8223
8224 logger.debug("Send M7 to AP")
8225 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8226 attrs += build_attr_msg_type(WPS_M7)
8227 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8228 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
8229 data = b''
8230 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8231 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8232 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8233 raw_m7_attrs = attrs
8234 send_wsc_msg(hapd, addr, m7)
8235
8236 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8237
8238 @remote_compatible
8239 def test_wps_ext_m7_e_snonce2_mismatch(dev, apdev):
8240 """WPS proto: M7 E-SNonce2 mismatch"""
8241 pin = "12345670"
8242 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8243 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8244 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8245
8246 logger.debug("Receive WSC/Start from AP")
8247 msg = get_wsc_msg(hapd)
8248 if msg['wsc_opcode'] != WSC_Start:
8249 raise Exception("Unexpected Op-Code for WSC/Start")
8250
8251 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8252 uuid_e = 16*b'\x11'
8253 e_nonce = 16*b'\x22'
8254 own_private, e_pk = wsc_dh_init()
8255
8256 logger.debug("Send M1 to AP")
8257 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8258 e_nonce, e_pk)
8259 send_wsc_msg(hapd, addr, m1)
8260
8261 logger.debug("Receive M2 from AP")
8262 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8263 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8264 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8265
8266 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8267 r_nonce)
8268 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8269
8270 logger.debug("Send M3 to AP")
8271 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8272 attrs += build_attr_msg_type(WPS_M3)
8273 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8274 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8275 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8276 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8277 raw_m3_attrs = attrs
8278 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8279 send_wsc_msg(hapd, addr, m3)
8280
8281 logger.debug("Receive M4 from AP")
8282 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8283
8284 logger.debug("Send M5 to AP")
8285 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8286 attrs += build_attr_msg_type(WPS_M5)
8287 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8288 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8289 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8290 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8291 raw_m5_attrs = attrs
8292 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8293 send_wsc_msg(hapd, addr, m5)
8294
8295 logger.debug("Receive M6 from AP")
8296 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8297
8298 logger.debug("Send M7 to AP")
8299 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8300 attrs += build_attr_msg_type(WPS_M7)
8301 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8302 data = build_wsc_attr(ATTR_E_SNONCE2, 16*'\x00')
8303 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8304 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8305 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8306 raw_m7_attrs = attrs
8307 send_wsc_msg(hapd, addr, m7)
8308
8309 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8310
8311 @remote_compatible
8312 def test_wps_ext_m1_pubkey_oom(dev, apdev):
8313 """WPS proto: M1 PubKey OOM"""
8314 pin = "12345670"
8315 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8316 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8317 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8318
8319 logger.debug("Receive WSC/Start from AP")
8320 msg = get_wsc_msg(hapd)
8321 if msg['wsc_opcode'] != WSC_Start:
8322 raise Exception("Unexpected Op-Code for WSC/Start")
8323
8324 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8325 uuid_e = 16*'\x11'
8326 e_nonce = 16*'\x22'
8327 own_private, e_pk = wsc_dh_init()
8328
8329 logger.debug("Send M1 to AP")
8330 with alloc_fail(hapd, 1, "wpabuf_alloc_copy;wps_process_pubkey"):
8331 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8332 e_nonce, e_pk)
8333 send_wsc_msg(hapd, addr, m1)
8334 wps_wait_eap_failure(hapd, dev[0])
8335
8336 def wps_wait_eap_failure(hapd, dev):
8337 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
8338 if ev is None:
8339 raise Exception("EAP-Failure not reported")
8340 dev.wait_disconnected()
8341
8342 @remote_compatible
8343 def test_wps_ext_m3_m1(dev, apdev):
8344 """WPS proto: M3 replaced with M1"""
8345 pin = "12345670"
8346 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8347 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8348 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8349
8350 logger.debug("Receive WSC/Start from AP")
8351 msg = get_wsc_msg(hapd)
8352 if msg['wsc_opcode'] != WSC_Start:
8353 raise Exception("Unexpected Op-Code for WSC/Start")
8354
8355 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8356 uuid_e = 16*b'\x11'
8357 e_nonce = 16*b'\x22'
8358 own_private, e_pk = wsc_dh_init()
8359
8360 logger.debug("Send M1 to AP")
8361 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8362 e_nonce, e_pk)
8363 send_wsc_msg(hapd, addr, m1)
8364
8365 logger.debug("Receive M2 from AP")
8366 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8367 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8368 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8369
8370 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8371 r_nonce)
8372 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8373
8374 logger.debug("Send M3(M1) to AP")
8375 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8376 attrs += build_attr_msg_type(WPS_M1)
8377 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8378 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8379 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8380 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8381 raw_m3_attrs = attrs
8382 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8383 send_wsc_msg(hapd, addr, m3)
8384
8385 wps_wait_eap_failure(hapd, dev[0])
8386
8387 @remote_compatible
8388 def test_wps_ext_m5_m3(dev, apdev):
8389 """WPS proto: M5 replaced with M3"""
8390 pin = "12345670"
8391 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8392 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8393 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8394
8395 logger.debug("Receive WSC/Start from AP")
8396 msg = get_wsc_msg(hapd)
8397 if msg['wsc_opcode'] != WSC_Start:
8398 raise Exception("Unexpected Op-Code for WSC/Start")
8399
8400 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8401 uuid_e = 16*b'\x11'
8402 e_nonce = 16*b'\x22'
8403 own_private, e_pk = wsc_dh_init()
8404
8405 logger.debug("Send M1 to AP")
8406 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8407 e_nonce, e_pk)
8408 send_wsc_msg(hapd, addr, m1)
8409
8410 logger.debug("Receive M2 from AP")
8411 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8412 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8413 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8414
8415 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8416 r_nonce)
8417 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8418
8419 logger.debug("Send M3 to AP")
8420 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8421 attrs += build_attr_msg_type(WPS_M3)
8422 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8423 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8424 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8425 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8426 raw_m3_attrs = attrs
8427 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8428 send_wsc_msg(hapd, addr, m3)
8429
8430 logger.debug("Receive M4 from AP")
8431 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8432
8433 logger.debug("Send M5(M3) to AP")
8434 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8435 attrs += build_attr_msg_type(WPS_M3)
8436 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8437 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8438 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8439 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8440 raw_m5_attrs = attrs
8441 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8442 send_wsc_msg(hapd, addr, m5)
8443
8444 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8445
8446 @remote_compatible
8447 def test_wps_ext_m3_m2(dev, apdev):
8448 """WPS proto: M3 replaced with M2"""
8449 pin = "12345670"
8450 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8451 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8452 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8453
8454 logger.debug("Receive WSC/Start from AP")
8455 msg = get_wsc_msg(hapd)
8456 if msg['wsc_opcode'] != WSC_Start:
8457 raise Exception("Unexpected Op-Code for WSC/Start")
8458
8459 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8460 uuid_e = 16*b'\x11'
8461 e_nonce = 16*b'\x22'
8462 own_private, e_pk = wsc_dh_init()
8463
8464 logger.debug("Send M1 to AP")
8465 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8466 e_nonce, e_pk)
8467 send_wsc_msg(hapd, addr, m1)
8468
8469 logger.debug("Receive M2 from AP")
8470 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8471 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8472 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8473
8474 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8475 r_nonce)
8476 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8477
8478 logger.debug("Send M3(M2) to AP")
8479 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8480 attrs += build_attr_msg_type(WPS_M2)
8481 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8482 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8483 raw_m3_attrs = attrs
8484 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8485 send_wsc_msg(hapd, addr, m3)
8486
8487 wps_wait_eap_failure(hapd, dev[0])
8488
8489 @remote_compatible
8490 def test_wps_ext_m3_m5(dev, apdev):
8491 """WPS proto: M3 replaced with M5"""
8492 pin = "12345670"
8493 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8494 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8495 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8496
8497 logger.debug("Receive WSC/Start from AP")
8498 msg = get_wsc_msg(hapd)
8499 if msg['wsc_opcode'] != WSC_Start:
8500 raise Exception("Unexpected Op-Code for WSC/Start")
8501
8502 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8503 uuid_e = 16*b'\x11'
8504 e_nonce = 16*b'\x22'
8505 own_private, e_pk = wsc_dh_init()
8506
8507 logger.debug("Send M1 to AP")
8508 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8509 e_nonce, e_pk)
8510 send_wsc_msg(hapd, addr, m1)
8511
8512 logger.debug("Receive M2 from AP")
8513 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8514 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8515 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8516
8517 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8518 r_nonce)
8519 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8520
8521 logger.debug("Send M3(M5) to AP")
8522 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8523 attrs += build_attr_msg_type(WPS_M5)
8524 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8525 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8526 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8527 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8528 raw_m3_attrs = attrs
8529 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8530 send_wsc_msg(hapd, addr, m3)
8531
8532 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8533
8534 @remote_compatible
8535 def test_wps_ext_m3_m7(dev, apdev):
8536 """WPS proto: M3 replaced with M7"""
8537 pin = "12345670"
8538 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8539 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8540 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8541
8542 logger.debug("Receive WSC/Start from AP")
8543 msg = get_wsc_msg(hapd)
8544 if msg['wsc_opcode'] != WSC_Start:
8545 raise Exception("Unexpected Op-Code for WSC/Start")
8546
8547 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8548 uuid_e = 16*b'\x11'
8549 e_nonce = 16*b'\x22'
8550 own_private, e_pk = wsc_dh_init()
8551
8552 logger.debug("Send M1 to AP")
8553 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8554 e_nonce, e_pk)
8555 send_wsc_msg(hapd, addr, m1)
8556
8557 logger.debug("Receive M2 from AP")
8558 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8559 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8560 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8561
8562 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8563 r_nonce)
8564 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8565
8566 logger.debug("Send M3(M7) to AP")
8567 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8568 attrs += build_attr_msg_type(WPS_M7)
8569 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8570 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8571 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8572 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8573 raw_m3_attrs = attrs
8574 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8575 send_wsc_msg(hapd, addr, m3)
8576
8577 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8578
8579 @remote_compatible
8580 def test_wps_ext_m3_done(dev, apdev):
8581 """WPS proto: M3 replaced with WSC_Done"""
8582 pin = "12345670"
8583 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8584 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8585 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8586
8587 logger.debug("Receive WSC/Start from AP")
8588 msg = get_wsc_msg(hapd)
8589 if msg['wsc_opcode'] != WSC_Start:
8590 raise Exception("Unexpected Op-Code for WSC/Start")
8591
8592 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8593 uuid_e = 16*b'\x11'
8594 e_nonce = 16*b'\x22'
8595 own_private, e_pk = wsc_dh_init()
8596
8597 logger.debug("Send M1 to AP")
8598 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8599 e_nonce, e_pk)
8600 send_wsc_msg(hapd, addr, m1)
8601
8602 logger.debug("Receive M2 from AP")
8603 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8604 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8605 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8606
8607 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8608 r_nonce)
8609 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8610
8611 logger.debug("Send M3(WSC_Done) to AP")
8612 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8613 attrs += build_attr_msg_type(WPS_WSC_DONE)
8614 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8615 raw_m3_attrs = attrs
8616 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8617 send_wsc_msg(hapd, addr, m3)
8618
8619 wps_wait_eap_failure(hapd, dev[0])
8620
8621 @remote_compatible
8622 def test_wps_ext_m2_nack_invalid(dev, apdev):
8623 """WPS proto: M2 followed by invalid NACK"""
8624 pin = "12345670"
8625 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8626 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8627 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8628
8629 logger.debug("Receive WSC/Start from AP")
8630 msg = get_wsc_msg(hapd)
8631 if msg['wsc_opcode'] != WSC_Start:
8632 raise Exception("Unexpected Op-Code for WSC/Start")
8633
8634 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8635 uuid_e = 16*b'\x11'
8636 e_nonce = 16*b'\x22'
8637 own_private, e_pk = wsc_dh_init()
8638
8639 logger.debug("Send M1 to AP")
8640 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8641 e_nonce, e_pk)
8642 send_wsc_msg(hapd, addr, m1)
8643
8644 logger.debug("Receive M2 from AP")
8645 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8646 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8647 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8648
8649 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8650 r_nonce)
8651 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8652
8653 logger.debug("Send WSC_NACK to AP")
8654 attrs = b'\x10\x00\x00'
8655 nack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_NACK)
8656 send_wsc_msg(hapd, addr, nack)
8657
8658 wps_wait_eap_failure(hapd, dev[0])
8659
8660 @remote_compatible
8661 def test_wps_ext_m2_nack_no_msg_type(dev, apdev):
8662 """WPS proto: M2 followed by NACK without Msg Type"""
8663 pin = "12345670"
8664 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8665 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8666 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8667
8668 logger.debug("Receive WSC/Start from AP")
8669 msg = get_wsc_msg(hapd)
8670 if msg['wsc_opcode'] != WSC_Start:
8671 raise Exception("Unexpected Op-Code for WSC/Start")
8672
8673 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8674 uuid_e = 16*b'\x11'
8675 e_nonce = 16*b'\x22'
8676 own_private, e_pk = wsc_dh_init()
8677
8678 logger.debug("Send M1 to AP")
8679 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8680 e_nonce, e_pk)
8681 send_wsc_msg(hapd, addr, m1)
8682
8683 logger.debug("Receive M2 from AP")
8684 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8685 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8686 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8687
8688 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8689 r_nonce)
8690 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8691
8692 logger.debug("Send WSC_NACK to AP")
8693 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8694 msg_type=None, eap_code=2)
8695 send_wsc_msg(hapd, addr, nack)
8696
8697 wps_wait_eap_failure(hapd, dev[0])
8698
8699 @remote_compatible
8700 def test_wps_ext_m2_nack_invalid_msg_type(dev, apdev):
8701 """WPS proto: M2 followed by NACK with invalid Msg Type"""
8702 pin = "12345670"
8703 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8704 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8705 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8706
8707 logger.debug("Receive WSC/Start from AP")
8708 msg = get_wsc_msg(hapd)
8709 if msg['wsc_opcode'] != WSC_Start:
8710 raise Exception("Unexpected Op-Code for WSC/Start")
8711
8712 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8713 uuid_e = 16*b'\x11'
8714 e_nonce = 16*b'\x22'
8715 own_private, e_pk = wsc_dh_init()
8716
8717 logger.debug("Send M1 to AP")
8718 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8719 e_nonce, e_pk)
8720 send_wsc_msg(hapd, addr, m1)
8721
8722 logger.debug("Receive M2 from AP")
8723 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8724 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8725 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8726
8727 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8728 r_nonce)
8729 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8730
8731 logger.debug("Send WSC_NACK to AP")
8732 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8733 msg_type=WPS_WSC_ACK, eap_code=2)
8734 send_wsc_msg(hapd, addr, nack)
8735
8736 wps_wait_eap_failure(hapd, dev[0])
8737
8738 @remote_compatible
8739 def test_wps_ext_m2_nack_e_nonce_mismatch(dev, apdev):
8740 """WPS proto: M2 followed by NACK with e-nonce mismatch"""
8741 pin = "12345670"
8742 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8743 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8744 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8745
8746 logger.debug("Receive WSC/Start from AP")
8747 msg = get_wsc_msg(hapd)
8748 if msg['wsc_opcode'] != WSC_Start:
8749 raise Exception("Unexpected Op-Code for WSC/Start")
8750
8751 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8752 uuid_e = 16*b'\x11'
8753 e_nonce = 16*b'\x22'
8754 own_private, e_pk = wsc_dh_init()
8755
8756 logger.debug("Send M1 to AP")
8757 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8758 e_nonce, e_pk)
8759 send_wsc_msg(hapd, addr, m1)
8760
8761 logger.debug("Receive M2 from AP")
8762 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8763 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8764 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8765
8766 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8767 r_nonce)
8768 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8769
8770 logger.debug("Send WSC_NACK to AP")
8771 nack, attrs = build_nack(msg['eap_identifier'], 16*b'\x00', r_nonce,
8772 eap_code=2)
8773 send_wsc_msg(hapd, addr, nack)
8774
8775 wps_wait_eap_failure(hapd, dev[0])
8776
8777 @remote_compatible
8778 def test_wps_ext_m2_nack_no_config_error(dev, apdev):
8779 """WPS proto: M2 followed by NACK without Config Error"""
8780 pin = "12345670"
8781 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8782 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8783 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8784
8785 logger.debug("Receive WSC/Start from AP")
8786 msg = get_wsc_msg(hapd)
8787 if msg['wsc_opcode'] != WSC_Start:
8788 raise Exception("Unexpected Op-Code for WSC/Start")
8789
8790 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8791 uuid_e = 16*b'\x11'
8792 e_nonce = 16*b'\x22'
8793 own_private, e_pk = wsc_dh_init()
8794
8795 logger.debug("Send M1 to AP")
8796 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8797 e_nonce, e_pk)
8798 send_wsc_msg(hapd, addr, m1)
8799
8800 logger.debug("Receive M2 from AP")
8801 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8802 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8803 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8804
8805 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8806 r_nonce)
8807 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8808
8809 logger.debug("Send WSC_NACK to AP")
8810 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8811 config_error=None, eap_code=2)
8812 send_wsc_msg(hapd, addr, nack)
8813
8814 wps_wait_eap_failure(hapd, dev[0])
8815
8816 @remote_compatible
8817 def test_wps_ext_m2_ack_invalid(dev, apdev):
8818 """WPS proto: M2 followed by invalid ACK"""
8819 pin = "12345670"
8820 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8821 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8822 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8823
8824 logger.debug("Receive WSC/Start from AP")
8825 msg = get_wsc_msg(hapd)
8826 if msg['wsc_opcode'] != WSC_Start:
8827 raise Exception("Unexpected Op-Code for WSC/Start")
8828
8829 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8830 uuid_e = 16*b'\x11'
8831 e_nonce = 16*b'\x22'
8832 own_private, e_pk = wsc_dh_init()
8833
8834 logger.debug("Send M1 to AP")
8835 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8836 e_nonce, e_pk)
8837 send_wsc_msg(hapd, addr, m1)
8838
8839 logger.debug("Receive M2 from AP")
8840 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8841 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8842 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8843
8844 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8845 r_nonce)
8846 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8847
8848 logger.debug("Send WSC_ACK to AP")
8849 attrs = b'\x10\x00\x00'
8850 ack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_ACK)
8851 send_wsc_msg(hapd, addr, ack)
8852
8853 wps_wait_eap_failure(hapd, dev[0])
8854
8855 @remote_compatible
8856 def test_wps_ext_m2_ack(dev, apdev):
8857 """WPS proto: M2 followed by ACK"""
8858 pin = "12345670"
8859 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8860 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8861 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8862
8863 logger.debug("Receive WSC/Start from AP")
8864 msg = get_wsc_msg(hapd)
8865 if msg['wsc_opcode'] != WSC_Start:
8866 raise Exception("Unexpected Op-Code for WSC/Start")
8867
8868 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8869 uuid_e = 16*b'\x11'
8870 e_nonce = 16*b'\x22'
8871 own_private, e_pk = wsc_dh_init()
8872
8873 logger.debug("Send M1 to AP")
8874 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8875 e_nonce, e_pk)
8876 send_wsc_msg(hapd, addr, m1)
8877
8878 logger.debug("Receive M2 from AP")
8879 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8880 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8881 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8882
8883 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8884 r_nonce)
8885 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8886
8887 logger.debug("Send WSC_ACK to AP")
8888 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce, eap_code=2)
8889 send_wsc_msg(hapd, addr, ack)
8890
8891 wps_wait_eap_failure(hapd, dev[0])
8892
8893 @remote_compatible
8894 def test_wps_ext_m2_ack_no_msg_type(dev, apdev):
8895 """WPS proto: M2 followed by ACK missing Msg Type"""
8896 pin = "12345670"
8897 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8898 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8899 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8900
8901 logger.debug("Receive WSC/Start from AP")
8902 msg = get_wsc_msg(hapd)
8903 if msg['wsc_opcode'] != WSC_Start:
8904 raise Exception("Unexpected Op-Code for WSC/Start")
8905
8906 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8907 uuid_e = 16*b'\x11'
8908 e_nonce = 16*b'\x22'
8909 own_private, e_pk = wsc_dh_init()
8910
8911 logger.debug("Send M1 to AP")
8912 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8913 e_nonce, e_pk)
8914 send_wsc_msg(hapd, addr, m1)
8915
8916 logger.debug("Receive M2 from AP")
8917 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8918 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8919 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8920
8921 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8922 r_nonce)
8923 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8924
8925 logger.debug("Send WSC_ACK to AP")
8926 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8927 msg_type=None, eap_code=2)
8928 send_wsc_msg(hapd, addr, ack)
8929
8930 wps_wait_eap_failure(hapd, dev[0])
8931
8932 @remote_compatible
8933 def test_wps_ext_m2_ack_invalid_msg_type(dev, apdev):
8934 """WPS proto: M2 followed by ACK with invalid Msg Type"""
8935 pin = "12345670"
8936 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8937 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8938 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8939
8940 logger.debug("Receive WSC/Start from AP")
8941 msg = get_wsc_msg(hapd)
8942 if msg['wsc_opcode'] != WSC_Start:
8943 raise Exception("Unexpected Op-Code for WSC/Start")
8944
8945 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8946 uuid_e = 16*b'\x11'
8947 e_nonce = 16*b'\x22'
8948 own_private, e_pk = wsc_dh_init()
8949
8950 logger.debug("Send M1 to AP")
8951 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8952 e_nonce, e_pk)
8953 send_wsc_msg(hapd, addr, m1)
8954
8955 logger.debug("Receive M2 from AP")
8956 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8957 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8958 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8959
8960 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8961 r_nonce)
8962 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8963
8964 logger.debug("Send WSC_ACK to AP")
8965 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8966 msg_type=WPS_WSC_NACK, eap_code=2)
8967 send_wsc_msg(hapd, addr, ack)
8968
8969 wps_wait_eap_failure(hapd, dev[0])
8970
8971 @remote_compatible
8972 def test_wps_ext_m2_ack_e_nonce_mismatch(dev, apdev):
8973 """WPS proto: M2 followed by ACK with e-nonce mismatch"""
8974 pin = "12345670"
8975 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8976 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8977 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8978
8979 logger.debug("Receive WSC/Start from AP")
8980 msg = get_wsc_msg(hapd)
8981 if msg['wsc_opcode'] != WSC_Start:
8982 raise Exception("Unexpected Op-Code for WSC/Start")
8983
8984 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8985 uuid_e = 16*b'\x11'
8986 e_nonce = 16*b'\x22'
8987 own_private, e_pk = wsc_dh_init()
8988
8989 logger.debug("Send M1 to AP")
8990 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8991 e_nonce, e_pk)
8992 send_wsc_msg(hapd, addr, m1)
8993
8994 logger.debug("Receive M2 from AP")
8995 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8996 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8997 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8998
8999 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9000 r_nonce)
9001 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9002
9003 logger.debug("Send WSC_ACK to AP")
9004 ack, attrs = build_ack(msg['eap_identifier'], 16*b'\x00', r_nonce,
9005 eap_code=2)
9006 send_wsc_msg(hapd, addr, ack)
9007
9008 wps_wait_eap_failure(hapd, dev[0])
9009
9010 @remote_compatible
9011 def test_wps_ext_m1_invalid(dev, apdev):
9012 """WPS proto: M1 failing parsing"""
9013 pin = "12345670"
9014 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9015 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9016 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9017
9018 logger.debug("Receive WSC/Start from AP")
9019 msg = get_wsc_msg(hapd)
9020 if msg['wsc_opcode'] != WSC_Start:
9021 raise Exception("Unexpected Op-Code for WSC/Start")
9022
9023 logger.debug("Send M1 to AP")
9024 attrs = b'\x10\x00\x00'
9025 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9026 send_wsc_msg(hapd, addr, m1)
9027
9028 wps_wait_eap_failure(hapd, dev[0])
9029
9030 def test_wps_ext_m1_missing_msg_type(dev, apdev):
9031 """WPS proto: M1 missing Msg Type"""
9032 pin = "12345670"
9033 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9034 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9035 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9036
9037 logger.debug("Receive WSC/Start from AP")
9038 msg = get_wsc_msg(hapd)
9039 if msg['wsc_opcode'] != WSC_Start:
9040 raise Exception("Unexpected Op-Code for WSC/Start")
9041
9042 logger.debug("Send M1 to AP")
9043 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9044 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9045 send_wsc_msg(hapd, addr, m1)
9046
9047 wps_wait_ap_nack(hapd, dev[0], 16*b'\x00', 16*b'\x00')
9048
9049 def wps_ext_wsc_done(dev, apdev):
9050 pin = "12345670"
9051 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9052 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9053 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9054
9055 logger.debug("Receive WSC/Start from AP")
9056 msg = get_wsc_msg(hapd)
9057 if msg['wsc_opcode'] != WSC_Start:
9058 raise Exception("Unexpected Op-Code for WSC/Start")
9059
9060 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9061 uuid_e = 16*b'\x11'
9062 e_nonce = 16*b'\x22'
9063 own_private, e_pk = wsc_dh_init()
9064
9065 logger.debug("Send M1 to AP")
9066 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9067 e_nonce, e_pk)
9068 send_wsc_msg(hapd, addr, m1)
9069
9070 logger.debug("Receive M2 from AP")
9071 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9072 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9073 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9074
9075 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9076 r_nonce)
9077 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9078
9079 logger.debug("Send M3 to AP")
9080 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9081 attrs += build_attr_msg_type(WPS_M3)
9082 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9083 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9084 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9085 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9086 raw_m3_attrs = attrs
9087 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9088 send_wsc_msg(hapd, addr, m3)
9089
9090 logger.debug("Receive M4 from AP")
9091 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9092
9093 logger.debug("Send M5 to AP")
9094 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9095 attrs += build_attr_msg_type(WPS_M5)
9096 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9097 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9098 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9099 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9100 raw_m5_attrs = attrs
9101 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9102 send_wsc_msg(hapd, addr, m5)
9103
9104 logger.debug("Receive M6 from AP")
9105 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9106
9107 logger.debug("Send M7 to AP")
9108 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9109 attrs += build_attr_msg_type(WPS_M7)
9110 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9111 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9112 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9113 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9114 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9115 raw_m7_attrs = attrs
9116 send_wsc_msg(hapd, addr, m7)
9117
9118 logger.debug("Receive M8 from AP")
9119 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
9120 return hapd, msg, e_nonce, r_nonce
9121
9122 @remote_compatible
9123 def test_wps_ext_wsc_done_invalid(dev, apdev):
9124 """WPS proto: invalid WSC_Done"""
9125 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9126
9127 logger.debug("Send WSC_Done to AP")
9128 attrs = b'\x10\x00\x00'
9129 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9130 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9131
9132 wps_wait_eap_failure(hapd, dev[0])
9133
9134 @remote_compatible
9135 def test_wps_ext_wsc_done_no_msg_type(dev, apdev):
9136 """WPS proto: invalid WSC_Done"""
9137 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9138
9139 logger.debug("Send WSC_Done to AP")
9140 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9141 #attrs += build_attr_msg_type(WPS_WSC_DONE)
9142 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9143 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9144 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9145 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9146
9147 wps_wait_eap_failure(hapd, dev[0])
9148
9149 @remote_compatible
9150 def test_wps_ext_wsc_done_wrong_msg_type(dev, apdev):
9151 """WPS proto: WSC_Done with wrong Msg Type"""
9152 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9153
9154 logger.debug("Send WSC_Done to AP")
9155 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9156 attrs += build_attr_msg_type(WPS_WSC_ACK)
9157 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9158 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9159 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9160 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9161
9162 wps_wait_eap_failure(hapd, dev[0])
9163
9164 @remote_compatible
9165 def test_wps_ext_wsc_done_no_e_nonce(dev, apdev):
9166 """WPS proto: WSC_Done without e_nonce"""
9167 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9168
9169 logger.debug("Send WSC_Done to AP")
9170 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9171 attrs += build_attr_msg_type(WPS_WSC_DONE)
9172 #attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9173 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9174 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9175 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9176
9177 wps_wait_eap_failure(hapd, dev[0])
9178
9179 def test_wps_ext_wsc_done_no_r_nonce(dev, apdev):
9180 """WPS proto: WSC_Done without r_nonce"""
9181 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9182
9183 logger.debug("Send WSC_Done to AP")
9184 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9185 attrs += build_attr_msg_type(WPS_WSC_DONE)
9186 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9187 #attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9188 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9189 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9190
9191 wps_wait_eap_failure(hapd, dev[0])
9192
9193 @remote_compatible
9194 def test_wps_ext_m7_no_encr_settings(dev, apdev):
9195 """WPS proto: M7 without Encr Settings"""
9196 pin = "12345670"
9197 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9198 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9199 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9200
9201 logger.debug("Receive WSC/Start from AP")
9202 msg = get_wsc_msg(hapd)
9203 if msg['wsc_opcode'] != WSC_Start:
9204 raise Exception("Unexpected Op-Code for WSC/Start")
9205
9206 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9207 uuid_e = 16*b'\x11'
9208 e_nonce = 16*b'\x22'
9209 own_private, e_pk = wsc_dh_init()
9210
9211 logger.debug("Send M1 to AP")
9212 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9213 e_nonce, e_pk)
9214 send_wsc_msg(hapd, addr, m1)
9215
9216 logger.debug("Receive M2 from AP")
9217 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9218 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9219 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9220
9221 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9222 r_nonce)
9223 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9224
9225 logger.debug("Send M3 to AP")
9226 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9227 attrs += build_attr_msg_type(WPS_M3)
9228 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9229 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9230 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9231 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9232 raw_m3_attrs = attrs
9233 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9234 send_wsc_msg(hapd, addr, m3)
9235
9236 logger.debug("Receive M4 from AP")
9237 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9238
9239 logger.debug("Send M5 to AP")
9240 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9241 attrs += build_attr_msg_type(WPS_M5)
9242 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9243 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9244 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9245 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9246 raw_m5_attrs = attrs
9247 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9248 send_wsc_msg(hapd, addr, m5)
9249
9250 logger.debug("Receive M6 from AP")
9251 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9252
9253 logger.debug("Send M7 to AP")
9254 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9255 attrs += build_attr_msg_type(WPS_M7)
9256 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9257 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9258 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9259 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9260 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9261 raw_m7_attrs = attrs
9262 send_wsc_msg(hapd, addr, m7)
9263
9264 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
9265
9266 @remote_compatible
9267 def test_wps_ext_m1_workaround(dev, apdev):
9268 """WPS proto: M1 Manufacturer/Model workaround"""
9269 pin = "12345670"
9270 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9271 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9272 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9273
9274 logger.debug("Receive WSC/Start from AP")
9275 msg = get_wsc_msg(hapd)
9276 if msg['wsc_opcode'] != WSC_Start:
9277 raise Exception("Unexpected Op-Code for WSC/Start")
9278
9279 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9280 uuid_e = 16*b'\x11'
9281 e_nonce = 16*b'\x22'
9282 own_private, e_pk = wsc_dh_init()
9283
9284 logger.debug("Send M1 to AP")
9285 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9286 e_nonce, e_pk, manufacturer='Apple TEST',
9287 model_name='AirPort', config_methods=b'\xff\xff')
9288 send_wsc_msg(hapd, addr, m1)
9289
9290 logger.debug("Receive M2 from AP")
9291 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9292
9293 @remote_compatible
9294 def test_ap_wps_disable_enable(dev, apdev):
9295 """WPS and DISABLE/ENABLE AP"""
9296 hapd = wps_start_ap(apdev[0])
9297 hapd.disable()
9298 hapd.enable()
9299 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9300
9301 def test_ap_wps_upnp_web_oom(dev, apdev, params):
9302 """hostapd WPS UPnP web OOM"""
9303 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9304 hapd = add_ssdp_ap(apdev[0], ap_uuid)
9305
9306 location = ssdp_get_location(ap_uuid)
9307 url = urlparse(location)
9308 urls = upnp_get_urls(location)
9309 eventurl = urlparse(urls['event_sub_url'])
9310 ctrlurl = urlparse(urls['control_url'])
9311
9312 conn = HTTPConnection(url.netloc)
9313 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9314 conn.request("GET", "/wps_device.xml")
9315 try:
9316 resp = conn.getresponse()
9317 except:
9318 pass
9319
9320 conn = HTTPConnection(url.netloc)
9321 conn.request("GET", "/unknown")
9322 resp = conn.getresponse()
9323 if resp.status != 404:
9324 raise Exception("Unexpected HTTP result for unknown URL: %d" + resp.status)
9325
9326 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9327 conn.request("GET", "/unknown")
9328 try:
9329 resp = conn.getresponse()
9330 print(resp.status)
9331 except:
9332 pass
9333
9334 conn = HTTPConnection(url.netloc)
9335 conn.request("GET", "/wps_device.xml")
9336 resp = conn.getresponse()
9337 if resp.status != 200:
9338 raise Exception("GET /wps_device.xml failed")
9339
9340 conn = HTTPConnection(url.netloc)
9341 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9342 if resp.status != 200:
9343 raise Exception("GetDeviceInfo failed")
9344
9345 with alloc_fail(hapd, 1, "web_process_get_device_info"):
9346 conn = HTTPConnection(url.netloc)
9347 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9348 if resp.status != 500:
9349 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9350
9351 with alloc_fail(hapd, 1, "wps_build_m1;web_process_get_device_info"):
9352 conn = HTTPConnection(url.netloc)
9353 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9354 if resp.status != 500:
9355 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9356
9357 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_send_reply"):
9358 conn = HTTPConnection(url.netloc)
9359 try:
9360 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9361 except:
9362 pass
9363
9364 conn = HTTPConnection(url.netloc)
9365 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9366 if resp.status != 200:
9367 raise Exception("GetDeviceInfo failed")
9368
9369 # No NewWLANEventType in PutWLANResponse NewMessage
9370 conn = HTTPConnection(url.netloc)
9371 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse", newmsg="foo")
9372 if resp.status != 600:
9373 raise Exception("Unexpected HTTP response: %d" % resp.status)
9374
9375 # No NewWLANEventMAC in PutWLANResponse NewMessage
9376 conn = HTTPConnection(url.netloc)
9377 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9378 newmsg="foo", neweventtype="1")
9379 if resp.status != 600:
9380 raise Exception("Unexpected HTTP response: %d" % resp.status)
9381
9382 # Invalid NewWLANEventMAC in PutWLANResponse NewMessage
9383 conn = HTTPConnection(url.netloc)
9384 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9385 newmsg="foo", neweventtype="1",
9386 neweventmac="foo")
9387 if resp.status != 600:
9388 raise Exception("Unexpected HTTP response: %d" % resp.status)
9389
9390 # Workaround for NewWLANEventMAC in PutWLANResponse NewMessage
9391 # Ignored unexpected PutWLANResponse WLANEventType 1
9392 conn = HTTPConnection(url.netloc)
9393 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9394 newmsg="foo", neweventtype="1",
9395 neweventmac="00.11.22.33.44.55")
9396 if resp.status != 500:
9397 raise Exception("Unexpected HTTP response: %d" % resp.status)
9398
9399 # PutWLANResponse NewMessage with invalid EAP message
9400 conn = HTTPConnection(url.netloc)
9401 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9402 newmsg="foo", neweventtype="2",
9403 neweventmac="00:11:22:33:44:55")
9404 if resp.status != 200:
9405 raise Exception("Unexpected HTTP response: %d" % resp.status)
9406
9407 with alloc_fail(hapd, 1, "web_connection_parse_subscribe"):
9408 conn = HTTPConnection(url.netloc)
9409 headers = {"callback": '<http://127.0.0.1:12345/event>',
9410 "NT": "upnp:event",
9411 "timeout": "Second-1234"}
9412 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9413 try:
9414 resp = conn.getresponse()
9415 except:
9416 pass
9417
9418 with alloc_fail(hapd, 1, "dup_binstr;web_connection_parse_subscribe"):
9419 conn = HTTPConnection(url.netloc)
9420 headers = {"callback": '<http://127.0.0.1:12345/event>',
9421 "NT": "upnp:event",
9422 "timeout": "Second-1234"}
9423 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9424 resp = conn.getresponse()
9425 if resp.status != 500:
9426 raise Exception("Unexpected HTTP response: %d" % resp.status)
9427
9428 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_parse_unsubscribe"):
9429 conn = HTTPConnection(url.netloc)
9430 headers = {"callback": '<http://127.0.0.1:12345/event>',
9431 "NT": "upnp:event",
9432 "timeout": "Second-1234"}
9433 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9434 try:
9435 resp = conn.getresponse()
9436 except:
9437 pass
9438
9439 with alloc_fail(hapd, 1, "web_connection_unimplemented"):
9440 conn = HTTPConnection(url.netloc)
9441 conn.request("HEAD", "/wps_device.xml")
9442 try:
9443 resp = conn.getresponse()
9444 except:
9445 pass
9446
9447 def test_ap_wps_frag_ack_oom(dev, apdev):
9448 """WPS and fragment ack OOM"""
9449 dev[0].request("SET wps_fragment_size 50")
9450 hapd = wps_start_ap(apdev[0])
9451 with alloc_fail(hapd, 1, "eap_wsc_build_frag_ack"):
9452 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
9453
9454 def wait_scan_stopped(dev):
9455 dev.request("ABORT_SCAN")
9456 for i in range(50):
9457 res = dev.get_driver_status_field("scan_state")
9458 if "SCAN_STARTED" not in res and "SCAN_REQUESTED" not in res:
9459 break
9460 logger.debug("Waiting for scan to complete")
9461 time.sleep(0.1)
9462
9463 @remote_compatible
9464 def test_ap_wps_eap_wsc_errors(dev, apdev):
9465 """WPS and EAP-WSC error cases"""
9466 ssid = "test-wps-conf-pin"
9467 appin = "12345670"
9468 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9469 "wpa_passphrase": "12345678", "wpa": "2",
9470 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9471 "fragment_size": "300", "ap_pin": appin}
9472 hapd = hostapd.add_ap(apdev[0], params)
9473 bssid = apdev[0]['bssid']
9474
9475 pin = dev[0].wps_read_pin()
9476 hapd.request("WPS_PIN any " + pin)
9477 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9478 dev[0].dump_monitor()
9479
9480 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK", "CCMP",
9481 "new passphrase", no_wait=True)
9482 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9483 if ev is None:
9484 raise Exception("WPS-FAIL not reported")
9485 dev[0].request("WPS_CANCEL")
9486 dev[0].wait_disconnected()
9487 wait_scan_stopped(dev[0])
9488 dev[0].dump_monitor()
9489
9490 dev[0].wps_reg(bssid, appin, "new ssid", "FOO", "CCMP",
9491 "new passphrase", no_wait=True)
9492 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9493 if ev is None:
9494 raise Exception("WPS-FAIL not reported")
9495 dev[0].request("WPS_CANCEL")
9496 dev[0].wait_disconnected()
9497 wait_scan_stopped(dev[0])
9498 dev[0].dump_monitor()
9499
9500 dev[0].wps_reg(bssid, appin, "new ssid", "WPA2PSK", "FOO",
9501 "new passphrase", no_wait=True)
9502 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9503 if ev is None:
9504 raise Exception("WPS-FAIL not reported")
9505 dev[0].request("WPS_CANCEL")
9506 dev[0].wait_disconnected()
9507 wait_scan_stopped(dev[0])
9508 dev[0].dump_monitor()
9509
9510 dev[0].wps_reg(bssid, appin + "new_key=a", "new ssid", "WPA2PSK", "CCMP",
9511 "new passphrase", no_wait=True)
9512 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9513 if ev is None:
9514 raise Exception("WPS-FAIL not reported")
9515 dev[0].request("WPS_CANCEL")
9516 dev[0].wait_disconnected()
9517 wait_scan_stopped(dev[0])
9518 dev[0].dump_monitor()
9519
9520 tests = ["eap_wsc_init",
9521 "eap_msg_alloc;eap_wsc_build_msg",
9522 "wpabuf_alloc;eap_wsc_process_fragment"]
9523 for func in tests:
9524 with alloc_fail(dev[0], 1, func):
9525 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
9526 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9527 dev[0].request("WPS_CANCEL")
9528 dev[0].wait_disconnected()
9529 wait_scan_stopped(dev[0])
9530 dev[0].dump_monitor()
9531
9532 tests = [(1, "wps_decrypt_encr_settings"),
9533 (2, "hmac_sha256;wps_derive_psk")]
9534 for count, func in tests:
9535 hapd.request("WPS_PIN any " + pin)
9536 with fail_test(dev[0], count, func):
9537 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
9538 wait_fail_trigger(dev[0], "GET_FAIL")
9539 dev[0].request("WPS_CANCEL")
9540 dev[0].wait_disconnected()
9541 wait_scan_stopped(dev[0])
9542 dev[0].dump_monitor()
9543
9544 with alloc_fail(dev[0], 1, "eap_msg_alloc;eap_sm_build_expanded_nak"):
9545 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK",
9546 "CCMP", "new passphrase", no_wait=True)
9547 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9548 dev[0].request("WPS_CANCEL")
9549 dev[0].wait_disconnected()
9550 wait_scan_stopped(dev[0])
9551 dev[0].dump_monitor()
9552
9553 def test_ap_wps_eap_wsc(dev, apdev):
9554 """WPS and EAP-WSC in network profile"""
9555 params = int_eap_server_params()
9556 params["wps_state"] = "2"
9557 hapd = hostapd.add_ap(apdev[0], params)
9558 bssid = apdev[0]['bssid']
9559
9560 logger.info("Unexpected identity")
9561 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9562 eap="WSC", identity="WFA-SimpleConfig-Enrollee-unexpected",
9563 wait_connect=False)
9564 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9565 if ev is None:
9566 raise Exception("No EAP-Failure seen")
9567 dev[0].request("REMOVE_NETWORK all")
9568 dev[0].wait_disconnected()
9569
9570 logger.info("No phase1 parameter")
9571 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9572 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9573 wait_connect=False)
9574 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9575 if ev is None:
9576 raise Exception("Timeout on EAP method start")
9577 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9578 if ev is None:
9579 raise Exception("No EAP-Failure seen")
9580 dev[0].request("REMOVE_NETWORK all")
9581 dev[0].wait_disconnected()
9582
9583 logger.info("No PIN/PBC in phase1")
9584 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9585 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9586 phase1="foo", wait_connect=False)
9587 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9588 if ev is None:
9589 raise Exception("Timeout on EAP method start")
9590 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9591 if ev is None:
9592 raise Exception("No EAP-Failure seen")
9593 dev[0].request("REMOVE_NETWORK all")
9594 dev[0].wait_disconnected()
9595
9596 logger.info("Invalid pkhash in phase1")
9597 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9598 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9599 phase1="foo pkhash=q pbc=1", wait_connect=False)
9600 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9601 if ev is None:
9602 raise Exception("Timeout on EAP method start")
9603 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9604 if ev is None:
9605 raise Exception("No EAP-Failure seen")
9606 dev[0].request("REMOVE_NETWORK all")
9607 dev[0].wait_disconnected()
9608
9609 logger.info("Zero fragment_size")
9610 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9611 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9612 fragment_size="0", phase1="pin=12345670", wait_connect=False)
9613 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9614 if ev is None:
9615 raise Exception("Timeout on EAP method start")
9616 ev = dev[0].wait_event(["WPS-M2D"], timeout=5)
9617 if ev is None:
9618 raise Exception("No M2D seen")
9619 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9620 if ev is None:
9621 raise Exception("No EAP-Failure seen")
9622 dev[0].request("REMOVE_NETWORK all")
9623 dev[0].wait_disconnected()
9624
9625 logger.info("Missing new_auth")
9626 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9627 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9628 phase1="pin=12345670 new_ssid=aa", wait_connect=False)
9629 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9630 if ev is None:
9631 raise Exception("Timeout on EAP method start")
9632 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9633 if ev is None:
9634 raise Exception("No EAP-Failure seen")
9635 dev[0].request("REMOVE_NETWORK all")
9636 dev[0].wait_disconnected()
9637
9638 logger.info("Missing new_encr")
9639 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9640 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9641 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa", wait_connect=False)
9642 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9643 if ev is None:
9644 raise Exception("Timeout on EAP method start")
9645 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9646 if ev is None:
9647 raise Exception("No EAP-Failure seen")
9648 dev[0].request("REMOVE_NETWORK all")
9649 dev[0].wait_disconnected()
9650
9651 logger.info("Missing new_key")
9652 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9653 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9654 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa new_encr=CCMP",
9655 wait_connect=False)
9656 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9657 if ev is None:
9658 raise Exception("Timeout on EAP method start")
9659 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9660 if ev is None:
9661 raise Exception("No EAP-Failure seen")
9662 dev[0].request("REMOVE_NETWORK all")
9663 dev[0].wait_disconnected()
9664
9665 def test_ap_wps_and_bss_limit(dev, apdev):
9666 """WPS and wpa_supplicant BSS entry limit"""
9667 try:
9668 _test_ap_wps_and_bss_limit(dev, apdev)
9669 finally:
9670 dev[0].request("SET bss_max_count 200")
9671 pass
9672
9673 def _test_ap_wps_and_bss_limit(dev, apdev):
9674 params = {"ssid": "test-wps", "eap_server": "1", "wps_state": "2",
9675 "wpa_passphrase": "12345678", "wpa": "2",
9676 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
9677 hapd = hostapd.add_ap(apdev[0], params)
9678
9679 params = {"ssid": "test-wps-2", "eap_server": "1", "wps_state": "2",
9680 "wpa_passphrase": "1234567890", "wpa": "2",
9681 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
9682 hapd2 = hostapd.add_ap(apdev[1], params)
9683
9684 id = dev[1].add_network()
9685 dev[1].set_network(id, "mode", "2")
9686 dev[1].set_network_quoted(id, "ssid", "wpas-ap-no-wps")
9687 dev[1].set_network_quoted(id, "psk", "12345678")
9688 dev[1].set_network(id, "frequency", "2462")
9689 dev[1].set_network(id, "scan_freq", "2462")
9690 dev[1].set_network(id, "wps_disabled", "1")
9691 dev[1].select_network(id)
9692
9693 id = dev[2].add_network()
9694 dev[2].set_network(id, "mode", "2")
9695 dev[2].set_network_quoted(id, "ssid", "wpas-ap")
9696 dev[2].set_network_quoted(id, "psk", "12345678")
9697 dev[2].set_network(id, "frequency", "2437")
9698 dev[2].set_network(id, "scan_freq", "2437")
9699 dev[2].select_network(id)
9700
9701 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9702 wpas.interface_add("wlan5")
9703 id = wpas.add_network()
9704 wpas.set_network(id, "mode", "2")
9705 wpas.set_network_quoted(id, "ssid", "wpas-ap")
9706 wpas.set_network_quoted(id, "psk", "12345678")
9707 wpas.set_network(id, "frequency", "2437")
9708 wpas.set_network(id, "scan_freq", "2437")
9709 wpas.select_network(id)
9710
9711 dev[1].wait_connected()
9712 dev[2].wait_connected()
9713 wpas.wait_connected()
9714 wpas.request("WPS_PIN any 12345670")
9715
9716 hapd.request("WPS_PBC")
9717 hapd2.request("WPS_PBC")
9718
9719 dev[0].request("SET bss_max_count 1")
9720
9721 id = dev[0].add_network()
9722 dev[0].set_network_quoted(id, "ssid", "testing")
9723
9724 id = dev[0].add_network()
9725 dev[0].set_network_quoted(id, "ssid", "testing")
9726 dev[0].set_network(id, "key_mgmt", "WPS")
9727
9728 dev[0].request("WPS_PBC")
9729 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
9730 dev[0].request("WPS_CANCEL")
9731
9732 id = dev[0].add_network()
9733 dev[0].set_network_quoted(id, "ssid", "testing")
9734 dev[0].set_network(id, "key_mgmt", "WPS")
9735
9736 dev[0].scan(freq="2412")
9737
9738 def test_ap_wps_pbc_2ap(dev, apdev):
9739 """WPS PBC with two APs advertising same SSID"""
9740 params = {"ssid": "wps", "eap_server": "1", "wps_state": "2",
9741 "wpa_passphrase": "12345678", "wpa": "2",
9742 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9743 "wps_independent": "1"}
9744 hapd = hostapd.add_ap(apdev[0], params)
9745 params = {"ssid": "wps", "eap_server": "1", "wps_state": "2",
9746 "wpa_passphrase": "123456789", "wpa": "2",
9747 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9748 "wps_independent": "1"}
9749 hapd2 = hostapd.add_ap(apdev[1], params)
9750 hapd.request("WPS_PBC")
9751
9752 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9753 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
9754 wpas.dump_monitor()
9755 wpas.flush_scan_cache()
9756
9757 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
9758 wpas.scan_for_bss(apdev[1]['bssid'], freq="2412")
9759 wpas.request("WPS_PBC")
9760 wpas.wait_connected()
9761 wpas.request("DISCONNECT")
9762 hapd.request("DISABLE")
9763 hapd2.request("DISABLE")
9764 wpas.flush_scan_cache()
9765
9766 def test_ap_wps_er_enrollee_to_conf_ap(dev, apdev):
9767 """WPS ER enrolling a new device to a configured AP"""
9768 try:
9769 _test_ap_wps_er_enrollee_to_conf_ap(dev, apdev)
9770 finally:
9771 dev[0].request("WPS_ER_STOP")
9772
9773 def _test_ap_wps_er_enrollee_to_conf_ap(dev, apdev):
9774 ssid = "wps-er-enrollee-to-conf-ap"
9775 ap_pin = "12345670"
9776 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9777 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9778 "wpa_passphrase": "12345678", "wpa": "2",
9779 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9780 "device_name": "Wireless AP", "manufacturer": "Company",
9781 "model_name": "WAP", "model_number": "123",
9782 "serial_number": "12345", "device_type": "6-0050F204-1",
9783 "os_version": "01020300",
9784 "config_methods": "label push_button",
9785 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
9786 hapd = hostapd.add_ap(apdev[0], params)
9787 bssid = hapd.own_addr()
9788
9789 id = dev[0].connect(ssid, psk="12345678", scan_freq="2412")
9790 dev[0].dump_monitor()
9791
9792 dev[0].request("WPS_ER_START ifname=lo")
9793 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
9794 if ev is None:
9795 raise Exception("AP discovery timed out")
9796 if ap_uuid not in ev:
9797 raise Exception("Expected AP UUID not found")
9798
9799 pin = dev[2].wps_read_pin()
9800 addr2 = dev[2].own_addr()
9801 dev[0].dump_monitor()
9802 dev[2].scan_for_bss(bssid, freq=2412)
9803 dev[2].dump_monitor()
9804 dev[2].request("WPS_PIN %s %s" % (bssid, pin))
9805
9806 for i in range(3):
9807 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
9808 if ev is None:
9809 raise Exception("Enrollee not seen")
9810 if addr2 in ev:
9811 break
9812 if addr2 not in ev:
9813 raise Exception("Unexpected Enrollee MAC address")
9814 dev[0].dump_monitor()
9815
9816 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " " + str(id))
9817 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
9818 dev[2].wait_connected(timeout=30)
9819 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
9820 if ev is None:
9821 raise Exception("WPS ER did not report success")
9822
9823 def test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev):
9824 """WPS ER enrolling a new device to a configured AP (2)"""
9825 try:
9826 _test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev)
9827 finally:
9828 dev[0].request("WPS_ER_STOP")
9829
9830 def _test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev):
9831 ssid = "wps-er-enrollee-to-conf-ap"
9832 ap_pin = "12345670"
9833 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9834 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9835 "wpa_passphrase": "12345678", "wpa": "2",
9836 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9837 "device_name": "Wireless AP", "manufacturer": "Company",
9838 "model_name": "WAP", "model_number": "123",
9839 "serial_number": "12345", "device_type": "6-0050F204-1",
9840 "os_version": "01020300",
9841 "config_methods": "label push_button",
9842 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
9843 hapd = hostapd.add_ap(apdev[0], params)
9844 bssid = hapd.own_addr()
9845
9846 id = dev[0].connect(ssid, psk="12345678", scan_freq="2412")
9847 dev[0].dump_monitor()
9848
9849 dev[0].request("WPS_ER_START ifname=lo")
9850 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
9851 if ev is None:
9852 raise Exception("AP discovery timed out")
9853 if ap_uuid not in ev:
9854 raise Exception("Expected AP UUID not found")
9855
9856 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
9857 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
9858 if ev is None:
9859 raise Exception("AP learn timed out")
9860 if ap_uuid not in ev:
9861 raise Exception("Expected AP UUID not in settings")
9862 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
9863 if ev is None:
9864 raise Exception("WPS-FAIL after AP learn timed out")
9865 time.sleep(0.1)
9866
9867 pin = dev[1].wps_read_pin()
9868 addr1 = dev[1].own_addr()
9869 dev[0].dump_monitor()
9870 dev[0].request("WPS_ER_PIN any " + pin)
9871 time.sleep(0.1)
9872 dev[1].scan_for_bss(bssid, freq=2412)
9873 dev[1].request("WPS_PIN any %s" % pin)
9874 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
9875 if ev is None:
9876 raise Exception("Enrollee did not report success")
9877 dev[1].wait_connected(timeout=15)
9878 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
9879 if ev is None:
9880 raise Exception("WPS ER did not report success")
9881
9882 def test_ap_wps_ignore_broadcast_ssid(dev, apdev):
9883 """WPS AP trying to ignore broadcast SSID"""
9884 ssid = "test-wps"
9885 hapd = hostapd.add_ap(apdev[0],
9886 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
9887 "ignore_broadcast_ssid": "1"})
9888 if "FAIL" not in hapd.request("WPS_PBC"):
9889 raise Exception("WPS unexpectedly enabled")
9890
9891 def test_ap_wps_wep(dev, apdev):
9892 """WPS AP trying to enable WEP"""
9893 ssid = "test-wps"
9894 hapd = hostapd.add_ap(apdev[0],
9895 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
9896 "ieee80211n": "0", "wep_key0": '"hello"'})
9897 if "FAIL" not in hapd.request("WPS_PBC"):
9898 raise Exception("WPS unexpectedly enabled")
9899
9900 def test_ap_wps_tkip(dev, apdev):
9901 """WPS AP trying to enable TKIP"""
9902 ssid = "test-wps"
9903 hapd = hostapd.add_ap(apdev[0],
9904 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
9905 "ieee80211n": "0", "wpa": '1',
9906 "wpa_key_mgmt": "WPA-PSK",
9907 "wpa_passphrase": "12345678"})
9908 if "FAIL" not in hapd.request("WPS_PBC"):
9909 raise Exception("WPS unexpectedly enabled")
9910
9911 def test_ap_wps_conf_dummy_cred(dev, apdev):
9912 """WPS PIN provisioning with configured AP using dummy cred"""
9913 ssid = "test-wps-conf"
9914 hapd = hostapd.add_ap(apdev[0],
9915 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9916 "wpa_passphrase": "12345678", "wpa": "2",
9917 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
9918 hapd.request("WPS_PIN any 12345670")
9919 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9920 dev[0].dump_monitor()
9921 try:
9922 hapd.set("wps_testing_dummy_cred", "1")
9923 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
9924 for i in range(1, 3):
9925 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
9926 if ev is None:
9927 raise Exception("WPS credential %d not received" % i)
9928 dev[0].wait_connected(timeout=30)
9929 finally:
9930 hapd.set("wps_testing_dummy_cred", "0")
9931
9932 def test_ap_wps_rf_bands(dev, apdev):
9933 """WPS and wps_rf_bands configuration"""
9934 ssid = "test-wps-conf"
9935 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9936 "wpa_passphrase": "12345678", "wpa": "2",
9937 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9938 "wps_rf_bands": "ag"}
9939
9940 hapd = hostapd.add_ap(apdev[0], params)
9941 bssid = hapd.own_addr()
9942 hapd.request("WPS_PBC")
9943 dev[0].scan_for_bss(bssid, freq="2412")
9944 dev[0].dump_monitor()
9945 dev[0].request("WPS_PBC " + bssid)
9946 dev[0].wait_connected(timeout=30)
9947 bss = dev[0].get_bss(bssid)
9948 logger.info("BSS: " + str(bss))
9949 if "103c000103" not in bss['ie']:
9950 raise Exception("RF Bands attribute with expected values not found")
9951 dev[0].request("DISCONNECT")
9952 dev[0].wait_disconnected()
9953 hapd.set("wps_rf_bands", "ad")
9954 hapd.set("wps_rf_bands", "a")
9955 hapd.set("wps_rf_bands", "g")
9956 hapd.set("wps_rf_bands", "b")
9957 hapd.set("wps_rf_bands", "ga")
9958 hapd.disable()
9959 dev[0].dump_monitor()
9960 dev[0].flush_scan_cache()
9961
9962 def test_ap_wps_pbc_in_m1(dev, apdev):
9963 """WPS and pbc_in_m1"""
9964 ssid = "test-wps-conf"
9965 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9966 "wpa_passphrase": "12345678", "wpa": "2",
9967 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9968 "config_methods": "virtual_push_button virtual_display",
9969 "pbc_in_m1": "1"}
9970
9971 hapd = hostapd.add_ap(apdev[0], params)
9972 bssid = hapd.own_addr()
9973 hapd.request("WPS_PBC")
9974 dev[0].scan_for_bss(bssid, freq="2412")
9975 dev[0].dump_monitor()
9976 dev[0].request("WPS_PBC " + bssid)
9977 dev[0].wait_connected(timeout=30)
9978 dev[0].request("DISCONNECT")
9979 dev[0].wait_disconnected()
9980 hapd.disable()
9981 dev[0].dump_monitor()
9982 dev[0].flush_scan_cache()
9983
9984 def test_ap_wps_pin_start_failure(dev, apdev):
9985 """WPS_PIN start failure"""
9986 with alloc_fail(dev[0], 1, "wpas_wps_start_dev_pw"):
9987 if "FAIL" not in dev[0].request("WPS_PIN any 12345670"):
9988 raise Exception("WPS_PIN not rejected during OOM")
9989 with alloc_fail(dev[0], 1, "wpas_wps_start_dev_pw"):
9990 if "FAIL" not in dev[0].request("WPS_PIN any"):
9991 raise Exception("WPS_PIN not rejected during OOM")
9992
9993 def test_ap_wps_ap_pin_failure(dev, apdev):
9994 """WPS_AP_PIN failure"""
9995 id = dev[0].add_network()
9996 dev[0].set_network(id, "mode", "2")
9997 dev[0].set_network_quoted(id, "ssid", "wpas-ap-wps")
9998 dev[0].set_network_quoted(id, "psk", "1234567890")
9999 dev[0].set_network(id, "frequency", "2412")
10000 dev[0].set_network(id, "scan_freq", "2412")
10001 dev[0].select_network(id)
10002 dev[0].wait_connected()
10003
10004 with fail_test(dev[0], 1,
10005 "os_get_random;wpa_supplicant_ctrl_iface_wps_ap_pin"):
10006 if "FAIL" not in dev[0].request("WPS_AP_PIN random"):
10007 raise Exception("WPS_AP_PIN random accepted")
10008 with alloc_fail(dev[0], 1, "wpas_wps_ap_pin_set"):
10009 if "FAIL" not in dev[0].request("WPS_AP_PIN set 12345670"):
10010 raise Exception("WPS_AP_PIN set accepted")
10011
10012 dev[0].request("DISCONNECT")
10013 dev[0].wait_disconnected()
10014
10015 def test_ap_wps_random_uuid(dev, apdev, params):
10016 """WPS and random UUID on Enrollee"""
10017 ssid = "test-wps-conf"
10018 hapd = hostapd.add_ap(apdev[0],
10019 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10020 "wpa_passphrase": "12345678", "wpa": "2",
10021 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
10022
10023 config = os.path.join(params['logdir'], 'ap_wps_random_uuid.conf')
10024 with open(config, "w") as f:
10025 f.write("auto_uuid=1\n")
10026
10027 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
10028
10029 uuid = []
10030 for i in range(3):
10031 wpas.interface_add("wlan5", config=config)
10032
10033 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
10034 wpas.dump_monitor()
10035 wpas.request("WPS_PBC " + apdev[0]['bssid'])
10036
10037 ev = hapd.wait_event(["WPS-ENROLLEE-SEEN"], timeout=10)
10038 if ev is None:
10039 raise Exception("Enrollee not seen")
10040 uuid.append(ev.split(' ')[2])
10041 wpas.request("WPS_CANCEL")
10042 wpas.dump_monitor()
10043
10044 wpas.interface_remove("wlan5")
10045
10046 hapd.dump_monitor()
10047
10048 logger.info("Seen UUIDs: " + str(uuid))
10049 if uuid[0] == uuid[1] or uuid[0] == uuid[2] or uuid[1] == uuid[2]:
10050 raise Exception("Same UUID used multiple times")
10051
10052 def test_ap_wps_conf_pin_gcmp_128(dev, apdev):
10053 """WPS PIN provisioning with configured AP using GCMP-128"""
10054 run_ap_wps_conf_pin_cipher(dev, apdev, "GCMP")
10055
10056 def test_ap_wps_conf_pin_gcmp_256(dev, apdev):
10057 """WPS PIN provisioning with configured AP using GCMP-256"""
10058 run_ap_wps_conf_pin_cipher(dev, apdev, "GCMP-256")
10059
10060 def test_ap_wps_conf_pin_ccmp_256(dev, apdev):
10061 """WPS PIN provisioning with configured AP using CCMP-256"""
10062 run_ap_wps_conf_pin_cipher(dev, apdev, "CCMP-256")
10063
10064 def run_ap_wps_conf_pin_cipher(dev, apdev, cipher):
10065 if cipher not in dev[0].get_capability("pairwise"):
10066 raise HwsimSkip("Cipher %s not supported" % cipher)
10067 ssid = "test-wps-conf-pin"
10068 hapd = hostapd.add_ap(apdev[0],
10069 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10070 "wpa_passphrase": "12345678", "wpa": "2",
10071 "wpa_key_mgmt": "WPA-PSK",
10072 "rsn_pairwise": cipher})
10073 logger.info("WPS provisioning step")
10074 pin = dev[0].wps_read_pin()
10075 hapd.request("WPS_PIN any " + pin)
10076 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10077 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
10078 dev[0].wait_connected(timeout=15)
10079
10080 def test_ap_wps_and_sae(dev, apdev):
10081 """Initial AP configuration with first WPS Enrollee and adding SAE"""
10082 try:
10083 run_ap_wps_and_sae(dev, apdev)
10084 finally:
10085 dev[0].set("wps_cred_add_sae", "0")
10086
10087 def run_ap_wps_and_sae(dev, apdev):
10088 ssid = "test-wps-sae"
10089 hapd = hostapd.add_ap(apdev[0],
10090 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
10091 "wps_cred_add_sae": "1"})
10092 logger.info("WPS provisioning step")
10093 pin = dev[0].wps_read_pin()
10094 hapd.request("WPS_PIN any " + pin)
10095
10096 dev[0].set("wps_cred_add_sae", "1")
10097 dev[0].request("SET sae_groups ")
10098 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
10099 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
10100 dev[0].wait_connected(timeout=30)
10101 status = dev[0].get_status()
10102 if status['key_mgmt'] != "SAE":
10103 raise Exception("SAE not used")
10104 if 'pmf' not in status or status['pmf'] != "1":
10105 raise Exception("PMF not enabled")
10106
10107 pin = dev[1].wps_read_pin()
10108 hapd.request("WPS_PIN any " + pin)
10109 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
10110 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
10111 dev[1].wait_connected(timeout=30)
10112 status = dev[1].get_status()
10113 if status['key_mgmt'] != "WPA2-PSK":
10114 raise Exception("WPA2-PSK not used")
10115 if 'pmf' in status:
10116 raise Exception("PMF enabled")
10117
10118 def test_ap_wps_conf_and_sae(dev, apdev):
10119 """WPS PBC provisioning with configured AP using PSK+SAE"""
10120 try:
10121 run_ap_wps_conf_and_sae(dev, apdev)
10122 finally:
10123 dev[0].set("wps_cred_add_sae", "0")
10124
10125 def run_ap_wps_conf_and_sae(dev, apdev):
10126 ssid = "test-wps-conf-sae"
10127 hapd = hostapd.add_ap(apdev[0],
10128 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10129 "wpa_passphrase": "12345678", "wpa": "2",
10130 "ieee80211w": "1", "sae_require_mfp": "1",
10131 "wpa_key_mgmt": "WPA-PSK SAE",
10132 "rsn_pairwise": "CCMP"})
10133
10134 dev[0].set("wps_cred_add_sae", "1")
10135 dev[0].request("SET sae_groups ")
10136 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10137 pin = dev[0].wps_read_pin()
10138 hapd.request("WPS_PIN any " + pin)
10139 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
10140 dev[0].wait_connected(timeout=30)
10141 status = dev[0].get_status()
10142 if status['key_mgmt'] != "SAE":
10143 raise Exception("SAE not used")
10144 if 'pmf' not in status or status['pmf'] != "1":
10145 raise Exception("PMF not enabled")
10146
10147 dev[1].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
10148 key_mgmt="WPA-PSK", ieee80211w="0")
10149
10150 def test_ap_wps_reg_config_and_sae(dev, apdev):
10151 """WPS registrar configuring an AP using AP PIN and using PSK+SAE"""
10152 try:
10153 run_ap_wps_reg_config_and_sae(dev, apdev)
10154 finally:
10155 dev[0].set("wps_cred_add_sae", "0")
10156
10157 def run_ap_wps_reg_config_and_sae(dev, apdev):
10158 ssid = "test-wps-init-ap-pin-sae"
10159 appin = "12345670"
10160 hostapd.add_ap(apdev[0],
10161 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10162 "ap_pin": appin, "wps_cred_add_sae": "1"})
10163 logger.info("WPS configuration step")
10164 dev[0].set("wps_cred_add_sae", "1")
10165 dev[0].request("SET sae_groups ")
10166 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
10167 dev[0].dump_monitor()
10168 new_ssid = "wps-new-ssid"
10169 new_passphrase = "1234567890"
10170 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
10171 new_passphrase)
10172 status = dev[0].get_status()
10173 if status['key_mgmt'] != "SAE":
10174 raise Exception("SAE not used")
10175 if 'pmf' not in status or status['pmf'] != "1":
10176 raise Exception("PMF not enabled")
10177
10178 dev[1].connect(new_ssid, psk=new_passphrase, scan_freq="2412", proto="WPA2",
10179 key_mgmt="WPA-PSK", ieee80211w="0")