]> git.ipfire.org Git - thirdparty/hostap.git/blame - tests/hwsim/test_ap_wps.py
tests: Remove forgotten print from gas_anqp_oom_hapd
[thirdparty/hostap.git] / tests / hwsim / test_ap_wps.py
CommitLineData
302b7a1b 1# WPS tests
a1eabc74 2# Copyright (c) 2013-2015, Jouni Malinen <j@w1.fi>
302b7a1b
JM
3#
4# This software may be distributed under the terms of the BSD license.
5# See README for more details.
6
6aaa661a 7import base64
476daa05 8import binascii
7511ead0
JM
9from Crypto.Cipher import AES
10import hashlib
11import hmac
2035b170 12import os
302b7a1b 13import time
2602a2ff 14import stat
302b7a1b
JM
15import subprocess
16import logging
c9aa4308 17logger = logging.getLogger()
1013a576 18import re
44ff0400 19import socket
7511ead0 20import struct
47c549fd
JM
21import httplib
22import urlparse
23import urllib
24import xml.etree.ElementTree as ET
25import StringIO
c965ae03 26import SocketServer
302b7a1b
JM
27
28import hwsim_utils
29import hostapd
1531402e 30from wpasupplicant import WpaSupplicant
c965ae03 31from utils import HwsimSkip, alloc_fail, fail_test, skip_with_fips
302b7a1b 32
24b7f282
JM
33def wps_start_ap(apdev, ssid="test-wps-conf"):
34 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
35 "wpa_passphrase": "12345678", "wpa": "2",
36 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
37 return hostapd.add_ap(apdev['ifname'], params)
38
ae3ad328 39def test_ap_wps_init(dev, apdev):
302b7a1b
JM
40 """Initial AP configuration with first WPS Enrollee"""
41 ssid = "test-wps"
ae3ad328 42 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b 43 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
ae3ad328 44 hapd = hostapd.Hostapd(apdev[0]['ifname'])
302b7a1b
JM
45 logger.info("WPS provisioning step")
46 hapd.request("WPS_PBC")
d671a420
JM
47 if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
48 raise Exception("PBC status not shown correctly")
b9018833
JM
49
50 id = dev[0].add_network()
51 dev[0].set_network_quoted(id, "ssid", "home")
52 dev[0].set_network_quoted(id, "psk", "12345678")
53 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
54
55 id = dev[0].add_network()
56 dev[0].set_network_quoted(id, "ssid", "home2")
57 dev[0].set_network(id, "bssid", "00:11:22:33:44:55")
58 dev[0].set_network(id, "key_mgmt", "NONE")
59 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
60
302b7a1b 61 dev[0].request("WPS_PBC")
5f35a5e2 62 dev[0].wait_connected(timeout=30)
302b7a1b 63 status = dev[0].get_status()
ae3ad328 64 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
65 raise Exception("Not fully connected")
66 if status['ssid'] != ssid:
67 raise Exception("Unexpected SSID")
68 if status['pairwise_cipher'] != 'CCMP':
69 raise Exception("Unexpected encryption configuration")
70 if status['key_mgmt'] != 'WPA2-PSK':
71 raise Exception("Unexpected key_mgmt")
72
d671a420
JM
73 status = hapd.request("WPS_GET_STATUS")
74 if "PBC Status: Disabled" not in status:
75 raise Exception("PBC status not shown correctly")
76 if "Last WPS result: Success" not in status:
77 raise Exception("Last WPS result not shown correctly")
78 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
79 raise Exception("Peer address not shown correctly")
75b25ece
JM
80 conf = hapd.request("GET_CONFIG")
81 if "wps_state=configured" not in conf:
82 raise Exception("AP not in WPS configured state")
742408af
JM
83 if "wpa=3" not in conf:
84 raise Exception("AP not in WPA+WPA2 configuration")
75b25ece
JM
85 if "rsn_pairwise_cipher=CCMP TKIP" not in conf:
86 raise Exception("Unexpected rsn_pairwise_cipher")
87 if "wpa_pairwise_cipher=CCMP TKIP" not in conf:
88 raise Exception("Unexpected wpa_pairwise_cipher")
89 if "group_cipher=TKIP" not in conf:
90 raise Exception("Unexpected group_cipher")
d671a420 91
b9018833
JM
92 if len(dev[0].list_networks()) != 3:
93 raise Exception("Unexpected number of network blocks")
94
18030dc0
JM
95def test_ap_wps_init_2ap_pbc(dev, apdev):
96 """Initial two-radio AP configuration with first WPS PBC Enrollee"""
97 ssid = "test-wps"
98 params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
99 hostapd.add_ap(apdev[0]['ifname'], params)
100 hostapd.add_ap(apdev[1]['ifname'], params)
101 hapd = hostapd.Hostapd(apdev[0]['ifname'])
102 logger.info("WPS provisioning step")
103 hapd.request("WPS_PBC")
84a40841
JM
104 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
105 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
106 bss = dev[0].get_bss(apdev[0]['bssid'])
107 if "[WPS-PBC]" not in bss['flags']:
108 raise Exception("WPS-PBC flag missing from AP1")
109 bss = dev[0].get_bss(apdev[1]['bssid'])
110 if "[WPS-PBC]" not in bss['flags']:
111 raise Exception("WPS-PBC flag missing from AP2")
112 dev[0].dump_monitor()
f19d87f1 113 dev[0].request("SET wps_cred_processing 2")
18030dc0 114 dev[0].request("WPS_PBC")
f19d87f1
JM
115 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=30)
116 dev[0].request("SET wps_cred_processing 0")
117 if ev is None:
118 raise Exception("WPS cred event not seen")
119 if "100e" not in ev:
120 raise Exception("WPS attributes not included in the cred event")
5f35a5e2 121 dev[0].wait_connected(timeout=30)
18030dc0 122
84a40841
JM
123 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
124 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
125 bss = dev[1].get_bss(apdev[0]['bssid'])
126 if "[WPS-PBC]" in bss['flags']:
127 raise Exception("WPS-PBC flag not cleared from AP1")
128 bss = dev[1].get_bss(apdev[1]['bssid'])
129 if "[WPS-PBC]" in bss['flags']:
0bde923c 130 raise Exception("WPS-PBC flag not cleared from AP2")
18030dc0
JM
131
132def test_ap_wps_init_2ap_pin(dev, apdev):
133 """Initial two-radio AP configuration with first WPS PIN Enrollee"""
134 ssid = "test-wps"
135 params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
136 hostapd.add_ap(apdev[0]['ifname'], params)
137 hostapd.add_ap(apdev[1]['ifname'], params)
138 hapd = hostapd.Hostapd(apdev[0]['ifname'])
139 logger.info("WPS provisioning step")
140 pin = dev[0].wps_read_pin()
141 hapd.request("WPS_PIN any " + pin)
84a40841
JM
142 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
143 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
144 bss = dev[0].get_bss(apdev[0]['bssid'])
145 if "[WPS-AUTH]" not in bss['flags']:
146 raise Exception("WPS-AUTH flag missing from AP1")
147 bss = dev[0].get_bss(apdev[1]['bssid'])
148 if "[WPS-AUTH]" not in bss['flags']:
149 raise Exception("WPS-AUTH flag missing from AP2")
150 dev[0].dump_monitor()
151 dev[0].request("WPS_PIN any " + pin)
5f35a5e2 152 dev[0].wait_connected(timeout=30)
18030dc0 153
84a40841
JM
154 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
155 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
156 bss = dev[1].get_bss(apdev[0]['bssid'])
157 if "[WPS-AUTH]" in bss['flags']:
158 raise Exception("WPS-AUTH flag not cleared from AP1")
159 bss = dev[1].get_bss(apdev[1]['bssid'])
160 if "[WPS-AUTH]" in bss['flags']:
0bde923c 161 raise Exception("WPS-AUTH flag not cleared from AP2")
18030dc0 162
35831e94
JM
163def test_ap_wps_init_through_wps_config(dev, apdev):
164 """Initial AP configuration using wps_config command"""
165 ssid = "test-wps-init-config"
166 hostapd.add_ap(apdev[0]['ifname'],
167 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
168 hapd = hostapd.Hostapd(apdev[0]['ifname'])
169 if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
170 raise Exception("WPS_CONFIG command failed")
180cd73d
JM
171 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
172 if ev is None:
173 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
174 # It takes some time for the AP to update Beacon and Probe Response frames,
175 # so wait here before requesting the scan to be started to avoid adding
176 # extra five second wait to the test due to fetching obsolete scan results.
177 hapd.ping()
178 time.sleep(0.2)
35831e94
JM
179 dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
180 pairwise="CCMP", group="CCMP")
181
fbf6b717
JM
182def test_ap_wps_init_through_wps_config_2(dev, apdev):
183 """AP configuration using wps_config and wps_cred_processing=2"""
184 ssid = "test-wps-init-config"
185 hostapd.add_ap(apdev[0]['ifname'],
186 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
187 "wps_cred_processing": "2" })
188 hapd = hostapd.Hostapd(apdev[0]['ifname'])
189 if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
190 raise Exception("WPS_CONFIG command failed")
191 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
192 if ev is None:
193 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
194 if "100e" not in ev:
195 raise Exception("WPS-NEW-AP-SETTINGS did not include Credential")
196
e1eb0e9e
JM
197def test_ap_wps_invalid_wps_config_passphrase(dev, apdev):
198 """AP configuration using wps_config command with invalid passphrase"""
199 ssid = "test-wps-init-config"
200 hostapd.add_ap(apdev[0]['ifname'],
201 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
202 hapd = hostapd.Hostapd(apdev[0]['ifname'])
203 if "FAIL" not in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "1234567".encode("hex")):
204 raise Exception("Invalid WPS_CONFIG command accepted")
205
ae3ad328 206def test_ap_wps_conf(dev, apdev):
302b7a1b
JM
207 """WPS PBC provisioning with configured AP"""
208 ssid = "test-wps-conf"
ae3ad328 209 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b
JM
210 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
211 "wpa_passphrase": "12345678", "wpa": "2",
212 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
ae3ad328 213 hapd = hostapd.Hostapd(apdev[0]['ifname'])
302b7a1b
JM
214 logger.info("WPS provisioning step")
215 hapd.request("WPS_PBC")
33d0b157 216 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 217 dev[0].dump_monitor()
33d0b157 218 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 219 dev[0].wait_connected(timeout=30)
302b7a1b 220 status = dev[0].get_status()
ae3ad328 221 if status['wpa_state'] != 'COMPLETED':
302b7a1b 222 raise Exception("Not fully connected")
ae3ad328
JM
223 if status['bssid'] != apdev[0]['bssid']:
224 raise Exception("Unexpected BSSID")
302b7a1b
JM
225 if status['ssid'] != ssid:
226 raise Exception("Unexpected SSID")
227 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
228 raise Exception("Unexpected encryption configuration")
229 if status['key_mgmt'] != 'WPA2-PSK':
230 raise Exception("Unexpected key_mgmt")
231
097cd9cd
JM
232 sta = hapd.get_sta(dev[0].p2p_interface_addr())
233 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
234 raise Exception("Device name not available in STA command")
235
daad14cc
JM
236def test_ap_wps_conf_5ghz(dev, apdev):
237 """WPS PBC provisioning with configured AP on 5 GHz band"""
238 try:
9d7fdac5 239 hapd = None
daad14cc
JM
240 ssid = "test-wps-conf"
241 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
242 "wpa_passphrase": "12345678", "wpa": "2",
243 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
244 "country_code": "FI", "hw_mode": "a", "channel": "36" }
245 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
246 logger.info("WPS provisioning step")
247 hapd.request("WPS_PBC")
33d0b157
JM
248 dev[0].scan_for_bss(apdev[0]['bssid'], freq="5180")
249 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 250 dev[0].wait_connected(timeout=30)
daad14cc
JM
251
252 sta = hapd.get_sta(dev[0].p2p_interface_addr())
253 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
254 raise Exception("Device name not available in STA command")
255 finally:
9d7fdac5
JM
256 dev[0].request("DISCONNECT")
257 if hapd:
258 hapd.request("DISABLE")
c4668009 259 subprocess.call(['iw', 'reg', 'set', '00'])
9d7fdac5 260 dev[0].flush_scan_cache()
daad14cc
JM
261
262def test_ap_wps_conf_chan14(dev, apdev):
263 """WPS PBC provisioning with configured AP on channel 14"""
264 try:
9d7fdac5 265 hapd = None
daad14cc
JM
266 ssid = "test-wps-conf"
267 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
268 "wpa_passphrase": "12345678", "wpa": "2",
269 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
270 "country_code": "JP", "hw_mode": "b", "channel": "14" }
271 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
272 logger.info("WPS provisioning step")
273 hapd.request("WPS_PBC")
274 dev[0].request("WPS_PBC")
5f35a5e2 275 dev[0].wait_connected(timeout=30)
daad14cc
JM
276
277 sta = hapd.get_sta(dev[0].p2p_interface_addr())
278 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
279 raise Exception("Device name not available in STA command")
280 finally:
9d7fdac5
JM
281 dev[0].request("DISCONNECT")
282 if hapd:
283 hapd.request("DISABLE")
c4668009 284 subprocess.call(['iw', 'reg', 'set', '00'])
9d7fdac5 285 dev[0].flush_scan_cache()
daad14cc 286
04e62788
JM
287def test_ap_wps_twice(dev, apdev):
288 """WPS provisioning with twice to change passphrase"""
289 ssid = "test-wps-twice"
290 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
291 "wpa_passphrase": "12345678", "wpa": "2",
292 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
293 hostapd.add_ap(apdev[0]['ifname'], params)
294 hapd = hostapd.Hostapd(apdev[0]['ifname'])
295 logger.info("WPS provisioning step")
296 hapd.request("WPS_PBC")
33d0b157 297 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
04e62788 298 dev[0].dump_monitor()
33d0b157 299 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 300 dev[0].wait_connected(timeout=30)
04e62788
JM
301 dev[0].request("DISCONNECT")
302
303 logger.info("Restart AP with different passphrase and re-run WPS")
304 hapd_global = hostapd.HostapdGlobal()
305 hapd_global.remove(apdev[0]['ifname'])
306 params['wpa_passphrase'] = 'another passphrase'
307 hostapd.add_ap(apdev[0]['ifname'], params)
308 hapd = hostapd.Hostapd(apdev[0]['ifname'])
309 logger.info("WPS provisioning step")
310 hapd.request("WPS_PBC")
311 dev[0].dump_monitor()
33d0b157 312 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 313 dev[0].wait_connected(timeout=30)
04e62788
JM
314 networks = dev[0].list_networks()
315 if len(networks) > 1:
316 raise Exception("Unexpected duplicated network block present")
317
d658205a
JM
318def test_ap_wps_incorrect_pin(dev, apdev):
319 """WPS PIN provisioning with incorrect PIN"""
320 ssid = "test-wps-incorrect-pin"
321 hostapd.add_ap(apdev[0]['ifname'],
322 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
323 "wpa_passphrase": "12345678", "wpa": "2",
324 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
325 hapd = hostapd.Hostapd(apdev[0]['ifname'])
326
327 logger.info("WPS provisioning attempt 1")
328 hapd.request("WPS_PIN any 12345670")
33d0b157 329 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
d658205a 330 dev[0].dump_monitor()
33d0b157 331 dev[0].request("WPS_PIN %s 55554444" % apdev[0]['bssid'])
d658205a
JM
332 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
333 if ev is None:
334 raise Exception("WPS operation timed out")
335 if "config_error=18" not in ev:
336 raise Exception("Incorrect config_error reported")
337 if "msg=8" not in ev:
338 raise Exception("PIN error detected on incorrect message")
5f35a5e2 339 dev[0].wait_disconnected(timeout=10)
d658205a
JM
340 dev[0].request("WPS_CANCEL")
341 # if a scan was in progress, wait for it to complete before trying WPS again
342 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
343
d671a420
JM
344 status = hapd.request("WPS_GET_STATUS")
345 if "Last WPS result: Failed" not in status:
346 raise Exception("WPS failure result not shown correctly")
347
d658205a
JM
348 logger.info("WPS provisioning attempt 2")
349 hapd.request("WPS_PIN any 12345670")
350 dev[0].dump_monitor()
33d0b157 351 dev[0].request("WPS_PIN %s 12344444" % apdev[0]['bssid'])
d658205a
JM
352 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
353 if ev is None:
354 raise Exception("WPS operation timed out")
355 if "config_error=18" not in ev:
356 raise Exception("Incorrect config_error reported")
357 if "msg=10" not in ev:
358 raise Exception("PIN error detected on incorrect message")
5f35a5e2 359 dev[0].wait_disconnected(timeout=10)
d658205a 360
ae3ad328 361def test_ap_wps_conf_pin(dev, apdev):
302b7a1b
JM
362 """WPS PIN provisioning with configured AP"""
363 ssid = "test-wps-conf-pin"
ae3ad328 364 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b
JM
365 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
366 "wpa_passphrase": "12345678", "wpa": "2",
367 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
ae3ad328 368 hapd = hostapd.Hostapd(apdev[0]['ifname'])
302b7a1b
JM
369 logger.info("WPS provisioning step")
370 pin = dev[0].wps_read_pin()
371 hapd.request("WPS_PIN any " + pin)
33d0b157 372 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 373 dev[0].dump_monitor()
33d0b157 374 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 375 dev[0].wait_connected(timeout=30)
302b7a1b 376 status = dev[0].get_status()
ae3ad328 377 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
378 raise Exception("Not fully connected")
379 if status['ssid'] != ssid:
380 raise Exception("Unexpected SSID")
381 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
382 raise Exception("Unexpected encryption configuration")
383 if status['key_mgmt'] != 'WPA2-PSK':
384 raise Exception("Unexpected key_mgmt")
385
84a40841 386 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
362ba6de
JM
387 bss = dev[1].get_bss(apdev[0]['bssid'])
388 if "[WPS-AUTH]" in bss['flags']:
389 raise Exception("WPS-AUTH flag not cleared")
a60a6d6b 390 logger.info("Try to connect from another station using the same PIN")
33d0b157 391 pin = dev[1].request("WPS_PIN " + apdev[0]['bssid'])
a60a6d6b
JM
392 ev = dev[1].wait_event(["WPS-M2D","CTRL-EVENT-CONNECTED"], timeout=30)
393 if ev is None:
394 raise Exception("Operation timed out")
395 if "WPS-M2D" not in ev:
396 raise Exception("Unexpected WPS operation started")
6e12eaa4 397 hapd.request("WPS_PIN any " + pin)
5f35a5e2 398 dev[1].wait_connected(timeout=30)
362ba6de 399
6257f9c0
JM
400def test_ap_wps_conf_pin_v1(dev, apdev):
401 """WPS PIN provisioning with configured WPS v1.0 AP"""
402 ssid = "test-wps-conf-pin-v1"
403 hostapd.add_ap(apdev[0]['ifname'],
404 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
405 "wpa_passphrase": "12345678", "wpa": "2",
406 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
407 hapd = hostapd.Hostapd(apdev[0]['ifname'])
408 logger.info("WPS provisioning step")
409 pin = dev[0].wps_read_pin()
410 hapd.request("SET wps_version_number 0x10")
411 hapd.request("WPS_PIN any " + pin)
412 found = False
413 for i in range(0, 10):
414 dev[0].scan(freq="2412")
415 if "[WPS-PIN]" in dev[0].request("SCAN_RESULTS"):
416 found = True
417 break
418 if not found:
419 hapd.request("SET wps_version_number 0x20")
420 raise Exception("WPS-PIN flag not seen in scan results")
421 dev[0].dump_monitor()
33d0b157 422 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 423 dev[0].wait_connected(timeout=30)
6257f9c0 424 hapd.request("SET wps_version_number 0x20")
6257f9c0 425
e9129860
JM
426def test_ap_wps_conf_pin_2sta(dev, apdev):
427 """Two stations trying to use WPS PIN at the same time"""
428 ssid = "test-wps-conf-pin2"
429 hostapd.add_ap(apdev[0]['ifname'],
430 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
431 "wpa_passphrase": "12345678", "wpa": "2",
432 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
433 hapd = hostapd.Hostapd(apdev[0]['ifname'])
434 logger.info("WPS provisioning step")
435 pin = "12345670"
436 pin2 = "55554444"
437 hapd.request("WPS_PIN " + dev[0].get_status_field("uuid") + " " + pin)
438 hapd.request("WPS_PIN " + dev[1].get_status_field("uuid") + " " + pin)
e9129860 439 dev[0].dump_monitor()
e9129860 440 dev[1].dump_monitor()
33d0b157
JM
441 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
442 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
443 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
444 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2
JM
445 dev[0].wait_connected(timeout=30)
446 dev[1].wait_connected(timeout=30)
0489e880
JM
447
448def test_ap_wps_conf_pin_timeout(dev, apdev):
449 """WPS PIN provisioning with configured AP timing out PIN"""
450 ssid = "test-wps-conf-pin"
451 hostapd.add_ap(apdev[0]['ifname'],
452 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
453 "wpa_passphrase": "12345678", "wpa": "2",
454 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
455 hapd = hostapd.Hostapd(apdev[0]['ifname'])
456 addr = dev[0].p2p_interface_addr()
457 pin = dev[0].wps_read_pin()
458 if "FAIL" not in hapd.request("WPS_PIN "):
459 raise Exception("Unexpected success on invalid WPS_PIN")
460 hapd.request("WPS_PIN any " + pin + " 1")
33d0b157 461 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
0489e880 462 time.sleep(1.1)
33d0b157 463 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
0489e880
JM
464 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=20)
465 if ev is None:
466 raise Exception("WPS-PIN-NEEDED event timed out")
467 ev = dev[0].wait_event(["WPS-M2D"])
468 if ev is None:
469 raise Exception("M2D not reported")
470 dev[0].request("WPS_CANCEL")
471
472 hapd.request("WPS_PIN any " + pin + " 20 " + addr)
33d0b157 473 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 474 dev[0].wait_connected(timeout=30)
e9129860 475
ae3ad328 476def test_ap_wps_reg_connect(dev, apdev):
302b7a1b 477 """WPS registrar using AP PIN to connect"""
803edd1c 478 ssid = "test-wps-reg-ap-pin"
302b7a1b 479 appin = "12345670"
ae3ad328 480 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b
JM
481 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
482 "wpa_passphrase": "12345678", "wpa": "2",
483 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
484 "ap_pin": appin})
485 logger.info("WPS provisioning step")
302b7a1b 486 dev[0].dump_monitor()
33d0b157 487 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 488 dev[0].wps_reg(apdev[0]['bssid'], appin)
302b7a1b 489 status = dev[0].get_status()
ae3ad328 490 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
491 raise Exception("Not fully connected")
492 if status['ssid'] != ssid:
493 raise Exception("Unexpected SSID")
494 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
495 raise Exception("Unexpected encryption configuration")
496 if status['key_mgmt'] != 'WPA2-PSK':
497 raise Exception("Unexpected key_mgmt")
498
e60be3b3
JM
499def test_ap_wps_reg_connect_mixed_mode(dev, apdev):
500 """WPS registrar using AP PIN to connect (WPA+WPA2)"""
501 ssid = "test-wps-reg-ap-pin"
502 appin = "12345670"
503 hostapd.add_ap(apdev[0]['ifname'],
504 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
505 "wpa_passphrase": "12345678", "wpa": "3",
506 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
507 "wpa_pairwise": "TKIP", "ap_pin": appin})
508 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
509 dev[0].wps_reg(apdev[0]['bssid'], appin)
510 status = dev[0].get_status()
511 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
512 raise Exception("Not fully connected")
513 if status['ssid'] != ssid:
514 raise Exception("Unexpected SSID")
515 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
516 raise Exception("Unexpected encryption configuration")
517 if status['key_mgmt'] != 'WPA2-PSK':
518 raise Exception("Unexpected key_mgmt")
519
7511ead0
JM
520def test_ap_wps_reg_override_ap_settings(dev, apdev):
521 """WPS registrar and ap_settings override"""
522 ap_settings = "/tmp/ap_wps_reg_override_ap_settings"
523 try:
524 os.remove(ap_settings)
525 except:
526 pass
527 # Override AP Settings with values that point to another AP
528 data = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
529 data += build_wsc_attr(ATTR_SSID, "test")
530 data += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
531 data += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
532 data += build_wsc_attr(ATTR_NETWORK_KEY, '')
533 data += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[1]['bssid'].replace(':', '')))
534 with open(ap_settings, "w") as f:
535 f.write(data)
536 ssid = "test-wps-reg-ap-pin"
537 appin = "12345670"
538 hostapd.add_ap(apdev[0]['ifname'],
539 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
540 "wpa_passphrase": "12345678", "wpa": "2",
541 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
542 "ap_pin": appin, "ap_settings": ap_settings })
543 hapd2 = hostapd.add_ap(apdev[1]['ifname'], { "ssid": "test" })
544 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
545 dev[0].scan_for_bss(apdev[1]['bssid'], freq=2412)
546 dev[0].wps_reg(apdev[0]['bssid'], appin)
547 ev = hapd2.wait_event(['AP-STA-CONNECTED'], timeout=10)
548 os.remove(ap_settings)
549 if ev is None:
550 raise Exception("No connection with the other AP")
551
9488858f
JM
552def check_wps_reg_failure(dev, ap, appin):
553 dev.request("WPS_REG " + ap['bssid'] + " " + appin)
554 ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
555 if ev is None:
556 raise Exception("WPS operation timed out")
557 if "WPS-SUCCESS" in ev:
558 raise Exception("WPS operation succeeded unexpectedly")
559 if "config_error=15" not in ev:
560 raise Exception("WPS setup locked state was not reported correctly")
561
e4357b19
JM
562def test_ap_wps_random_ap_pin(dev, apdev):
563 """WPS registrar using random AP PIN"""
564 ssid = "test-wps-reg-random-ap-pin"
565 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
566 hostapd.add_ap(apdev[0]['ifname'],
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 "device_name": "Wireless AP", "manufacturer": "Company",
571 "model_name": "WAP", "model_number": "123",
572 "serial_number": "12345", "device_type": "6-0050F204-1",
573 "os_version": "01020300",
574 "config_methods": "label push_button",
575 "uuid": ap_uuid, "upnp_iface": "lo" })
576 hapd = hostapd.Hostapd(apdev[0]['ifname'])
577 appin = hapd.request("WPS_AP_PIN random")
578 if "FAIL" in appin:
579 raise Exception("Could not generate random AP PIN")
580 if appin not in hapd.request("WPS_AP_PIN get"):
581 raise Exception("Could not fetch current AP PIN")
582 logger.info("WPS provisioning step")
33d0b157 583 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
e4357b19
JM
584 dev[0].wps_reg(apdev[0]['bssid'], appin)
585
586 hapd.request("WPS_AP_PIN disable")
587 logger.info("WPS provisioning step with AP PIN disabled")
33d0b157 588 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
9488858f
JM
589 check_wps_reg_failure(dev[1], apdev[0], appin)
590
591 logger.info("WPS provisioning step with AP PIN reset")
592 appin = "12345670"
593 hapd.request("WPS_AP_PIN set " + appin)
594 dev[1].wps_reg(apdev[0]['bssid'], appin)
595 dev[0].request("REMOVE_NETWORK all")
596 dev[1].request("REMOVE_NETWORK all")
5f35a5e2
JM
597 dev[0].wait_disconnected(timeout=10)
598 dev[1].wait_disconnected(timeout=10)
9488858f
JM
599
600 logger.info("WPS provisioning step after AP PIN timeout")
601 hapd.request("WPS_AP_PIN disable")
602 appin = hapd.request("WPS_AP_PIN random 1")
603 time.sleep(1.1)
604 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
605 raise Exception("AP PIN unexpectedly still enabled")
606 check_wps_reg_failure(dev[0], apdev[0], appin)
607
608 logger.info("WPS provisioning step after AP PIN timeout(2)")
609 hapd.request("WPS_AP_PIN disable")
610 appin = "12345670"
611 hapd.request("WPS_AP_PIN set " + appin + " 1")
612 time.sleep(1.1)
613 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
614 raise Exception("AP PIN unexpectedly still enabled")
615 check_wps_reg_failure(dev[1], apdev[0], appin)
e4357b19 616
24b7f282
JM
617 with fail_test(hapd, 1, "os_get_random;wps_generate_pin"):
618 if "FAIL" in hapd.request("WPS_AP_PIN random 1"):
619 raise Exception("Failed to generate PIN during OOM")
620 hapd.request("WPS_AP_PIN disable")
621
622 with alloc_fail(hapd, 1, "upnp_wps_set_ap_pin"):
623 hapd.request("WPS_AP_PIN set 12345670")
624 hapd.request("WPS_AP_PIN disable")
625
ae3ad328 626def test_ap_wps_reg_config(dev, apdev):
4b727c5c 627 """WPS registrar configuring an AP using AP PIN"""
302b7a1b
JM
628 ssid = "test-wps-init-ap-pin"
629 appin = "12345670"
ae3ad328 630 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b
JM
631 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
632 "ap_pin": appin})
633 logger.info("WPS configuration step")
33d0b157 634 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
302b7a1b
JM
635 dev[0].dump_monitor()
636 new_ssid = "wps-new-ssid"
637 new_passphrase = "1234567890"
6edaee9c
JM
638 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
639 new_passphrase)
302b7a1b 640 status = dev[0].get_status()
ae3ad328 641 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
642 raise Exception("Not fully connected")
643 if status['ssid'] != new_ssid:
644 raise Exception("Unexpected SSID")
645 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
646 raise Exception("Unexpected encryption configuration")
647 if status['key_mgmt'] != 'WPA2-PSK':
648 raise Exception("Unexpected key_mgmt")
649
375afd7c
JM
650 logger.info("Re-configure back to open")
651 dev[0].request("REMOVE_NETWORK all")
243dcc4a 652 dev[0].flush_scan_cache()
375afd7c
JM
653 dev[0].dump_monitor()
654 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-open", "OPEN", "NONE", "")
655 status = dev[0].get_status()
656 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
657 raise Exception("Not fully connected")
658 if status['ssid'] != "wps-open":
659 raise Exception("Unexpected SSID")
660 if status['key_mgmt'] != 'NONE':
661 raise Exception("Unexpected key_mgmt")
662
4b727c5c
JM
663def test_ap_wps_reg_config_ext_processing(dev, apdev):
664 """WPS registrar configuring an AP with external config processing"""
665 ssid = "test-wps-init-ap-pin"
666 appin = "12345670"
667 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
668 "wps_cred_processing": "1", "ap_pin": appin}
669 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
33d0b157 670 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
4b727c5c
JM
671 new_ssid = "wps-new-ssid"
672 new_passphrase = "1234567890"
673 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
674 new_passphrase, no_wait=True)
675 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
676 if ev is None:
677 raise Exception("WPS registrar operation timed out")
678 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=15)
679 if ev is None:
680 raise Exception("WPS configuration timed out")
681 if "1026" not in ev:
682 raise Exception("AP Settings missing from event")
683 hapd.request("SET wps_cred_processing 0")
684 if "FAIL" in hapd.request("WPS_CONFIG " + new_ssid.encode("hex") + " WPA2PSK CCMP " + new_passphrase.encode("hex")):
685 raise Exception("WPS_CONFIG command failed")
5f35a5e2 686 dev[0].wait_connected(timeout=15)
4b727c5c 687
eeefe187
JM
688def test_ap_wps_reg_config_tkip(dev, apdev):
689 """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
a1eabc74 690 skip_with_fips(dev[0])
eeefe187
JM
691 ssid = "test-wps-init-ap"
692 appin = "12345670"
693 hostapd.add_ap(apdev[0]['ifname'],
694 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
695 "ap_pin": appin})
696 logger.info("WPS configuration step")
eeefe187 697 dev[0].request("SET wps_version_number 0x10")
33d0b157 698 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
eeefe187
JM
699 dev[0].dump_monitor()
700 new_ssid = "wps-new-ssid-with-tkip"
701 new_passphrase = "1234567890"
702 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
703 new_passphrase)
704 logger.info("Re-connect to verify WPA2 mixed mode")
705 dev[0].request("DISCONNECT")
706 id = 0
707 dev[0].set_network(id, "pairwise", "CCMP")
708 dev[0].set_network(id, "proto", "RSN")
709 dev[0].connect_network(id)
710 status = dev[0].get_status()
711 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
3c086180 712 raise Exception("Not fully connected: wpa_state={} bssid={}".format(status['wpa_state'], status['bssid']))
eeefe187
JM
713 if status['ssid'] != new_ssid:
714 raise Exception("Unexpected SSID")
715 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
716 raise Exception("Unexpected encryption configuration")
717 if status['key_mgmt'] != 'WPA2-PSK':
718 raise Exception("Unexpected key_mgmt")
719
6645ff50
JM
720def test_ap_wps_setup_locked(dev, apdev):
721 """WPS registrar locking up AP setup on AP PIN failures"""
722 ssid = "test-wps-incorrect-ap-pin"
723 appin = "12345670"
724 hostapd.add_ap(apdev[0]['ifname'],
725 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
726 "wpa_passphrase": "12345678", "wpa": "2",
727 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
728 "ap_pin": appin})
6645ff50
JM
729 new_ssid = "wps-new-ssid-test"
730 new_passphrase = "1234567890"
731
33d0b157 732 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6645ff50
JM
733 ap_setup_locked=False
734 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
735 dev[0].dump_monitor()
736 logger.info("Try incorrect AP PIN - attempt " + pin)
737 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
738 "CCMP", new_passphrase, no_wait=True)
739 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
740 if ev is None:
741 raise Exception("Timeout on receiving WPS operation failure event")
742 if "CTRL-EVENT-CONNECTED" in ev:
743 raise Exception("Unexpected connection")
744 if "config_error=15" in ev:
745 logger.info("AP Setup Locked")
746 ap_setup_locked=True
747 elif "config_error=18" not in ev:
748 raise Exception("config_error=18 not reported")
5f35a5e2 749 dev[0].wait_disconnected(timeout=10)
6645ff50
JM
750 time.sleep(0.1)
751 if not ap_setup_locked:
752 raise Exception("AP setup was not locked")
24b7f282
JM
753 dev[0].request("WPS_CANCEL")
754 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True,
755 only_new=True)
756 bss = dev[0].get_bss(apdev[0]['bssid'])
757 if 'wps_ap_setup_locked' not in bss or bss['wps_ap_setup_locked'] != '1':
758 logger.info("BSS: " + str(bss))
759 raise Exception("AP Setup Locked not indicated in scan results")
6645ff50 760
d671a420
JM
761 hapd = hostapd.Hostapd(apdev[0]['ifname'])
762 status = hapd.request("WPS_GET_STATUS")
763 if "Last WPS result: Failed" not in status:
764 raise Exception("WPS failure result not shown correctly")
765 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
766 raise Exception("Peer address not shown correctly")
767
6645ff50
JM
768 time.sleep(0.5)
769 dev[0].dump_monitor()
770 logger.info("WPS provisioning step")
771 pin = dev[0].wps_read_pin()
772 hapd = hostapd.Hostapd(apdev[0]['ifname'])
773 hapd.request("WPS_PIN any " + pin)
33d0b157 774 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
6645ff50
JM
775 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
776 if ev is None:
777 raise Exception("WPS success was not reported")
5f35a5e2 778 dev[0].wait_connected(timeout=30)
6645ff50 779
c1cec68b
JM
780 appin = hapd.request("WPS_AP_PIN random")
781 if "FAIL" in appin:
782 raise Exception("Could not generate random AP PIN")
783 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=10)
784 if ev is None:
785 raise Exception("Failed to unlock AP PIN")
786
33c9b8d8
JM
787def test_ap_wps_setup_locked_timeout(dev, apdev):
788 """WPS re-enabling AP PIN after timeout"""
789 ssid = "test-wps-incorrect-ap-pin"
790 appin = "12345670"
791 hostapd.add_ap(apdev[0]['ifname'],
792 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
793 "wpa_passphrase": "12345678", "wpa": "2",
794 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
795 "ap_pin": appin})
796 new_ssid = "wps-new-ssid-test"
797 new_passphrase = "1234567890"
798
33d0b157 799 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
33c9b8d8
JM
800 ap_setup_locked=False
801 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
802 dev[0].dump_monitor()
803 logger.info("Try incorrect AP PIN - attempt " + pin)
804 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
805 "CCMP", new_passphrase, no_wait=True)
9ed53f5e 806 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"], timeout=15)
33c9b8d8
JM
807 if ev is None:
808 raise Exception("Timeout on receiving WPS operation failure event")
809 if "CTRL-EVENT-CONNECTED" in ev:
810 raise Exception("Unexpected connection")
811 if "config_error=15" in ev:
812 logger.info("AP Setup Locked")
813 ap_setup_locked=True
814 break
815 elif "config_error=18" not in ev:
816 raise Exception("config_error=18 not reported")
5f35a5e2 817 dev[0].wait_disconnected(timeout=10)
33c9b8d8
JM
818 time.sleep(0.1)
819 if not ap_setup_locked:
820 raise Exception("AP setup was not locked")
821 hapd = hostapd.Hostapd(apdev[0]['ifname'])
822 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=80)
823 if ev is None:
824 raise Exception("AP PIN did not get unlocked on 60 second timeout")
825
4c355e3e
JM
826def test_ap_wps_setup_locked_2(dev, apdev):
827 """WPS AP configured for special ap_setup_locked=2 mode"""
828 ssid = "test-wps-ap-pin"
829 appin = "12345670"
830 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
831 "wpa_passphrase": "12345678", "wpa": "2",
832 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
833 "ap_pin": appin, "ap_setup_locked": "2" }
834 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
835 new_ssid = "wps-new-ssid-test"
836 new_passphrase = "1234567890"
837
838 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
839 dev[0].wps_reg(apdev[0]['bssid'], appin)
840 dev[0].request("REMOVE_NETWORK all")
841 dev[0].wait_disconnected()
842
843 hapd.dump_monitor()
844 dev[0].dump_monitor()
845 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK",
846 "CCMP", new_passphrase, no_wait=True)
847
848 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
849 if ev is None:
850 raise Exception("hostapd did not report WPS failure")
851 if "msg=12 config_error=15" not in ev:
852 raise Exception("Unexpected failure reason (AP): " + ev)
853
854 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
855 if ev is None:
856 raise Exception("Timeout on receiving WPS operation failure event")
857 if "CTRL-EVENT-CONNECTED" in ev:
858 raise Exception("Unexpected connection")
859 if "config_error=15" not in ev:
860 raise Exception("Unexpected failure reason (STA): " + ev)
861 dev[0].request("WPS_CANCEL")
862 dev[0].wait_disconnected()
863
ae3ad328 864def test_ap_wps_pbc_overlap_2ap(dev, apdev):
302b7a1b 865 """WPS PBC session overlap with two active APs"""
ae3ad328 866 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b
JM
867 { "ssid": "wps1", "eap_server": "1", "wps_state": "2",
868 "wpa_passphrase": "12345678", "wpa": "2",
869 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
870 "wps_independent": "1"})
ae3ad328 871 hostapd.add_ap(apdev[1]['ifname'],
302b7a1b
JM
872 { "ssid": "wps2", "eap_server": "1", "wps_state": "2",
873 "wpa_passphrase": "123456789", "wpa": "2",
874 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
875 "wps_independent": "1"})
ae3ad328 876 hapd = hostapd.Hostapd(apdev[0]['ifname'])
302b7a1b 877 hapd.request("WPS_PBC")
ae3ad328 878 hapd2 = hostapd.Hostapd(apdev[1]['ifname'])
302b7a1b
JM
879 hapd2.request("WPS_PBC")
880 logger.info("WPS provisioning step")
84a40841
JM
881 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
882 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
302b7a1b
JM
883 dev[0].request("WPS_PBC")
884 ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
885 if ev is None:
886 raise Exception("PBC session overlap not detected")
492c3a91
JM
887 hapd.request("DISABLE")
888 hapd2.request("DISABLE")
889 dev[0].flush_scan_cache()
302b7a1b 890
ae3ad328 891def test_ap_wps_pbc_overlap_2sta(dev, apdev):
302b7a1b
JM
892 """WPS PBC session overlap with two active STAs"""
893 ssid = "test-wps-pbc-overlap"
ae3ad328 894 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b
JM
895 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
896 "wpa_passphrase": "12345678", "wpa": "2",
897 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
ae3ad328 898 hapd = hostapd.Hostapd(apdev[0]['ifname'])
302b7a1b
JM
899 logger.info("WPS provisioning step")
900 hapd.request("WPS_PBC")
33d0b157 901 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 902 dev[0].dump_monitor()
33d0b157 903 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 904 dev[1].dump_monitor()
33d0b157
JM
905 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
906 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
302b7a1b
JM
907 ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
908 if ev is None:
909 raise Exception("PBC session overlap not detected (dev0)")
910 if "config_error=12" not in ev:
911 raise Exception("PBC session overlap not correctly reported (dev0)")
492c3a91
JM
912 dev[0].request("WPS_CANCEL")
913 dev[0].request("DISCONNECT")
302b7a1b
JM
914 ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
915 if ev is None:
916 raise Exception("PBC session overlap not detected (dev1)")
917 if "config_error=12" not in ev:
918 raise Exception("PBC session overlap not correctly reported (dev1)")
492c3a91
JM
919 dev[1].request("WPS_CANCEL")
920 dev[1].request("DISCONNECT")
11e7eeba
JM
921 hapd.request("WPS_CANCEL")
922 ret = hapd.request("WPS_PBC")
923 if "FAIL" not in ret:
924 raise Exception("PBC mode allowed to be started while PBC overlap still active")
492c3a91
JM
925 hapd.request("DISABLE")
926 dev[0].flush_scan_cache()
927 dev[1].flush_scan_cache()
6edaee9c 928
71afe834
JM
929def test_ap_wps_cancel(dev, apdev):
930 """WPS AP cancelling enabled config method"""
931 ssid = "test-wps-ap-cancel"
932 hostapd.add_ap(apdev[0]['ifname'],
933 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
934 "wpa_passphrase": "12345678", "wpa": "2",
935 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
936 bssid = apdev[0]['bssid']
937 hapd = hostapd.Hostapd(apdev[0]['ifname'])
938
939 logger.info("Verify PBC enable/cancel")
940 hapd.request("WPS_PBC")
71afe834 941 dev[0].scan(freq="2412")
84a40841 942 dev[0].scan(freq="2412")
71afe834
JM
943 bss = dev[0].get_bss(apdev[0]['bssid'])
944 if "[WPS-PBC]" not in bss['flags']:
945 raise Exception("WPS-PBC flag missing")
946 if "FAIL" in hapd.request("WPS_CANCEL"):
947 raise Exception("WPS_CANCEL failed")
948 dev[0].scan(freq="2412")
84a40841 949 dev[0].scan(freq="2412")
71afe834
JM
950 bss = dev[0].get_bss(apdev[0]['bssid'])
951 if "[WPS-PBC]" in bss['flags']:
952 raise Exception("WPS-PBC flag not cleared")
953
954 logger.info("Verify PIN enable/cancel")
955 hapd.request("WPS_PIN any 12345670")
956 dev[0].scan(freq="2412")
84a40841 957 dev[0].scan(freq="2412")
71afe834
JM
958 bss = dev[0].get_bss(apdev[0]['bssid'])
959 if "[WPS-AUTH]" not in bss['flags']:
960 raise Exception("WPS-AUTH flag missing")
961 if "FAIL" in hapd.request("WPS_CANCEL"):
962 raise Exception("WPS_CANCEL failed")
963 dev[0].scan(freq="2412")
84a40841 964 dev[0].scan(freq="2412")
71afe834
JM
965 bss = dev[0].get_bss(apdev[0]['bssid'])
966 if "[WPS-AUTH]" in bss['flags']:
967 raise Exception("WPS-AUTH flag not cleared")
968
6edaee9c
JM
969def test_ap_wps_er_add_enrollee(dev, apdev):
970 """WPS ER configuring AP and adding a new enrollee using PIN"""
be9f1562
JM
971 try:
972 _test_ap_wps_er_add_enrollee(dev, apdev)
973 finally:
974 dev[0].request("WPS_ER_STOP")
975
976def _test_ap_wps_er_add_enrollee(dev, apdev):
6edaee9c
JM
977 ssid = "wps-er-add-enrollee"
978 ap_pin = "12345670"
979 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
980 hostapd.add_ap(apdev[0]['ifname'],
981 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
982 "device_name": "Wireless AP", "manufacturer": "Company",
983 "model_name": "WAP", "model_number": "123",
984 "serial_number": "12345", "device_type": "6-0050F204-1",
985 "os_version": "01020300",
24b7f282 986 'friendly_name': "WPS AP - <>&'\" - TEST",
6edaee9c
JM
987 "config_methods": "label push_button",
988 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
989 logger.info("WPS configuration step")
990 new_passphrase = "1234567890"
991 dev[0].dump_monitor()
33d0b157 992 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c
JM
993 dev[0].wps_reg(apdev[0]['bssid'], ap_pin, ssid, "WPA2PSK", "CCMP",
994 new_passphrase)
995 status = dev[0].get_status()
996 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
997 raise Exception("Not fully connected")
998 if status['ssid'] != ssid:
999 raise Exception("Unexpected SSID")
1000 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
1001 raise Exception("Unexpected encryption configuration")
1002 if status['key_mgmt'] != 'WPA2-PSK':
1003 raise Exception("Unexpected key_mgmt")
1004
1005 logger.info("Start ER")
1006 dev[0].request("WPS_ER_START ifname=lo")
1007 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1008 if ev is None:
1009 raise Exception("AP discovery timed out")
1010 if ap_uuid not in ev:
1011 raise Exception("Expected AP UUID not found")
24b7f282
JM
1012 if "|WPS AP - &lt;&gt;&amp;&apos;&quot; - TEST|Company|" not in ev:
1013 raise Exception("Expected friendly name not found")
6edaee9c
JM
1014
1015 logger.info("Learn AP configuration through UPnP")
1016 dev[0].dump_monitor()
1017 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1018 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1019 if ev is None:
1020 raise Exception("AP learn timed out")
1021 if ap_uuid not in ev:
1022 raise Exception("Expected AP UUID not in settings")
1023 if "ssid=" + ssid not in ev:
1024 raise Exception("Expected SSID not in settings")
1025 if "key=" + new_passphrase not in ev:
1026 raise Exception("Expected passphrase not in settings")
33d0b157
JM
1027 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1028 if ev is None:
1029 raise Exception("WPS-FAIL after AP learn timed out")
1030 time.sleep(0.1)
6edaee9c
JM
1031
1032 logger.info("Add Enrollee using ER")
1033 pin = dev[1].wps_read_pin()
1034 dev[0].dump_monitor()
1035 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
33d0b157 1036 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 1037 dev[1].dump_monitor()
33d0b157 1038 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
846be889 1039 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
6edaee9c
JM
1040 if ev is None:
1041 raise Exception("Enrollee did not report success")
5f35a5e2 1042 dev[1].wait_connected(timeout=15)
6edaee9c
JM
1043 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1044 if ev is None:
1045 raise Exception("WPS ER did not report success")
1046 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1047
11c26f1b
JM
1048 logger.info("Add a specific Enrollee using ER")
1049 pin = dev[2].wps_read_pin()
1050 addr2 = dev[2].p2p_interface_addr()
1051 dev[0].dump_monitor()
33d0b157 1052 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
11c26f1b 1053 dev[2].dump_monitor()
33d0b157 1054 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
11c26f1b
JM
1055 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1056 if ev is None:
1057 raise Exception("Enrollee not seen")
1058 if addr2 not in ev:
1059 raise Exception("Unexpected Enrollee MAC address")
1060 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
5f35a5e2 1061 dev[2].wait_connected(timeout=30)
11c26f1b
JM
1062 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1063 if ev is None:
1064 raise Exception("WPS ER did not report success")
1065
38ae43de
JM
1066 logger.info("Verify registrar selection behavior")
1067 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1068 dev[1].request("DISCONNECT")
5f35a5e2 1069 dev[1].wait_disconnected(timeout=10)
84a40841 1070 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
38ae43de
JM
1071 dev[1].scan(freq="2412")
1072 bss = dev[1].get_bss(apdev[0]['bssid'])
1073 if "[WPS-AUTH]" not in bss['flags']:
321c7f60
JM
1074 # It is possible for scan to miss an update especially when running
1075 # tests under load with multiple VMs, so allow another attempt.
1076 dev[1].scan(freq="2412")
1077 bss = dev[1].get_bss(apdev[0]['bssid'])
1078 if "[WPS-AUTH]" not in bss['flags']:
1079 raise Exception("WPS-AUTH flag missing")
38ae43de
JM
1080
1081 logger.info("Stop ER")
1082 dev[0].dump_monitor()
1083 dev[0].request("WPS_ER_STOP")
1084 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
1085 if ev is None:
1086 raise Exception("WPS ER unsubscription timed out")
8697cbc0 1087 # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
befd671c 1088 # a bit before verifying that the scan results have changed.
8697cbc0 1089 time.sleep(0.2)
38ae43de 1090
befd671c
JM
1091 for i in range(0, 10):
1092 dev[1].request("BSS_FLUSH 0")
1093 dev[1].scan(freq="2412", only_new=True)
1094 bss = dev[1].get_bss(apdev[0]['bssid'])
1095 if bss and 'flags' in bss and "[WPS-AUTH]" not in bss['flags']:
1096 break
1097 logger.debug("WPS-AUTH flag was still in place - wait a bit longer")
1098 time.sleep(0.1)
38ae43de
JM
1099 if "[WPS-AUTH]" in bss['flags']:
1100 raise Exception("WPS-AUTH flag not removed")
1101
c965ae03
JM
1102def test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1103 """WPS ER adding a new enrollee identified by UUID"""
1104 try:
1105 _test_ap_wps_er_add_enrollee_uuid(dev, apdev)
1106 finally:
1107 dev[0].request("WPS_ER_STOP")
1108
1109def _test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1110 ssid = "wps-er-add-enrollee"
1111 ap_pin = "12345670"
1112 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1113 hostapd.add_ap(apdev[0]['ifname'],
1114 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1115 "wpa_passphrase": "12345678", "wpa": "2",
1116 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1117 "device_name": "Wireless AP", "manufacturer": "Company",
1118 "model_name": "WAP", "model_number": "123",
1119 "serial_number": "12345", "device_type": "6-0050F204-1",
1120 "os_version": "01020300",
1121 "config_methods": "label push_button",
1122 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1123 logger.info("WPS configuration step")
1124 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1125 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1126
1127 logger.info("Start ER")
1128 dev[0].request("WPS_ER_START ifname=lo")
1129 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1130 if ev is None:
1131 raise Exception("AP discovery timed out")
1132 if ap_uuid not in ev:
1133 raise Exception("Expected AP UUID not found")
1134
1135 logger.info("Learn AP configuration through UPnP")
1136 dev[0].dump_monitor()
1137 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1138 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1139 if ev is None:
1140 raise Exception("AP learn timed out")
1141 if ap_uuid not in ev:
1142 raise Exception("Expected AP UUID not in settings")
1143 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1144 if ev is None:
1145 raise Exception("WPS-FAIL after AP learn timed out")
1146 time.sleep(0.1)
1147
1148 logger.info("Add a specific Enrollee using ER (PBC/UUID)")
1149 addr1 = dev[1].p2p_interface_addr()
1150 dev[0].dump_monitor()
1151 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1152 dev[1].dump_monitor()
1153 dev[1].request("WPS_PBC %s" % apdev[0]['bssid'])
1154 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1155 if ev is None:
1156 raise Exception("Enrollee not seen")
1157 if addr1 not in ev:
1158 raise Exception("Unexpected Enrollee MAC address")
1159 uuid = ev.split(' ')[1]
1160 dev[0].request("WPS_ER_PBC " + uuid)
1161 dev[1].wait_connected(timeout=30)
1162 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1163 if ev is None:
1164 raise Exception("WPS ER did not report success")
1165
1166 logger.info("Add a specific Enrollee using ER (PIN/UUID)")
1167 pin = dev[2].wps_read_pin()
1168 addr2 = dev[2].p2p_interface_addr()
1169 dev[0].dump_monitor()
1170 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1171 dev[2].dump_monitor()
1172 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1173 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1174 if ev is None:
1175 raise Exception("Enrollee not seen")
1176 if addr2 not in ev:
1177 raise Exception("Unexpected Enrollee MAC address")
1178 uuid = ev.split(' ')[1]
1179 dev[0].request("WPS_ER_PIN " + uuid + " " + pin)
1180 dev[2].wait_connected(timeout=30)
1181 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1182 if ev is None:
1183 raise Exception("WPS ER did not report success")
1184
ea982de1
JM
1185 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-REMOVE"], timeout=15)
1186 if ev is None:
1187 raise Exception("No Enrollee STA entry timeout seen")
1188
c965ae03
JM
1189 logger.info("Stop ER")
1190 dev[0].dump_monitor()
1191 dev[0].request("WPS_ER_STOP")
1192
61c3d464
JM
1193def test_ap_wps_er_multi_add_enrollee(dev, apdev):
1194 """Multiple WPS ERs adding a new enrollee using PIN"""
1195 try:
1196 _test_ap_wps_er_multi_add_enrollee(dev, apdev)
1197 finally:
1198 dev[0].request("WPS_ER_STOP")
1199
1200def _test_ap_wps_er_multi_add_enrollee(dev, apdev):
1201 ssid = "wps-er-add-enrollee"
1202 ap_pin = "12345670"
1203 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1204 hostapd.add_ap(apdev[0]['ifname'],
1205 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1206 "wpa_passphrase": "12345678", "wpa": "2",
1207 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1208 "device_name": "Wireless AP", "manufacturer": "Company",
1209 "model_name": "WAP", "model_number": "123",
1210 "serial_number": "12345", "device_type": "6-0050F204-1",
1211 "os_version": "01020300",
1212 'friendly_name': "WPS AP",
1213 "config_methods": "label push_button",
1214 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1215
1216 for i in range(2):
1217 dev[i].scan_for_bss(apdev[0]['bssid'], freq=2412)
1218 dev[i].wps_reg(apdev[0]['bssid'], ap_pin)
6a5f578c 1219 for i in range(2):
61c3d464
JM
1220 dev[i].request("WPS_ER_START ifname=lo")
1221 for i in range(2):
1222 ev = dev[i].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1223 if ev is None:
1224 raise Exception("AP discovery timed out")
1225 dev[i].dump_monitor()
6a5f578c 1226 for i in range(2):
61c3d464 1227 dev[i].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
6a5f578c 1228 for i in range(2):
61c3d464
JM
1229 ev = dev[i].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1230 if ev is None:
1231 raise Exception("AP learn timed out")
1232 ev = dev[i].wait_event(["WPS-FAIL"], timeout=15)
1233 if ev is None:
1234 raise Exception("WPS-FAIL after AP learn timed out")
1235
1236 time.sleep(0.1)
1237
1238 pin = dev[2].wps_read_pin()
1239 addr = dev[2].own_addr()
1240 dev[0].dump_monitor()
1241 dev[0].request("WPS_ER_PIN any " + pin + " " + addr)
1242 dev[1].dump_monitor()
1243 dev[1].request("WPS_ER_PIN any " + pin + " " + addr)
1244
1245 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1246 dev[2].dump_monitor()
1247 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1248 ev = dev[2].wait_event(["WPS-SUCCESS"], timeout=30)
1249 if ev is None:
1250 raise Exception("Enrollee did not report success")
1251 dev[2].wait_connected(timeout=15)
1252
6edaee9c
JM
1253def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1254 """WPS ER connected to AP and adding a new enrollee using PBC"""
be9f1562
JM
1255 try:
1256 _test_ap_wps_er_add_enrollee_pbc(dev, apdev)
1257 finally:
1258 dev[0].request("WPS_ER_STOP")
1259
1260def _test_ap_wps_er_add_enrollee_pbc(dev, apdev):
6edaee9c
JM
1261 ssid = "wps-er-add-enrollee-pbc"
1262 ap_pin = "12345670"
1263 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1264 hostapd.add_ap(apdev[0]['ifname'],
1265 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1266 "wpa_passphrase": "12345678", "wpa": "2",
1267 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1268 "device_name": "Wireless AP", "manufacturer": "Company",
1269 "model_name": "WAP", "model_number": "123",
1270 "serial_number": "12345", "device_type": "6-0050F204-1",
1271 "os_version": "01020300",
1272 "config_methods": "label push_button",
1273 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1274 logger.info("Learn AP configuration")
33d0b157 1275 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 1276 dev[0].dump_monitor()
6edaee9c
JM
1277 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1278 status = dev[0].get_status()
1279 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1280 raise Exception("Not fully connected")
1281
1282 logger.info("Start ER")
1283 dev[0].request("WPS_ER_START ifname=lo")
1284 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1285 if ev is None:
1286 raise Exception("AP discovery timed out")
1287 if ap_uuid not in ev:
1288 raise Exception("Expected AP UUID not found")
1289
d6b916c9
JM
1290 enrollee = dev[1].p2p_interface_addr()
1291
1292 if "FAIL-UNKNOWN-UUID" not in dev[0].request("WPS_ER_PBC " + enrollee):
1293 raise Exception("Unknown UUID not reported")
6edaee9c
JM
1294
1295 logger.info("Add Enrollee using ER and PBC")
1296 dev[0].dump_monitor()
6edaee9c
JM
1297 dev[1].dump_monitor()
1298 dev[1].request("WPS_PBC")
1299
8674c022
JM
1300 for i in range(0, 2):
1301 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1302 if ev is None:
1303 raise Exception("Enrollee discovery timed out")
1304 if enrollee in ev:
1305 break
1306 if i == 1:
1307 raise Exception("Expected Enrollee not found")
d6b916c9
JM
1308 if "FAIL-NO-AP-SETTINGS" not in dev[0].request("WPS_ER_PBC " + enrollee):
1309 raise Exception("Unknown UUID not reported")
1310 logger.info("Use learned network configuration on ER")
1311 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1312 if "OK" not in dev[0].request("WPS_ER_PBC " + enrollee):
1313 raise Exception("WPS_ER_PBC failed")
6edaee9c
JM
1314
1315 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
1316 if ev is None:
1317 raise Exception("Enrollee did not report success")
5f35a5e2 1318 dev[1].wait_connected(timeout=15)
6edaee9c
JM
1319 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1320 if ev is None:
1321 raise Exception("WPS ER did not report success")
1322 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
bff3ac5b 1323
d6b916c9
JM
1324def test_ap_wps_er_pbc_overlap(dev, apdev):
1325 """WPS ER connected to AP and PBC session overlap"""
be9f1562
JM
1326 try:
1327 _test_ap_wps_er_pbc_overlap(dev, apdev)
1328 finally:
1329 dev[0].request("WPS_ER_STOP")
1330
1331def _test_ap_wps_er_pbc_overlap(dev, apdev):
d6b916c9
JM
1332 ssid = "wps-er-add-enrollee-pbc"
1333 ap_pin = "12345670"
1334 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1335 hostapd.add_ap(apdev[0]['ifname'],
1336 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1337 "wpa_passphrase": "12345678", "wpa": "2",
1338 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1339 "device_name": "Wireless AP", "manufacturer": "Company",
1340 "model_name": "WAP", "model_number": "123",
1341 "serial_number": "12345", "device_type": "6-0050F204-1",
1342 "os_version": "01020300",
1343 "config_methods": "label push_button",
1344 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1345 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1346 dev[0].dump_monitor()
1347 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1348
fba25c99
JM
1349 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1350 dev[2].scan_for_bss(apdev[0]['bssid'], freq="2412")
1351 # avoid leaving dev 1 or 2 as the last Probe Request to the AP
1352 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True)
1353
d6b916c9
JM
1354 dev[0].dump_monitor()
1355 dev[0].request("WPS_ER_START ifname=lo")
1356
1357 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1358 if ev is None:
1359 raise Exception("AP discovery timed out")
1360 if ap_uuid not in ev:
1361 raise Exception("Expected AP UUID not found")
1362
800bcf4e
JM
1363 # verify BSSID selection of the AP instead of UUID
1364 if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
1365 raise Exception("Could not select AP based on BSSID")
1366
fba25c99 1367 dev[0].dump_monitor()
d6b916c9
JM
1368 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1369 dev[2].request("WPS_PBC " + apdev[0]['bssid'])
1370 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1371 if ev is None:
1372 raise Exception("PBC scan failed")
1373 ev = dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1374 if ev is None:
1375 raise Exception("PBC scan failed")
fba25c99
JM
1376 found1 = False
1377 found2 = False
1378 addr1 = dev[1].own_addr()
1379 addr2 = dev[2].own_addr()
1380 for i in range(3):
d6b916c9
JM
1381 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1382 if ev is None:
1383 raise Exception("Enrollee discovery timed out")
fba25c99
JM
1384 if addr1 in ev:
1385 found1 = True
1386 if found2:
1387 break
1388 if addr2 in ev:
1389 found2 = True
1390 if found1:
1391 break
d6b916c9
JM
1392 if dev[0].request("WPS_ER_PBC " + ap_uuid) != "FAIL-PBC-OVERLAP\n":
1393 raise Exception("PBC overlap not reported")
1394 dev[1].request("WPS_CANCEL")
1395 dev[2].request("WPS_CANCEL")
1396 if dev[0].request("WPS_ER_PBC foo") != "FAIL\n":
1397 raise Exception("Invalid WPS_ER_PBC accepted")
1398
1f020f5e
JM
1399def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1400 """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
be9f1562
JM
1401 try:
1402 _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev)
1403 finally:
1404 dev[0].request("WPS_ER_STOP")
1405
1406def _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1f020f5e
JM
1407 ssid = "wps-er-add-enrollee-pbc"
1408 ap_pin = "12345670"
1409 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1410 hostapd.add_ap(apdev[0]['ifname'],
1411 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1412 "wpa_passphrase": "12345678", "wpa": "2",
1413 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1414 "device_name": "Wireless AP", "manufacturer": "Company",
1415 "model_name": "WAP", "model_number": "123",
1416 "serial_number": "12345", "device_type": "6-0050F204-1",
1417 "os_version": "01020300",
1418 "config_methods": "label push_button",
1419 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1420 logger.info("Learn AP configuration")
1421 dev[0].request("SET wps_version_number 0x10")
33d0b157 1422 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1f020f5e
JM
1423 dev[0].dump_monitor()
1424 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1425 status = dev[0].get_status()
1426 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1427 raise Exception("Not fully connected")
1428
1429 logger.info("Start ER")
1430 dev[0].request("WPS_ER_START ifname=lo")
1431 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1432 if ev is None:
1433 raise Exception("AP discovery timed out")
1434 if ap_uuid not in ev:
1435 raise Exception("Expected AP UUID not found")
1436
1437 logger.info("Use learned network configuration on ER")
1438 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1439
1440 logger.info("Add Enrollee using ER and PIN")
1441 enrollee = dev[1].p2p_interface_addr()
1442 pin = dev[1].wps_read_pin()
1443 dev[0].dump_monitor()
1444 dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
33d0b157 1445 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1f020f5e 1446 dev[1].dump_monitor()
33d0b157 1447 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 1448 dev[1].wait_connected(timeout=30)
1f020f5e
JM
1449 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1450 if ev is None:
1451 raise Exception("WPS ER did not report success")
1452
be923570
JM
1453def test_ap_wps_er_config_ap(dev, apdev):
1454 """WPS ER configuring AP over UPnP"""
be9f1562
JM
1455 try:
1456 _test_ap_wps_er_config_ap(dev, apdev)
1457 finally:
1458 dev[0].request("WPS_ER_STOP")
1459
1460def _test_ap_wps_er_config_ap(dev, apdev):
be923570
JM
1461 ssid = "wps-er-ap-config"
1462 ap_pin = "12345670"
1463 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1464 hostapd.add_ap(apdev[0]['ifname'],
1465 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1466 "wpa_passphrase": "12345678", "wpa": "2",
1467 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1468 "device_name": "Wireless AP", "manufacturer": "Company",
1469 "model_name": "WAP", "model_number": "123",
1470 "serial_number": "12345", "device_type": "6-0050F204-1",
1471 "os_version": "01020300",
1472 "config_methods": "label push_button",
1473 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1474
1475 logger.info("Connect ER to the AP")
1476 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
1477
1478 logger.info("WPS configuration step")
1479 dev[0].request("WPS_ER_START ifname=lo")
1480 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1481 if ev is None:
1482 raise Exception("AP discovery timed out")
1483 if ap_uuid not in ev:
1484 raise Exception("Expected AP UUID not found")
1485 new_passphrase = "1234567890"
1486 dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
1487 ssid.encode("hex") + " WPA2PSK CCMP " +
1488 new_passphrase.encode("hex"))
1489 ev = dev[0].wait_event(["WPS-SUCCESS"])
1490 if ev is None:
1491 raise Exception("WPS ER configuration operation timed out")
5f35a5e2 1492 dev[0].wait_disconnected(timeout=10)
be923570
JM
1493 dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
1494
8f8c2fe8
JM
1495 logger.info("WPS ER restart")
1496 dev[0].request("WPS_ER_START")
1497 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1498 if ev is None:
1499 raise Exception("AP discovery timed out on ER restart")
1500 if ap_uuid not in ev:
1501 raise Exception("Expected AP UUID not found on ER restart")
1502 if "OK" not in dev[0].request("WPS_ER_STOP"):
1503 raise Exception("WPS_ER_STOP failed")
1504 if "OK" not in dev[0].request("WPS_ER_STOP"):
1505 raise Exception("WPS_ER_STOP failed")
1506
6aaa661a
JM
1507def test_ap_wps_er_cache_ap_settings(dev, apdev):
1508 """WPS ER caching AP settings"""
1509 try:
1510 _test_ap_wps_er_cache_ap_settings(dev, apdev)
1511 finally:
1512 dev[0].request("WPS_ER_STOP")
1513
1514def _test_ap_wps_er_cache_ap_settings(dev, apdev):
1515 ssid = "wps-er-add-enrollee"
1516 ap_pin = "12345670"
1517 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1518 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1519 "wpa_passphrase": "12345678", "wpa": "2",
1520 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1521 "device_name": "Wireless AP", "manufacturer": "Company",
1522 "model_name": "WAP", "model_number": "123",
1523 "serial_number": "12345", "device_type": "6-0050F204-1",
1524 "os_version": "01020300",
1525 "config_methods": "label push_button",
1526 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
1527 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1528 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1529 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1530 id = int(dev[0].list_networks()[0]['id'])
1531 dev[0].set_network(id, "scan_freq", "2412")
1532
1533 dev[0].request("WPS_ER_START ifname=lo")
1534 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1535 if ev is None:
1536 raise Exception("AP discovery timed out")
1537 if ap_uuid not in ev:
1538 raise Exception("Expected AP UUID not found")
1539
1540 dev[0].dump_monitor()
1541 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1542 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1543 if ev is None:
1544 raise Exception("AP learn timed out")
1545 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1546 if ev is None:
1547 raise Exception("WPS-FAIL after AP learn timed out")
1548 time.sleep(0.1)
1549
1550 hapd.disable()
1551
1552 for i in range(2):
1553 ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1554 "CTRL-EVENT-DISCONNECTED" ],
1555 timeout=15)
1556 if ev is None:
1557 raise Exception("AP removal or disconnection timed out")
1558
1559 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1560 for i in range(2):
1561 ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1562 timeout=15)
1563 if ev is None:
1564 raise Exception("AP discovery or connection timed out")
1565
1566 pin = dev[1].wps_read_pin()
1567 dev[0].dump_monitor()
1568 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1569
1570 time.sleep(0.2)
1571
1572 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1573 dev[1].dump_monitor()
1574 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1575 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
1576 if ev is None:
1577 raise Exception("Enrollee did not report success")
1578 dev[1].wait_connected(timeout=15)
1579 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1580 if ev is None:
1581 raise Exception("WPS ER did not report success")
1582
1583 dev[0].dump_monitor()
1584 dev[0].request("WPS_ER_STOP")
1585
d840350a
JM
1586def test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1587 """WPS ER caching AP settings (OOM)"""
1588 try:
1589 _test_ap_wps_er_cache_ap_settings_oom(dev, apdev)
1590 finally:
1591 dev[0].request("WPS_ER_STOP")
1592
1593def _test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1594 ssid = "wps-er-add-enrollee"
1595 ap_pin = "12345670"
1596 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1597 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1598 "wpa_passphrase": "12345678", "wpa": "2",
1599 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1600 "device_name": "Wireless AP", "manufacturer": "Company",
1601 "model_name": "WAP", "model_number": "123",
1602 "serial_number": "12345", "device_type": "6-0050F204-1",
1603 "os_version": "01020300",
1604 "config_methods": "label push_button",
1605 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
1606 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1607 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1608 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1609 id = int(dev[0].list_networks()[0]['id'])
1610 dev[0].set_network(id, "scan_freq", "2412")
1611
1612 dev[0].request("WPS_ER_START ifname=lo")
1613 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1614 if ev is None:
1615 raise Exception("AP discovery timed out")
1616 if ap_uuid not in ev:
1617 raise Exception("Expected AP UUID not found")
1618
1619 dev[0].dump_monitor()
1620 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1621 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1622 if ev is None:
1623 raise Exception("AP learn timed out")
1624 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1625 if ev is None:
1626 raise Exception("WPS-FAIL after AP learn timed out")
1627 time.sleep(0.1)
1628
1629 with alloc_fail(dev[0], 1, "=wps_er_ap_use_cached_settings"):
1630 hapd.disable()
1631
1632 for i in range(2):
1633 ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1634 "CTRL-EVENT-DISCONNECTED" ],
1635 timeout=15)
1636 if ev is None:
1637 raise Exception("AP removal or disconnection timed out")
1638
1639 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1640 for i in range(2):
1641 ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1642 timeout=15)
1643 if ev is None:
1644 raise Exception("AP discovery or connection timed out")
1645
1646 dev[0].request("WPS_ER_STOP")
1647
1648def test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1649 """WPS ER caching AP settings (OOM 2)"""
1650 try:
1651 _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev)
1652 finally:
1653 dev[0].request("WPS_ER_STOP")
1654
1655def _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1656 ssid = "wps-er-add-enrollee"
1657 ap_pin = "12345670"
1658 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1659 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1660 "wpa_passphrase": "12345678", "wpa": "2",
1661 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1662 "device_name": "Wireless AP", "manufacturer": "Company",
1663 "model_name": "WAP", "model_number": "123",
1664 "serial_number": "12345", "device_type": "6-0050F204-1",
1665 "os_version": "01020300",
1666 "config_methods": "label push_button",
1667 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
1668 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1669 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1670 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1671 id = int(dev[0].list_networks()[0]['id'])
1672 dev[0].set_network(id, "scan_freq", "2412")
1673
1674 dev[0].request("WPS_ER_START ifname=lo")
1675 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1676 if ev is None:
1677 raise Exception("AP discovery timed out")
1678 if ap_uuid not in ev:
1679 raise Exception("Expected AP UUID not found")
1680
1681 dev[0].dump_monitor()
1682 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1683 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1684 if ev is None:
1685 raise Exception("AP learn timed out")
1686 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1687 if ev is None:
1688 raise Exception("WPS-FAIL after AP learn timed out")
1689 time.sleep(0.1)
1690
1691 with alloc_fail(dev[0], 1, "=wps_er_ap_cache_settings"):
1692 hapd.disable()
1693
1694 for i in range(2):
1695 ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1696 "CTRL-EVENT-DISCONNECTED" ],
1697 timeout=15)
1698 if ev is None:
1699 raise Exception("AP removal or disconnection timed out")
1700
1701 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1702 for i in range(2):
1703 ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1704 timeout=15)
1705 if ev is None:
1706 raise Exception("AP discovery or connection timed out")
1707
1708 dev[0].request("WPS_ER_STOP")
1709
eb95ced2
JM
1710def test_ap_wps_er_subscribe_oom(dev, apdev):
1711 """WPS ER subscribe OOM"""
1712 try:
1713 _test_ap_wps_er_subscribe_oom(dev, apdev)
1714 finally:
1715 dev[0].request("WPS_ER_STOP")
1716
1717def _test_ap_wps_er_subscribe_oom(dev, apdev):
1718 ssid = "wps-er-add-enrollee"
1719 ap_pin = "12345670"
1720 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1721 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1722 "wpa_passphrase": "12345678", "wpa": "2",
1723 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1724 "device_name": "Wireless AP", "manufacturer": "Company",
1725 "model_name": "WAP", "model_number": "123",
1726 "serial_number": "12345", "device_type": "6-0050F204-1",
1727 "os_version": "01020300",
1728 "config_methods": "label push_button",
1729 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
1730 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1731 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1732 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1733 id = int(dev[0].list_networks()[0]['id'])
1734 dev[0].set_network(id, "scan_freq", "2412")
1735
1736 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_subscribe"):
1737 dev[0].request("WPS_ER_START ifname=lo")
1738 for i in range(50):
1739 res = dev[0].request("GET_ALLOC_FAIL")
1740 if res.startswith("0:"):
1741 break
1742 time.sleep(0.1)
1743 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=0)
1744 if ev:
1745 raise Exception("Unexpected AP discovery during OOM")
1746
1747 dev[0].request("WPS_ER_STOP")
1748
db9c88eb
JM
1749def test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1750 """WPS ER SetSelectedRegistrar OOM"""
1751 try:
1752 _test_ap_wps_er_set_sel_reg_oom(dev, apdev)
1753 finally:
1754 dev[0].request("WPS_ER_STOP")
1755
1756def _test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1757 ssid = "wps-er-add-enrollee"
1758 ap_pin = "12345670"
1759 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1760 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1761 "wpa_passphrase": "12345678", "wpa": "2",
1762 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1763 "device_name": "Wireless AP", "manufacturer": "Company",
1764 "model_name": "WAP", "model_number": "123",
1765 "serial_number": "12345", "device_type": "6-0050F204-1",
1766 "os_version": "01020300",
1767 "config_methods": "label push_button",
1768 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
1769 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1770 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1771 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1772
1773 dev[0].request("WPS_ER_START ifname=lo")
1774 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1775 if ev is None:
1776 raise Exception("AP not discovered")
1777
1778 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1779 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1780 if ev is None:
1781 raise Exception("AP learn timed out")
1782 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1783 if ev is None:
1784 raise Exception("WPS-FAIL timed out")
1785 time.sleep(0.1)
1786
1787 for func in [ "http_client_url_parse;wps_er_send_set_sel_reg",
1788 "wps_er_soap_hdr;wps_er_send_set_sel_reg",
1789 "http_client_addr;wps_er_send_set_sel_reg",
1790 "wpabuf_alloc;wps_er_set_sel_reg" ]:
1791 with alloc_fail(dev[0], 1, func):
1792 if "OK" not in dev[0].request("WPS_ER_PBC " + ap_uuid):
1793 raise Exception("WPS_ER_PBC failed")
1794 ev = dev[0].wait_event(["WPS-PBC-ACTIVE"], timeout=3)
1795 if ev is None:
1796 raise Exception("WPS-PBC-ACTIVE not seen")
1797
1798 dev[0].request("WPS_ER_STOP")
1799
ae3eacf7
JM
1800def test_ap_wps_er_learn_oom(dev, apdev):
1801 """WPS ER learn OOM"""
1802 try:
1803 _test_ap_wps_er_learn_oom(dev, apdev)
1804 finally:
1805 dev[0].request("WPS_ER_STOP")
1806
1807def _test_ap_wps_er_learn_oom(dev, apdev):
1808 ssid = "wps-er-add-enrollee"
1809 ap_pin = "12345670"
1810 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1811 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1812 "wpa_passphrase": "12345678", "wpa": "2",
1813 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1814 "device_name": "Wireless AP", "manufacturer": "Company",
1815 "model_name": "WAP", "model_number": "123",
1816 "serial_number": "12345", "device_type": "6-0050F204-1",
1817 "os_version": "01020300",
1818 "config_methods": "label push_button",
1819 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
1820 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1821 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1822 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1823
1824 dev[0].request("WPS_ER_START ifname=lo")
1825 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1826 if ev is None:
1827 raise Exception("AP not discovered")
1828
1829 for func in [ "wps_er_http_put_message_cb",
1830 "xml_get_base64_item;wps_er_http_put_message_cb",
1831 "http_client_url_parse;wps_er_ap_put_message",
1832 "wps_er_soap_hdr;wps_er_ap_put_message",
1833 "http_client_addr;wps_er_ap_put_message" ]:
1834 with alloc_fail(dev[0], 1, func):
1835 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1836 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=1)
1837 if ev is not None:
1838 raise Exception("AP learn succeeded during OOM")
1839
1840 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1841 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=10)
1842 if ev is None:
1843 raise Exception("AP learn did not succeed")
1844
1845 if "FAIL" not in dev[0].request("WPS_ER_LEARN 00000000-9e5c-4e73-bd82-f89cbcd10d7e " + ap_pin):
1846 raise Exception("WPS_ER_LEARN for unknown AP accepted")
1847
1848 dev[0].request("WPS_ER_STOP")
1849
bff3ac5b
JM
1850def test_ap_wps_fragmentation(dev, apdev):
1851 """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
1852 ssid = "test-wps-fragmentation"
9602b355 1853 appin = "12345670"
bff3ac5b
JM
1854 hostapd.add_ap(apdev[0]['ifname'],
1855 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1856 "wpa_passphrase": "12345678", "wpa": "3",
1857 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9602b355 1858 "wpa_pairwise": "TKIP", "ap_pin": appin,
bff3ac5b
JM
1859 "fragment_size": "50" })
1860 hapd = hostapd.Hostapd(apdev[0]['ifname'])
9602b355 1861 logger.info("WPS provisioning step (PBC)")
bff3ac5b 1862 hapd.request("WPS_PBC")
33d0b157 1863 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
bff3ac5b
JM
1864 dev[0].dump_monitor()
1865 dev[0].request("SET wps_fragment_size 50")
33d0b157 1866 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1867 dev[0].wait_connected(timeout=30)
bff3ac5b
JM
1868 status = dev[0].get_status()
1869 if status['wpa_state'] != 'COMPLETED':
9602b355
JM
1870 raise Exception("Not fully connected")
1871 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1872 raise Exception("Unexpected encryption configuration")
1873 if status['key_mgmt'] != 'WPA2-PSK':
1874 raise Exception("Unexpected key_mgmt")
1875
1876 logger.info("WPS provisioning step (PIN)")
1877 pin = dev[1].wps_read_pin()
1878 hapd.request("WPS_PIN any " + pin)
33d0b157 1879 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
9602b355 1880 dev[1].request("SET wps_fragment_size 50")
33d0b157 1881 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 1882 dev[1].wait_connected(timeout=30)
9602b355
JM
1883 status = dev[1].get_status()
1884 if status['wpa_state'] != 'COMPLETED':
1885 raise Exception("Not fully connected")
1886 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1887 raise Exception("Unexpected encryption configuration")
1888 if status['key_mgmt'] != 'WPA2-PSK':
1889 raise Exception("Unexpected key_mgmt")
1890
1891 logger.info("WPS connection as registrar")
33d0b157 1892 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
9602b355
JM
1893 dev[2].request("SET wps_fragment_size 50")
1894 dev[2].wps_reg(apdev[0]['bssid'], appin)
1895 status = dev[2].get_status()
1896 if status['wpa_state'] != 'COMPLETED':
bff3ac5b
JM
1897 raise Exception("Not fully connected")
1898 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1899 raise Exception("Unexpected encryption configuration")
1900 if status['key_mgmt'] != 'WPA2-PSK':
1901 raise Exception("Unexpected key_mgmt")
10ea6848
JM
1902
1903def test_ap_wps_new_version_sta(dev, apdev):
1904 """WPS compatibility with new version number on the station"""
1905 ssid = "test-wps-ver"
1906 hostapd.add_ap(apdev[0]['ifname'],
1907 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1908 "wpa_passphrase": "12345678", "wpa": "2",
1909 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1910 hapd = hostapd.Hostapd(apdev[0]['ifname'])
1911 logger.info("WPS provisioning step")
1912 hapd.request("WPS_PBC")
33d0b157 1913 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10ea6848
JM
1914 dev[0].dump_monitor()
1915 dev[0].request("SET wps_version_number 0x43")
dccafedb 1916 dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
33d0b157 1917 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1918 dev[0].wait_connected(timeout=30)
10ea6848
JM
1919
1920def test_ap_wps_new_version_ap(dev, apdev):
1921 """WPS compatibility with new version number on the AP"""
1922 ssid = "test-wps-ver"
1923 hostapd.add_ap(apdev[0]['ifname'],
1924 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1925 "wpa_passphrase": "12345678", "wpa": "2",
1926 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1927 hapd = hostapd.Hostapd(apdev[0]['ifname'])
1928 logger.info("WPS provisioning step")
1929 if "FAIL" in hapd.request("SET wps_version_number 0x43"):
1930 raise Exception("Failed to enable test functionality")
1931 hapd.request("WPS_PBC")
33d0b157 1932 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10ea6848 1933 dev[0].dump_monitor()
33d0b157 1934 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1935 dev[0].wait_connected(timeout=30)
10ea6848 1936 hapd.request("SET wps_version_number 0x20")
3bdf7d7f
JM
1937
1938def test_ap_wps_check_pin(dev, apdev):
1939 """Verify PIN checking through control interface"""
1940 hostapd.add_ap(apdev[0]['ifname'],
1941 { "ssid": "wps", "eap_server": "1", "wps_state": "2",
1942 "wpa_passphrase": "12345678", "wpa": "2",
1943 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1944 hapd = hostapd.Hostapd(apdev[0]['ifname'])
1945 for t in [ ("12345670", "12345670"),
1946 ("12345678", "FAIL-CHECKSUM"),
df58939c 1947 ("12345", "FAIL"),
6e12eaa4 1948 ("123456789", "FAIL"),
3bdf7d7f
JM
1949 ("1234-5670", "12345670"),
1950 ("1234 5670", "12345670"),
1951 ("1-2.3:4 5670", "12345670") ]:
1952 res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
1953 res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
1954 if res != res2:
1955 raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
1956 if res != t[1]:
1957 raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
9ba1fcb0 1958
ac786d67
JM
1959 if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
1960 raise Exception("Unexpected WPS_CHECK_PIN success")
1961 if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
1962 raise Exception("Unexpected WPS_CHECK_PIN success")
1963
acd9b45a
JM
1964 for i in range(0, 10):
1965 pin = dev[0].request("WPS_PIN get")
1966 rpin = dev[0].request("WPS_CHECK_PIN " + pin).rstrip('\n')
1967 if pin != rpin:
1968 raise Exception("Random PIN validation failed for " + pin)
1969
9ba1fcb0
JM
1970def test_ap_wps_wep_config(dev, apdev):
1971 """WPS 2.0 AP rejecting WEP configuration"""
1972 ssid = "test-wps-config"
1973 appin = "12345670"
1974 hostapd.add_ap(apdev[0]['ifname'],
1975 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1976 "ap_pin": appin})
1977 hapd = hostapd.Hostapd(apdev[0]['ifname'])
33d0b157 1978 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
9ba1fcb0
JM
1979 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
1980 "hello", no_wait=True)
1981 ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
1982 if ev is None:
1983 raise Exception("WPS-FAIL timed out")
1984 if "reason=2" not in ev:
1985 raise Exception("Unexpected reason code in WPS-FAIL")
1986 status = hapd.request("WPS_GET_STATUS")
1987 if "Last WPS result: Failed" not in status:
1988 raise Exception("WPS failure result not shown correctly")
1989 if "Failure Reason: WEP Prohibited" not in status:
1990 raise Exception("Failure reason not reported correctly")
1991 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
1992 raise Exception("Peer address not shown correctly")
1013a576 1993
11d78bb1
JM
1994def test_ap_wps_wep_enroll(dev, apdev):
1995 """WPS 2.0 STA rejecting WEP configuration"""
1996 ssid = "test-wps-wep"
1997 hostapd.add_ap(apdev[0]['ifname'],
1998 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1999 "skip_cred_build": "1", "extra_cred": "wps-wep-cred" })
2000 hapd = hostapd.Hostapd(apdev[0]['ifname'])
2001 hapd.request("WPS_PBC")
33d0b157
JM
2002 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2003 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
11d78bb1
JM
2004 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
2005 if ev is None:
2006 raise Exception("WPS-FAIL event timed out")
2007 if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
2008 raise Exception("Unexpected WPS-FAIL event: " + ev)
2009
1013a576
JM
2010def test_ap_wps_ie_fragmentation(dev, apdev):
2011 """WPS AP using fragmented WPS IE"""
2012 ssid = "test-wps-ie-fragmentation"
2013 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2014 "wpa_passphrase": "12345678", "wpa": "2",
2015 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2016 "device_name": "1234567890abcdef1234567890abcdef",
2017 "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
2018 "model_name": "1234567890abcdef1234567890abcdef",
2019 "model_number": "1234567890abcdef1234567890abcdef",
2020 "serial_number": "1234567890abcdef1234567890abcdef" }
2021 hostapd.add_ap(apdev[0]['ifname'], params)
2022 hapd = hostapd.Hostapd(apdev[0]['ifname'])
2023 hapd.request("WPS_PBC")
33d0b157
JM
2024 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2025 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2026 dev[0].wait_connected(timeout=30)
1013a576
JM
2027 bss = dev[0].get_bss(apdev[0]['bssid'])
2028 if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
cf3f0ec8 2029 logger.info("Device Name not received correctly")
d7a68ad6 2030 logger.info(bss)
cf3f0ec8
JM
2031 # This can fail if Probe Response frame is missed and Beacon frame was
2032 # used to fill in the BSS entry. This can happen, e.g., during heavy
2033 # load every now and then and is not really an error, so try to
2034 # workaround by runnign another scan.
2035 dev[0].scan(freq="2412", only_new=True)
2036 bss = dev[0].get_bss(apdev[0]['bssid'])
84a40841 2037 if not bss or "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
cf3f0ec8
JM
2038 logger.info(bss)
2039 raise Exception("Device Name not received correctly")
1013a576
JM
2040 if len(re.findall("dd..0050f204", bss['ie'])) != 2:
2041 raise Exception("Unexpected number of WPS IEs")
44ff0400 2042
2035b170
JM
2043def get_psk(pskfile):
2044 psks = {}
2045 with open(pskfile, "r") as f:
2046 lines = f.read().splitlines()
2047 for l in lines:
2048 if l == "# WPA PSKs":
2049 continue
2050 (addr,psk) = l.split(' ')
2051 psks[addr] = psk
2052 return psks
2053
2054def test_ap_wps_per_station_psk(dev, apdev):
2055 """WPS PBC provisioning with per-station PSK"""
1d21a5be
B
2056 addr0 = dev[0].own_addr()
2057 addr1 = dev[1].own_addr()
2058 addr2 = dev[2].own_addr()
2035b170
JM
2059 ssid = "wps"
2060 appin = "12345670"
2061 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2062 try:
2063 os.remove(pskfile)
2064 except:
2065 pass
2066
4f524e99 2067 hapd = None
2035b170
JM
2068 try:
2069 with open(pskfile, "w") as f:
2070 f.write("# WPA PSKs\n")
2071
2072 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2073 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2074 "rsn_pairwise": "CCMP", "ap_pin": appin,
2075 "wpa_psk_file": pskfile }
2076 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2077
2078 logger.info("First enrollee")
2079 hapd.request("WPS_PBC")
33d0b157
JM
2080 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2081 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2082 dev[0].wait_connected(timeout=30)
2035b170
JM
2083
2084 logger.info("Second enrollee")
2085 hapd.request("WPS_PBC")
33d0b157
JM
2086 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2087 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2088 dev[1].wait_connected(timeout=30)
2035b170
JM
2089
2090 logger.info("External registrar")
33d0b157 2091 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2035b170
JM
2092 dev[2].wps_reg(apdev[0]['bssid'], appin)
2093
2094 logger.info("Verifying PSK results")
2095 psks = get_psk(pskfile)
2096 if addr0 not in psks:
2097 raise Exception("No PSK recorded for sta0")
2098 if addr1 not in psks:
2099 raise Exception("No PSK recorded for sta1")
2100 if addr2 not in psks:
2101 raise Exception("No PSK recorded for sta2")
2102 if psks[addr0] == psks[addr1]:
2103 raise Exception("Same PSK recorded for sta0 and sta1")
2104 if psks[addr0] == psks[addr2]:
2105 raise Exception("Same PSK recorded for sta0 and sta2")
2106 if psks[addr1] == psks[addr2]:
2107 raise Exception("Same PSK recorded for sta1 and sta2")
2108
2109 dev[0].request("REMOVE_NETWORK all")
2110 logger.info("Second external registrar")
33d0b157 2111 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2035b170
JM
2112 dev[0].wps_reg(apdev[0]['bssid'], appin)
2113 psks2 = get_psk(pskfile)
2114 if addr0 not in psks2:
2115 raise Exception("No PSK recorded for sta0(reg)")
2116 if psks[addr0] == psks2[addr0]:
2117 raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
2118 finally:
2119 os.remove(pskfile)
4f524e99
JM
2120 if hapd:
2121 dev[0].request("DISCONNECT")
2122 dev[1].request("DISCONNECT")
2123 dev[2].request("DISCONNECT")
2124 hapd.disable()
2125 dev[0].flush_scan_cache()
2126 dev[1].flush_scan_cache()
2127 dev[2].flush_scan_cache()
2035b170 2128
373cce55
JM
2129def test_ap_wps_per_station_psk_failure(dev, apdev):
2130 """WPS PBC provisioning with per-station PSK (file not writable)"""
2131 addr0 = dev[0].p2p_dev_addr()
2132 addr1 = dev[1].p2p_dev_addr()
2133 addr2 = dev[2].p2p_dev_addr()
2134 ssid = "wps"
2135 appin = "12345670"
2136 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2137 try:
2138 os.remove(pskfile)
2139 except:
2140 pass
2141
2142 try:
2143 with open(pskfile, "w") as f:
2144 f.write("# WPA PSKs\n")
2145
2146 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2147 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2148 "rsn_pairwise": "CCMP", "ap_pin": appin,
2149 "wpa_psk_file": pskfile }
2150 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2151 if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
2152 raise Exception("Failed to set wpa_psk_file")
2153
2154 logger.info("First enrollee")
2155 hapd.request("WPS_PBC")
33d0b157
JM
2156 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2157 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2158 dev[0].wait_connected(timeout=30)
373cce55
JM
2159
2160 logger.info("Second enrollee")
2161 hapd.request("WPS_PBC")
33d0b157
JM
2162 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2163 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2164 dev[1].wait_connected(timeout=30)
373cce55
JM
2165
2166 logger.info("External registrar")
33d0b157 2167 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
373cce55
JM
2168 dev[2].wps_reg(apdev[0]['bssid'], appin)
2169
2170 logger.info("Verifying PSK results")
2171 psks = get_psk(pskfile)
2172 if len(psks) > 0:
2173 raise Exception("PSK recorded unexpectedly")
2174 finally:
2175 os.remove(pskfile)
2176
e8518757
JM
2177def test_ap_wps_pin_request_file(dev, apdev):
2178 """WPS PIN provisioning with configured AP"""
2179 ssid = "wps"
2180 pinfile = "/tmp/ap_wps_pin_request_file.log"
2181 if os.path.exists(pinfile):
b638f703 2182 os.remove(pinfile)
e8518757
JM
2183 hostapd.add_ap(apdev[0]['ifname'],
2184 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2185 "wps_pin_requests": pinfile,
2186 "wpa_passphrase": "12345678", "wpa": "2",
2187 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2188 hapd = hostapd.Hostapd(apdev[0]['ifname'])
2189 uuid = dev[0].get_status_field("uuid")
2190 pin = dev[0].wps_read_pin()
2191 try:
33d0b157
JM
2192 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2193 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
e8518757
JM
2194 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
2195 if ev is None:
2196 raise Exception("PIN needed event not shown")
2197 if uuid not in ev:
2198 raise Exception("UUID mismatch")
2199 dev[0].request("WPS_CANCEL")
2200 success = False
2201 with open(pinfile, "r") as f:
2202 lines = f.readlines()
2203 for l in lines:
2204 if uuid in l:
2205 success = True
2206 break
2207 if not success:
2208 raise Exception("PIN request entry not in the log file")
2209 finally:
b638f703
JM
2210 try:
2211 os.remove(pinfile)
2212 except:
2213 pass
e8518757 2214
56887c35
JM
2215def test_ap_wps_auto_setup_with_config_file(dev, apdev):
2216 """WPS auto-setup with configuration file"""
2217 conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
2218 ifname = apdev[0]['ifname']
2219 try:
2220 with open(conffile, "w") as f:
2221 f.write("driver=nl80211\n")
2222 f.write("hw_mode=g\n")
2223 f.write("channel=1\n")
2224 f.write("ieee80211n=1\n")
2225 f.write("interface=%s\n" % ifname)
2226 f.write("ctrl_interface=/var/run/hostapd\n")
2227 f.write("ssid=wps\n")
2228 f.write("eap_server=1\n")
2229 f.write("wps_state=1\n")
2230 hostapd.add_bss('phy3', ifname, conffile)
2231 hapd = hostapd.Hostapd(ifname)
2232 hapd.request("WPS_PBC")
33d0b157
JM
2233 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2234 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2235 dev[0].wait_connected(timeout=30)
56887c35
JM
2236 with open(conffile, "r") as f:
2237 lines = f.read().splitlines()
2238 vals = dict()
2239 for l in lines:
2240 try:
2241 [name,value] = l.split('=', 1)
2242 vals[name] = value
2243 except ValueError, e:
2244 if "# WPS configuration" in l:
2245 pass
2246 else:
2247 raise Exception("Unexpected configuration line: " + l)
2248 if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
2249 raise Exception("Incorrect configuration: " + str(vals))
2250 finally:
b638f703
JM
2251 try:
2252 os.remove(conffile)
2253 except:
2254 pass
56887c35 2255
91f3cf69 2256def test_ap_wps_pbc_timeout(dev, apdev, params):
31e56b95 2257 """wpa_supplicant PBC walk time and WPS ER SelReg timeout [long]"""
91f3cf69 2258 if not params['long']:
81e787b7 2259 raise HwsimSkip("Skip test case with long duration due to --long not specified")
31e56b95
JM
2260 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2261 hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2262
2263 location = ssdp_get_location(ap_uuid)
2264 urls = upnp_get_urls(location)
2265 eventurl = urlparse.urlparse(urls['event_sub_url'])
2266 ctrlurl = urlparse.urlparse(urls['control_url'])
2267
2268 url = urlparse.urlparse(location)
2269 conn = httplib.HTTPConnection(url.netloc)
2270
2271 class WPSERHTTPServer(SocketServer.StreamRequestHandler):
2272 def handle(self):
2273 data = self.rfile.readline().strip()
2274 logger.debug(data)
2275 self.wfile.write(gen_wps_event())
2276
2277 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
2278 server.timeout = 1
2279
2280 headers = { "callback": '<http://127.0.0.1:12345/event>',
2281 "NT": "upnp:event",
2282 "timeout": "Second-1234" }
2283 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2284 resp = conn.getresponse()
2285 if resp.status != 200:
2286 raise Exception("Unexpected HTTP response: %d" % resp.status)
2287 sid = resp.getheader("sid")
2288 logger.debug("Subscription SID " + sid)
2289
2290 msg = '''<?xml version="1.0"?>
2291<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
2292<s:Body>
2293<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
2294<NewMessage>EEoAARAQQQABARASAAIAABBTAAIxSBBJAA4ANyoAASABBv///////xBIABA2LbR7pTpRkYj7
2295VFi5hrLk
2296</NewMessage>
2297</u:SetSelectedRegistrar>
2298</s:Body>
2299</s:Envelope>'''
2300 headers = { "Content-type": 'text/xml; charset="utf-8"' }
2301 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
2302 conn.request("POST", ctrlurl.path, msg, headers)
2303 resp = conn.getresponse()
2304 if resp.status != 200:
2305 raise Exception("Unexpected HTTP response: %d" % resp.status)
2306
2307 server.handle_request()
2308
91f3cf69
JM
2309 logger.info("Start WPS_PBC and wait for PBC walk time expiration")
2310 if "OK" not in dev[0].request("WPS_PBC"):
2311 raise Exception("WPS_PBC failed")
31e56b95
JM
2312
2313 start = os.times()[4]
2314
2315 server.handle_request()
2316 dev[1].request("BSS_FLUSH 0")
2317 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2318 only_new=True)
2319 bss = dev[1].get_bss(apdev[0]['bssid'])
2320 logger.debug("BSS: " + str(bss))
2321 if '[WPS-AUTH]' not in bss['flags']:
2322 raise Exception("WPS not indicated authorized")
2323
2324 server.handle_request()
2325
2326 wps_timeout_seen = False
2327
2328 while True:
2329 hapd.dump_monitor()
2330 dev[1].dump_monitor()
2331 if not wps_timeout_seen:
2332 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=0)
2333 if ev is not None:
2334 logger.info("PBC timeout seen")
2335 wps_timeout_seen = True
2336 else:
2337 dev[0].dump_monitor()
2338 now = os.times()[4]
2339 if now - start > 130:
2340 raise Exception("Selected registration information not removed")
2341 dev[1].request("BSS_FLUSH 0")
2342 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2343 only_new=True)
2344 bss = dev[1].get_bss(apdev[0]['bssid'])
2345 logger.debug("BSS: " + str(bss))
2346 if '[WPS-AUTH]' not in bss['flags']:
2347 break
2348 server.handle_request()
2349
2350 server.server_close()
2351
2352 if wps_timeout_seen:
2353 return
2354
2355 now = os.times()[4]
2356 if now < start + 150:
2357 dur = start + 150 - now
2358 else:
2359 dur = 1
2360 logger.info("Continue waiting for PBC timeout (%d sec)" % dur)
2361 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=dur)
91f3cf69
JM
2362 if ev is None:
2363 raise Exception("WPS-TIMEOUT not reported")
2364
44ff0400
JM
2365def add_ssdp_ap(ifname, ap_uuid):
2366 ssid = "wps-ssdp"
2367 ap_pin = "12345670"
24b7f282
JM
2368 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2369 "wpa_passphrase": "12345678", "wpa": "2",
2370 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2371 "device_name": "Wireless AP", "manufacturer": "Company",
2372 "model_name": "WAP", "model_number": "123",
2373 "serial_number": "12345", "device_type": "6-0050F204-1",
2374 "os_version": "01020300",
2375 "config_methods": "label push_button",
2376 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
2377 "friendly_name": "WPS Access Point",
2378 "manufacturer_url": "http://www.example.com/",
2379 "model_description": "Wireless Access Point",
2380 "model_url": "http://www.example.com/model/",
2381 "upc": "123456789012" }
2382 return hostapd.add_ap(ifname, params)
44ff0400
JM
2383
2384def ssdp_send(msg, no_recv=False):
2385 socket.setdefaulttimeout(1)
2386 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2387 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2388 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2389 sock.bind(("127.0.0.1", 0))
2390 sock.sendto(msg, ("239.255.255.250", 1900))
2391 if no_recv:
2392 return None
2393 return sock.recv(1000)
2394
96038a5f 2395def ssdp_send_msearch(st, no_recv=False):
44ff0400
JM
2396 msg = '\r\n'.join([
2397 'M-SEARCH * HTTP/1.1',
2398 'HOST: 239.255.255.250:1900',
2399 'MX: 1',
2400 'MAN: "ssdp:discover"',
2401 'ST: ' + st,
2402 '', ''])
96038a5f 2403 return ssdp_send(msg, no_recv=no_recv)
44ff0400
JM
2404
2405def test_ap_wps_ssdp_msearch(dev, apdev):
2406 """WPS AP and SSDP M-SEARCH messages"""
2407 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2408 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2409
2410 msg = '\r\n'.join([
2411 'M-SEARCH * HTTP/1.1',
2412 'Host: 239.255.255.250:1900',
2413 'Mx: 1',
2414 'Man: "ssdp:discover"',
2415 'St: urn:schemas-wifialliance-org:device:WFADevice:1',
2416 '', ''])
2417 ssdp_send(msg)
2418
2419 msg = '\r\n'.join([
2420 'M-SEARCH * HTTP/1.1',
2421 'host:\t239.255.255.250:1900\t\t\t\t \t\t',
2422 'mx: \t1\t\t ',
2423 'man: \t \t "ssdp:discover" ',
2424 'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
2425 '', ''])
2426 ssdp_send(msg)
2427
2428 ssdp_send_msearch("ssdp:all")
2429 ssdp_send_msearch("upnp:rootdevice")
2430 ssdp_send_msearch("uuid:" + ap_uuid)
2431 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
2432 ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1");
2433
2434 msg = '\r\n'.join([
2435 'M-SEARCH * HTTP/1.1',
2436 'HOST:\t239.255.255.250:1900',
2437 'MAN: "ssdp:discover"',
2438 'MX: 130',
2439 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2440 '', ''])
2441 ssdp_send(msg, no_recv=True)
2442
2443def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
2444 """WPS AP and invalid SSDP M-SEARCH messages"""
2445 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2446 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2447
2448 socket.setdefaulttimeout(1)
2449 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2450 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2451 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2452 sock.bind(("127.0.0.1", 0))
2453
2454 logger.debug("Missing MX")
2455 msg = '\r\n'.join([
2456 'M-SEARCH * HTTP/1.1',
2457 'HOST: 239.255.255.250:1900',
2458 'MAN: "ssdp:discover"',
2459 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2460 '', ''])
2461 sock.sendto(msg, ("239.255.255.250", 1900))
2462
2463 logger.debug("Negative MX")
2464 msg = '\r\n'.join([
2465 'M-SEARCH * HTTP/1.1',
2466 'HOST: 239.255.255.250:1900',
2467 'MX: -1',
2468 'MAN: "ssdp:discover"',
2469 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2470 '', ''])
2471 sock.sendto(msg, ("239.255.255.250", 1900))
2472
2473 logger.debug("Invalid MX")
2474 msg = '\r\n'.join([
2475 'M-SEARCH * HTTP/1.1',
2476 'HOST: 239.255.255.250:1900',
2477 'MX; 1',
2478 'MAN: "ssdp:discover"',
2479 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2480 '', ''])
2481 sock.sendto(msg, ("239.255.255.250", 1900))
2482
2483 logger.debug("Missing MAN")
2484 msg = '\r\n'.join([
2485 'M-SEARCH * HTTP/1.1',
2486 'HOST: 239.255.255.250:1900',
2487 'MX: 1',
2488 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2489 '', ''])
2490 sock.sendto(msg, ("239.255.255.250", 1900))
2491
2492 logger.debug("Invalid MAN")
2493 msg = '\r\n'.join([
2494 'M-SEARCH * HTTP/1.1',
2495 'HOST: 239.255.255.250:1900',
2496 'MX: 1',
2497 'MAN: foo',
2498 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2499 '', ''])
2500 sock.sendto(msg, ("239.255.255.250", 1900))
2501 msg = '\r\n'.join([
2502 'M-SEARCH * HTTP/1.1',
2503 'HOST: 239.255.255.250:1900',
2504 'MX: 1',
2505 'MAN; "ssdp:discover"',
2506 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2507 '', ''])
2508 sock.sendto(msg, ("239.255.255.250", 1900))
2509
2510 logger.debug("Missing HOST")
2511 msg = '\r\n'.join([
2512 'M-SEARCH * HTTP/1.1',
2513 'MAN: "ssdp:discover"',
2514 'MX: 1',
2515 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2516 '', ''])
2517 sock.sendto(msg, ("239.255.255.250", 1900))
2518
2519 logger.debug("Missing ST")
2520 msg = '\r\n'.join([
2521 'M-SEARCH * HTTP/1.1',
2522 'HOST: 239.255.255.250:1900',
2523 'MAN: "ssdp:discover"',
2524 'MX: 1',
2525 '', ''])
2526 sock.sendto(msg, ("239.255.255.250", 1900))
2527
2528 logger.debug("Mismatching ST")
2529 msg = '\r\n'.join([
2530 'M-SEARCH * HTTP/1.1',
2531 'HOST: 239.255.255.250:1900',
2532 'MAN: "ssdp:discover"',
2533 'MX: 1',
2534 'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
2535 '', ''])
2536 sock.sendto(msg, ("239.255.255.250", 1900))
2537 msg = '\r\n'.join([
2538 'M-SEARCH * HTTP/1.1',
2539 'HOST: 239.255.255.250:1900',
2540 'MAN: "ssdp:discover"',
2541 'MX: 1',
2542 'ST: foo:bar',
2543 '', ''])
2544 sock.sendto(msg, ("239.255.255.250", 1900))
2545 msg = '\r\n'.join([
2546 'M-SEARCH * HTTP/1.1',
2547 'HOST: 239.255.255.250:1900',
2548 'MAN: "ssdp:discover"',
2549 'MX: 1',
2550 'ST: foobar',
2551 '', ''])
2552 sock.sendto(msg, ("239.255.255.250", 1900))
2553
2554 logger.debug("Invalid ST")
2555 msg = '\r\n'.join([
2556 'M-SEARCH * HTTP/1.1',
2557 'HOST: 239.255.255.250:1900',
2558 'MAN: "ssdp:discover"',
2559 'MX: 1',
2560 'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
2561 '', ''])
2562 sock.sendto(msg, ("239.255.255.250", 1900))
2563
2564 logger.debug("Invalid M-SEARCH")
2565 msg = '\r\n'.join([
2566 'M+SEARCH * HTTP/1.1',
2567 'HOST: 239.255.255.250:1900',
2568 'MAN: "ssdp:discover"',
2569 'MX: 1',
2570 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2571 '', ''])
2572 sock.sendto(msg, ("239.255.255.250", 1900))
2573 msg = '\r\n'.join([
2574 'M-SEARCH-* HTTP/1.1',
2575 'HOST: 239.255.255.250:1900',
2576 'MAN: "ssdp:discover"',
2577 'MX: 1',
2578 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2579 '', ''])
2580 sock.sendto(msg, ("239.255.255.250", 1900))
2581
2582 logger.debug("Invalid message format")
2583 sock.sendto("NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
2584 msg = '\r'.join([
2585 'M-SEARCH * HTTP/1.1',
2586 'HOST: 239.255.255.250:1900',
2587 'MAN: "ssdp:discover"',
2588 'MX: 1',
2589 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2590 '', ''])
2591 sock.sendto(msg, ("239.255.255.250", 1900))
2592
2593 try:
2594 r = sock.recv(1000)
2595 raise Exception("Unexpected M-SEARCH response: " + r)
2596 except socket.timeout:
2597 pass
2598
2599 logger.debug("Valid M-SEARCH")
2600 msg = '\r\n'.join([
2601 'M-SEARCH * HTTP/1.1',
2602 'HOST: 239.255.255.250:1900',
2603 'MAN: "ssdp:discover"',
2604 'MX: 1',
2605 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2606 '', ''])
2607 sock.sendto(msg, ("239.255.255.250", 1900))
2608
2609 try:
2610 r = sock.recv(1000)
2611 pass
2612 except socket.timeout:
2613 raise Exception("No SSDP response")
2614
2615def test_ap_wps_ssdp_burst(dev, apdev):
2616 """WPS AP and SSDP burst"""
2617 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2618 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2619
2620 msg = '\r\n'.join([
2621 'M-SEARCH * HTTP/1.1',
2622 'HOST: 239.255.255.250:1900',
2623 'MAN: "ssdp:discover"',
2624 'MX: 1',
2625 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2626 '', ''])
2627 socket.setdefaulttimeout(1)
2628 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2629 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2630 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2631 sock.bind(("127.0.0.1", 0))
2632 for i in range(0, 25):
2633 sock.sendto(msg, ("239.255.255.250", 1900))
2634 resp = 0
2635 while True:
2636 try:
2637 r = sock.recv(1000)
2638 if not r.startswith("HTTP/1.1 200 OK\r\n"):
2639 raise Exception("Unexpected message: " + r)
2640 resp += 1
2641 except socket.timeout:
2642 break
2643 if resp < 20:
2644 raise Exception("Too few SSDP responses")
2645
2646 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2647 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2648 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2649 sock.bind(("127.0.0.1", 0))
2650 for i in range(0, 25):
2651 sock.sendto(msg, ("239.255.255.250", 1900))
2652 while True:
2653 try:
2654 r = sock.recv(1000)
2655 if ap_uuid in r:
2656 break
2657 except socket.timeout:
2658 raise Exception("No SSDP response")
47c549fd
JM
2659
2660def ssdp_get_location(uuid):
2661 res = ssdp_send_msearch("uuid:" + uuid)
2662 location = None
2663 for l in res.splitlines():
2664 if l.lower().startswith("location:"):
2665 location = l.split(':', 1)[1].strip()
2666 break
2667 if location is None:
2668 raise Exception("No UPnP location found")
2669 return location
2670
2671def upnp_get_urls(location):
2672 conn = urllib.urlopen(location)
2673 tree = ET.parse(conn)
2674 root = tree.getroot()
2675 urn = '{urn:schemas-upnp-org:device-1-0}'
2676 service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
2677 res = {}
2678 res['scpd_url'] = urlparse.urljoin(location, service.find(urn + 'SCPDURL').text)
2679 res['control_url'] = urlparse.urljoin(location, service.find(urn + 'controlURL').text)
2680 res['event_sub_url'] = urlparse.urljoin(location, service.find(urn + 'eventSubURL').text)
2681 return res
2682
dd124ee8
JM
2683def upnp_soap_action(conn, path, action, include_soap_action=True,
2684 soap_action_override=None, newmsg=None, neweventtype=None,
2685 neweventmac=None):
47c549fd
JM
2686 soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
2687 wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
2688 ET.register_namespace('soapenv', soapns)
2689 ET.register_namespace('wfa', wpsns)
2690 attrib = {}
2691 attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
2692 root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
2693 body = ET.SubElement(root, "{%s}Body" % soapns)
2694 act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
dd124ee8
JM
2695 if newmsg:
2696 msg = ET.SubElement(act, "NewMessage")
2697 msg.text = base64.b64encode(newmsg)
2698 if neweventtype:
2699 msg = ET.SubElement(act, "NewWLANEventType")
2700 msg.text = neweventtype
2701 if neweventmac:
2702 msg = ET.SubElement(act, "NewWLANEventMAC")
2703 msg.text = neweventmac
47c549fd
JM
2704 tree = ET.ElementTree(root)
2705 soap = StringIO.StringIO()
2706 tree.write(soap, xml_declaration=True, encoding='utf-8')
2707
2708 headers = { "Content-type": 'text/xml; charset="utf-8"' }
2709 if include_soap_action:
2710 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
2711 elif soap_action_override:
2712 headers["SOAPAction"] = soap_action_override
2713 conn.request("POST", path, soap.getvalue(), headers)
2714 return conn.getresponse()
2715
2716def test_ap_wps_upnp(dev, apdev):
2717 """WPS AP and UPnP operations"""
2718 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2719 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2720
2721 location = ssdp_get_location(ap_uuid)
2722 urls = upnp_get_urls(location)
2723
2724 conn = urllib.urlopen(urls['scpd_url'])
2725 scpd = conn.read()
2726
2727 conn = urllib.urlopen(urlparse.urljoin(location, "unknown.html"))
2728 if conn.getcode() != 404:
2729 raise Exception("Unexpected HTTP response to GET unknown URL")
2730
2731 url = urlparse.urlparse(location)
2732 conn = httplib.HTTPConnection(url.netloc)
2733 #conn.set_debuglevel(1)
2734 headers = { "Content-type": 'text/xml; charset="utf-8"',
2735 "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"' }
2736 conn.request("POST", "hello", "\r\n\r\n", headers)
2737 resp = conn.getresponse()
2738 if resp.status != 404:
5c267d71 2739 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2740
2741 conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
2742 resp = conn.getresponse()
2743 if resp.status != 501:
5c267d71 2744 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2745
2746 headers = { "Content-type": 'text/xml; charset="utf-8"',
2747 "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"' }
2748 ctrlurl = urlparse.urlparse(urls['control_url'])
2749 conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
2750 resp = conn.getresponse()
2751 if resp.status != 401:
5c267d71 2752 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2753
2754 logger.debug("GetDeviceInfo without SOAPAction header")
2755 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2756 include_soap_action=False)
2757 if resp.status != 401:
5c267d71 2758 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2759
2760 logger.debug("GetDeviceInfo with invalid SOAPAction header")
2761 for act in [ "foo",
2762 "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
2763 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
2764 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
2765 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2766 include_soap_action=False,
2767 soap_action_override=act)
2768 if resp.status != 401:
5c267d71 2769 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2770
2771 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
2772 if resp.status != 200:
5c267d71 2773 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2774 dev = resp.read()
2775 if "NewDeviceInfo" not in dev:
2776 raise Exception("Unexpected GetDeviceInfo response")
2777
2778 logger.debug("PutMessage without required parameters")
2779 resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
2780 if resp.status != 600:
5c267d71 2781 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2782
2783 logger.debug("PutWLANResponse without required parameters")
2784 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
2785 if resp.status != 600:
5c267d71 2786 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2787
2788 logger.debug("SetSelectedRegistrar from unregistered ER")
2789 resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
2790 if resp.status != 501:
5c267d71 2791 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2792
2793 logger.debug("Unknown action")
2794 resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
2795 if resp.status != 401:
5c267d71 2796 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2797
2798def test_ap_wps_upnp_subscribe(dev, apdev):
2799 """WPS AP and UPnP event subscription"""
2800 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
24b7f282 2801 hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
47c549fd
JM
2802
2803 location = ssdp_get_location(ap_uuid)
2804 urls = upnp_get_urls(location)
2805 eventurl = urlparse.urlparse(urls['event_sub_url'])
2806
2807 url = urlparse.urlparse(location)
2808 conn = httplib.HTTPConnection(url.netloc)
2809 #conn.set_debuglevel(1)
2810 headers = { "callback": '<http://127.0.0.1:12345/event>',
2811 "timeout": "Second-1234" }
2812 conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
2813 resp = conn.getresponse()
2814 if resp.status != 412:
5c267d71 2815 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2816
2817 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2818 resp = conn.getresponse()
2819 if resp.status != 412:
5c267d71 2820 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2821
2822 headers = { "NT": "upnp:event",
2823 "timeout": "Second-1234" }
2824 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2825 resp = conn.getresponse()
2826 if resp.status != 412:
5c267d71 2827 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2828
2829 headers = { "callback": '<http://127.0.0.1:12345/event>',
2830 "NT": "upnp:foobar",
2831 "timeout": "Second-1234" }
2832 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2833 resp = conn.getresponse()
2834 if resp.status != 400:
5c267d71 2835 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2836
2837 logger.debug("Valid subscription")
2838 headers = { "callback": '<http://127.0.0.1:12345/event>',
2839 "NT": "upnp:event",
2840 "timeout": "Second-1234" }
2841 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2842 resp = conn.getresponse()
2843 if resp.status != 200:
5c267d71 2844 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2845 sid = resp.getheader("sid")
2846 logger.debug("Subscription SID " + sid)
2847
2848 logger.debug("Invalid re-subscription")
2849 headers = { "NT": "upnp:event",
2850 "sid": "123456734567854",
2851 "timeout": "Second-1234" }
2852 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2853 resp = conn.getresponse()
2854 if resp.status != 400:
5c267d71 2855 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2856
2857 logger.debug("Invalid re-subscription")
2858 headers = { "NT": "upnp:event",
2859 "sid": "uuid:123456734567854",
2860 "timeout": "Second-1234" }
2861 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2862 resp = conn.getresponse()
2863 if resp.status != 400:
5c267d71 2864 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2865
2866 logger.debug("Invalid re-subscription")
2867 headers = { "callback": '<http://127.0.0.1:12345/event>',
2868 "NT": "upnp:event",
2869 "sid": sid,
2870 "timeout": "Second-1234" }
2871 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2872 resp = conn.getresponse()
2873 if resp.status != 400:
5c267d71 2874 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2875
2876 logger.debug("SID mismatch in re-subscription")
2877 headers = { "NT": "upnp:event",
2878 "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
2879 "timeout": "Second-1234" }
2880 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2881 resp = conn.getresponse()
2882 if resp.status != 412:
5c267d71 2883 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2884
2885 logger.debug("Valid re-subscription")
2886 headers = { "NT": "upnp:event",
2887 "sid": sid,
2888 "timeout": "Second-1234" }
2889 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2890 resp = conn.getresponse()
2891 if resp.status != 200:
5c267d71 2892 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2893 sid2 = resp.getheader("sid")
2894 logger.debug("Subscription SID " + sid2)
2895
2896 if sid != sid2:
2897 raise Exception("Unexpected SID change")
2898
2899 logger.debug("Valid re-subscription")
2900 headers = { "NT": "upnp:event",
2901 "sid": "uuid: \t \t" + sid.split(':')[1],
2902 "timeout": "Second-1234" }
2903 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2904 resp = conn.getresponse()
2905 if resp.status != 200:
5c267d71 2906 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2907
2908 logger.debug("Invalid unsubscription")
2909 headers = { "sid": sid }
2910 conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
2911 resp = conn.getresponse()
2912 if resp.status != 412:
5c267d71 2913 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2914 headers = { "foo": "bar" }
2915 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2916 resp = conn.getresponse()
2917 if resp.status != 412:
5c267d71 2918 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2919
2920 logger.debug("Valid unsubscription")
2921 headers = { "sid": sid }
2922 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2923 resp = conn.getresponse()
2924 if resp.status != 200:
5c267d71 2925 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2926
2927 logger.debug("Unsubscription for not existing SID")
2928 headers = { "sid": sid }
2929 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2930 resp = conn.getresponse()
2931 if resp.status != 412:
5c267d71 2932 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2933
2934 logger.debug("Invalid unsubscription")
2935 headers = { "sid": " \t \tfoo" }
2936 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2937 resp = conn.getresponse()
2938 if resp.status != 400:
5c267d71 2939 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2940
2941 logger.debug("Invalid unsubscription")
2942 headers = { "sid": "uuid:\t \tfoo" }
2943 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2944 resp = conn.getresponse()
2945 if resp.status != 400:
5c267d71 2946 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2947
2948 logger.debug("Invalid unsubscription")
2949 headers = { "NT": "upnp:event",
2950 "sid": sid }
2951 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2952 resp = conn.getresponse()
2953 if resp.status != 400:
5c267d71 2954 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2955 headers = { "callback": '<http://127.0.0.1:12345/event>',
2956 "sid": sid }
2957 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2958 resp = conn.getresponse()
2959 if resp.status != 400:
5c267d71 2960 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2961
2962 logger.debug("Valid subscription with multiple callbacks")
2963 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>',
2964 "NT": "upnp:event",
2965 "timeout": "Second-1234" }
2966 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2967 resp = conn.getresponse()
2968 if resp.status != 200:
5c267d71 2969 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2970 sid = resp.getheader("sid")
2971 logger.debug("Subscription SID " + sid)
d352c407 2972
24b7f282
JM
2973 # Force subscription to be deleted due to errors
2974 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2975 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2976 with alloc_fail(hapd, 1, "event_build_message"):
2977 for i in range(10):
2978 dev[1].dump_monitor()
2979 dev[2].dump_monitor()
2980 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2981 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2982 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2983 dev[1].request("WPS_CANCEL")
2984 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2985 dev[2].request("WPS_CANCEL")
2986 if i % 4 == 1:
2987 time.sleep(1)
2988 else:
2989 time.sleep(0.1)
2990 time.sleep(0.2)
2991
2992 headers = { "sid": sid }
2993 conn.request("UNSUBSCRIBE", eventurl.path, "", headers)
2994 resp = conn.getresponse()
2995 if resp.status != 200 and resp.status != 412:
2996 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
2997
2998 headers = { "callback": '<http://127.0.0.1:12345/event>',
2999 "NT": "upnp:event",
3000 "timeout": "Second-1234" }
3001 with alloc_fail(hapd, 1, "http_client_addr;event_send_start"):
3002 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3003 resp = conn.getresponse()
3004 if resp.status != 200:
3005 raise Exception("Unexpected HTTP response for SUBSCRIBE: %d" % resp.status)
3006 sid = resp.getheader("sid")
3007 logger.debug("Subscription SID " + sid)
3008
3009 headers = { "sid": sid }
3010 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3011 resp = conn.getresponse()
3012 if resp.status != 200:
3013 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3014
3015 headers = { "callback": '<http://127.0.0.1:12345/event>',
3016 "NT": "upnp:event",
3017 "timeout": "Second-1234" }
3018 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3019 resp = conn.getresponse()
3020 if resp.status != 200:
3021 raise Exception("Unexpected HTTP response: %d" % resp.status)
3022 sid = resp.getheader("sid")
3023 logger.debug("Subscription SID " + sid)
3024
3025 with alloc_fail(hapd, 1, "=event_add"):
3026 for i in range(2):
3027 dev[1].dump_monitor()
3028 dev[2].dump_monitor()
3029 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3030 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3031 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3032 dev[1].request("WPS_CANCEL")
3033 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3034 dev[2].request("WPS_CANCEL")
3035 if i == 0:
3036 time.sleep(1)
3037 else:
3038 time.sleep(0.1)
3039
3040 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3041 resp = conn.getresponse()
3042 if resp.status != 200:
3043 raise Exception("Unexpected HTTP response: %d" % resp.status)
3044
3045 with alloc_fail(hapd, 1, "wpabuf_dup;event_add"):
3046 dev[1].dump_monitor()
3047 dev[2].dump_monitor()
3048 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3049 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3050 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3051 dev[1].request("WPS_CANCEL")
3052 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3053 dev[2].request("WPS_CANCEL")
3054 time.sleep(0.1)
3055
3056 with fail_test(hapd, 1, "os_get_random;uuid_make;subscription_start"):
3057 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3058 resp = conn.getresponse()
3059 if resp.status != 500:
3060 raise Exception("Unexpected HTTP response: %d" % resp.status)
3061
3062 with alloc_fail(hapd, 1, "=subscription_start"):
3063 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3064 resp = conn.getresponse()
3065 if resp.status != 500:
3066 raise Exception("Unexpected HTTP response: %d" % resp.status)
3067
3068 headers = { "callback": '',
3069 "NT": "upnp:event",
3070 "timeout": "Second-1234" }
3071 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3072 resp = conn.getresponse()
3073 if resp.status != 500:
3074 raise Exception("Unexpected HTTP response: %d" % resp.status)
3075
3076 headers = { "callback": ' <',
3077 "NT": "upnp:event",
3078 "timeout": "Second-1234" }
3079 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3080 resp = conn.getresponse()
3081 if resp.status != 500:
3082 raise Exception("Unexpected HTTP response: %d" % resp.status)
3083
3084 headers = { "callback": '<http://127.0.0.1:12345/event>',
3085 "NT": "upnp:event",
3086 "timeout": "Second-1234" }
3087 with alloc_fail(hapd, 1, "wpabuf_alloc;subscription_first_event"):
3088 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3089 resp = conn.getresponse()
3090 if resp.status != 500:
3091 raise Exception("Unexpected HTTP response: %d" % resp.status)
3092
3093 with alloc_fail(hapd, 1, "event_add;subscription_first_event"):
3094 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3095 resp = conn.getresponse()
3096 if resp.status != 500:
3097 raise Exception("Unexpected HTTP response: %d" % resp.status)
3098
3099 with alloc_fail(hapd, 1, "subscr_addr_add_url"):
3100 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3101 resp = conn.getresponse()
3102 if resp.status != 500:
3103 raise Exception("Unexpected HTTP response: %d" % resp.status)
3104
3105 with alloc_fail(hapd, 2, "subscr_addr_add_url"):
3106 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3107 resp = conn.getresponse()
3108 if resp.status != 500:
3109 raise Exception("Unexpected HTTP response: %d" % resp.status)
3110
3111 for i in range(6):
3112 headers = { "callback": '<http://127.0.0.1:%d/event>' % (12345 + i),
3113 "NT": "upnp:event",
3114 "timeout": "Second-1234" }
3115 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3116 resp = conn.getresponse()
3117 if resp.status != 200:
3118 raise Exception("Unexpected HTTP response: %d" % resp.status)
3119
3120 with alloc_fail(hapd, 1, "=upnp_wps_device_send_wlan_event"):
3121 dev[1].dump_monitor()
3122 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3123 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3124 dev[1].request("WPS_CANCEL")
3125 time.sleep(0.1)
3126
3127 with alloc_fail(hapd, 1, "wpabuf_alloc;upnp_wps_device_send_event"):
3128 dev[1].dump_monitor()
3129 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3130 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3131 dev[1].request("WPS_CANCEL")
3132 time.sleep(0.1)
3133
3134 with alloc_fail(hapd, 1, "base64_encode;upnp_wps_device_send_wlan_event"):
3135 dev[1].dump_monitor()
3136 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3137 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3138 dev[1].request("WPS_CANCEL")
3139 time.sleep(0.1)
3140
3141 hapd.disable()
3142 with alloc_fail(hapd, 1, "get_netif_info"):
3143 if "FAIL" not in hapd.request("ENABLE"):
3144 raise Exception("ENABLE succeeded during OOM")
3145
d91a64c4
JM
3146def test_ap_wps_upnp_subscribe_events(dev, apdev):
3147 """WPS AP and UPnP event subscription and many events"""
3148 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3149 hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
3150
3151 location = ssdp_get_location(ap_uuid)
3152 urls = upnp_get_urls(location)
3153 eventurl = urlparse.urlparse(urls['event_sub_url'])
3154
3155 class WPSERHTTPServer(SocketServer.StreamRequestHandler):
3156 def handle(self):
3157 data = self.rfile.readline().strip()
3158 logger.debug(data)
3159 self.wfile.write(gen_wps_event())
3160
3161 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
3162 server.timeout = 1
3163
3164 url = urlparse.urlparse(location)
3165 conn = httplib.HTTPConnection(url.netloc)
3166
3167 headers = { "callback": '<http://127.0.0.1:12345/event>',
3168 "NT": "upnp:event",
3169 "timeout": "Second-1234" }
3170 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3171 resp = conn.getresponse()
3172 if resp.status != 200:
3173 raise Exception("Unexpected HTTP response: %d" % resp.status)
3174 sid = resp.getheader("sid")
3175 logger.debug("Subscription SID " + sid)
3176
3177 # Fetch the first event message
3178 server.handle_request()
3179
3180 # Force subscription event queue to reach the maximum length by generating
3181 # new proxied events without the ER fetching any of the pending events.
3182 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3183 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3184 for i in range(16):
3185 dev[1].dump_monitor()
3186 dev[2].dump_monitor()
3187 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3188 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3189 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3190 dev[1].request("WPS_CANCEL")
3191 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3192 dev[2].request("WPS_CANCEL")
3193 if i % 4 == 1:
3194 time.sleep(1)
3195 else:
3196 time.sleep(0.1)
3197
3198 hapd.request("WPS_PIN any 12345670")
3199 dev[1].dump_monitor()
3200 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3201 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=10)
3202 if ev is None:
3203 raise Exception("WPS success not reported")
3204
3205 # Close the WPS ER HTTP server without fetching all the pending events.
3206 # This tests hostapd code path that clears subscription and the remaining
3207 # event queue when the interface is deinitialized.
3208 server.handle_request()
3209 server.server_close()
3210
3211 dev[1].wait_connected()
3212
b2047531
JM
3213def test_ap_wps_upnp_http_proto(dev, apdev):
3214 """WPS AP and UPnP/HTTP protocol testing"""
3215 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3216 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
3217
3218 location = ssdp_get_location(ap_uuid)
3219
3220 url = urlparse.urlparse(location)
81f8e7e9 3221 conn = httplib.HTTPConnection(url.netloc, timeout=0.2)
b2047531
JM
3222 #conn.set_debuglevel(1)
3223
3224 conn.request("HEAD", "hello")
3225 resp = conn.getresponse()
3226 if resp.status != 501:
3227 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3228 conn.close()
3229
3230 for cmd in [ "PUT", "DELETE", "TRACE", "CONNECT", "M-SEARCH", "M-POST" ]:
3231 try:
3232 conn.request(cmd, "hello")
3233 resp = conn.getresponse()
3234 except Exception, e:
3235 pass
3236 conn.close()
3237
3238 headers = { "Content-Length": 'abc' }
3239 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3240 try:
3241 resp = conn.getresponse()
3242 except Exception, e:
3243 pass
3244 conn.close()
3245
3246 headers = { "Content-Length": '-10' }
3247 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3248 try:
3249 resp = conn.getresponse()
3250 except Exception, e:
3251 pass
3252 conn.close()
3253
3254 headers = { "Content-Length": '10000000000000' }
3255 conn.request("HEAD", "hello", "\r\n\r\nhello", headers)
3256 try:
3257 resp = conn.getresponse()
3258 except Exception, e:
3259 pass
3260 conn.close()
3261
3262 headers = { "Transfer-Encoding": 'abc' }
3263 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3264 resp = conn.getresponse()
3265 if resp.status != 501:
3266 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3267 conn.close()
3268
3269 headers = { "Transfer-Encoding": 'chunked' }
3270 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3271 resp = conn.getresponse()
3272 if resp.status != 501:
3273 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3274 conn.close()
3275
3276 # Too long a header
3277 conn.request("HEAD", 5000 * 'A')
3278 try:
3279 resp = conn.getresponse()
3280 except Exception, e:
3281 pass
3282 conn.close()
3283
3284 # Long URL but within header length limits
3285 conn.request("HEAD", 3000 * 'A')
3286 resp = conn.getresponse()
3287 if resp.status != 501:
3288 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3289 conn.close()
3290
3291 headers = { "Content-Length": '20' }
3292 conn.request("POST", "hello", 10 * 'A' + "\r\n\r\n", headers)
3293 try:
3294 resp = conn.getresponse()
3295 except Exception, e:
3296 pass
3297 conn.close()
3298
3299 conn.request("POST", "hello", 5000 * 'A' + "\r\n\r\n")
3300 resp = conn.getresponse()
3301 if resp.status != 404:
5c267d71 3302 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
3303 conn.close()
3304
3305 conn.request("POST", "hello", 60000 * 'A' + "\r\n\r\n")
3306 try:
3307 resp = conn.getresponse()
3308 except Exception, e:
3309 pass
3310 conn.close()
3311
3312def test_ap_wps_upnp_http_proto_chunked(dev, apdev):
3313 """WPS AP and UPnP/HTTP protocol testing for chunked encoding"""
3314 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3315 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
3316
3317 location = ssdp_get_location(ap_uuid)
3318
3319 url = urlparse.urlparse(location)
3320 conn = httplib.HTTPConnection(url.netloc)
3321 #conn.set_debuglevel(1)
3322
3323 headers = { "Transfer-Encoding": 'chunked' }
3324 conn.request("POST", "hello",
3325 "a\r\nabcdefghij\r\n" + "2\r\nkl\r\n" + "0\r\n\r\n",
3326 headers)
3327 resp = conn.getresponse()
3328 if resp.status != 404:
5c267d71 3329 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
3330 conn.close()
3331
3332 conn.putrequest("POST", "hello")
3333 conn.putheader('Transfer-Encoding', 'chunked')
3334 conn.endheaders()
3335 conn.send("a\r\nabcdefghij\r\n")
3336 time.sleep(0.1)
3337 conn.send("2\r\nkl\r\n")
3338 conn.send("0\r\n\r\n")
3339 resp = conn.getresponse()
3340 if resp.status != 404:
5c267d71 3341 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
3342 conn.close()
3343
3344 conn.putrequest("POST", "hello")
3345 conn.putheader('Transfer-Encoding', 'chunked')
3346 conn.endheaders()
3347 completed = False
3348 try:
3349 for i in range(20000):
3350 conn.send("1\r\nZ\r\n")
3351 conn.send("0\r\n\r\n")
3352 resp = conn.getresponse()
3353 completed = True
3354 except Exception, e:
3355 pass
3356 conn.close()
3357 if completed:
3358 raise Exception("Too long chunked request did not result in connection reset")
3359
3360 headers = { "Transfer-Encoding": 'chunked' }
3361 conn.request("POST", "hello", "80000000\r\na", headers)
3362 try:
3363 resp = conn.getresponse()
3364 except Exception, e:
3365 pass
3366 conn.close()
3367
3368 conn.request("POST", "hello", "10000000\r\na", headers)
3369 try:
3370 resp = conn.getresponse()
3371 except Exception, e:
3372 pass
3373 conn.close()
3374
d352c407
JM
3375def test_ap_wps_disabled(dev, apdev):
3376 """WPS operations while WPS is disabled"""
3377 ssid = "test-wps-disabled"
3378 hostapd.add_ap(apdev[0]['ifname'], { "ssid": ssid })
3379 hapd = hostapd.Hostapd(apdev[0]['ifname'])
3380 if "FAIL" not in hapd.request("WPS_PBC"):
3381 raise Exception("WPS_PBC succeeded unexpectedly")
3382 if "FAIL" not in hapd.request("WPS_CANCEL"):
3383 raise Exception("WPS_CANCEL succeeded unexpectedly")
a0fd2ae6
JM
3384
3385def test_ap_wps_mixed_cred(dev, apdev):
3386 """WPS 2.0 STA merging mixed mode WPA/WPA2 credentials"""
3387 ssid = "test-wps-wep"
3388 hostapd.add_ap(apdev[0]['ifname'],
3389 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3390 "skip_cred_build": "1", "extra_cred": "wps-mixed-cred" })
3391 hapd = hostapd.Hostapd(apdev[0]['ifname'])
3392 hapd.request("WPS_PBC")
33d0b157
JM
3393 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3394 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
9ed53f5e 3395 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
a0fd2ae6
JM
3396 if ev is None:
3397 raise Exception("WPS-SUCCESS event timed out")
3398 nets = dev[0].list_networks()
3399 if len(nets) != 1:
3400 raise Exception("Unexpected number of network blocks")
3401 id = nets[0]['id']
3402 proto = dev[0].get_network(id, "proto")
3403 if proto != "WPA RSN":
3404 raise Exception("Unexpected merged proto field value: " + proto)
3405 pairwise = dev[0].get_network(id, "pairwise")
72a8e30b 3406 if pairwise != "CCMP TKIP" and pairwise != "CCMP GCMP TKIP":
a0fd2ae6 3407 raise Exception("Unexpected merged pairwise field value: " + pairwise)
e5a79e3f
JM
3408
3409def test_ap_wps_while_connected(dev, apdev):
3410 """WPS PBC provisioning while connected to another AP"""
3411 ssid = "test-wps-conf"
3412 hostapd.add_ap(apdev[0]['ifname'],
3413 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3414 "wpa_passphrase": "12345678", "wpa": "2",
3415 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3416 hapd = hostapd.Hostapd(apdev[0]['ifname'])
3417
3418 hostapd.add_ap(apdev[1]['ifname'], { "ssid": "open" })
3419 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3420
3421 logger.info("WPS provisioning step")
3422 hapd.request("WPS_PBC")
3423 dev[0].dump_monitor()
33d0b157 3424 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 3425 dev[0].wait_connected(timeout=30)
e5a79e3f
JM
3426 status = dev[0].get_status()
3427 if status['bssid'] != apdev[0]['bssid']:
3428 raise Exception("Unexpected BSSID")
3429
3430def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
3431 """WPS PBC provisioning while connected to another AP and STA_AUTOCONNECT disabled"""
3432 ssid = "test-wps-conf"
3433 hostapd.add_ap(apdev[0]['ifname'],
3434 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3435 "wpa_passphrase": "12345678", "wpa": "2",
3436 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3437 hapd = hostapd.Hostapd(apdev[0]['ifname'])
3438
3439 hostapd.add_ap(apdev[1]['ifname'], { "ssid": "open" })
3440
3441 try:
3442 dev[0].request("STA_AUTOCONNECT 0")
3443 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3444
3445 logger.info("WPS provisioning step")
3446 hapd.request("WPS_PBC")
3447 dev[0].dump_monitor()
33d0b157 3448 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 3449 dev[0].wait_connected(timeout=30)
e5a79e3f
JM
3450 status = dev[0].get_status()
3451 if status['bssid'] != apdev[0]['bssid']:
3452 raise Exception("Unexpected BSSID")
3453 finally:
3454 dev[0].request("STA_AUTOCONNECT 1")
3f08d1cd
JM
3455
3456def test_ap_wps_from_event(dev, apdev):
3457 """WPS PBC event on AP to enable PBC"""
3458 ssid = "test-wps-conf"
3459 hapd = hostapd.add_ap(apdev[0]['ifname'],
3460 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3461 "wpa_passphrase": "12345678", "wpa": "2",
3462 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
33d0b157 3463 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3f08d1cd 3464 dev[0].dump_monitor()
33d0b157
JM
3465 hapd.dump_monitor()
3466 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3f08d1cd
JM
3467
3468 ev = hapd.wait_event(['WPS-ENROLLEE-SEEN'], timeout=15)
3469 if ev is None:
3470 raise Exception("No WPS-ENROLLEE-SEEN event on AP")
3471 vals = ev.split(' ')
3472 if vals[1] != dev[0].p2p_interface_addr():
3473 raise Exception("Unexpected enrollee address: " + vals[1])
3474 if vals[5] != '4':
3475 raise Exception("Unexpected Device Password Id: " + vals[5])
3476 hapd.request("WPS_PBC")
5f35a5e2 3477 dev[0].wait_connected(timeout=30)
1531402e
JM
3478
3479def test_ap_wps_ap_scan_2(dev, apdev):
3480 """AP_SCAN 2 for WPS"""
3481 ssid = "test-wps-conf"
3482 hapd = hostapd.add_ap(apdev[0]['ifname'],
3483 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3484 "wpa_passphrase": "12345678", "wpa": "2",
3485 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3486 hapd.request("WPS_PBC")
3487
3488 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
3489 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
4b9d79b6 3490 wpas.dump_monitor()
1531402e
JM
3491
3492 if "OK" not in wpas.request("AP_SCAN 2"):
3493 raise Exception("Failed to set AP_SCAN 2")
3494
e51c8b2e 3495 wpas.flush_scan_cache()
33d0b157 3496 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
4b9d79b6 3497 wpas.dump_monitor()
33d0b157 3498 wpas.request("WPS_PBC " + apdev[0]['bssid'])
1531402e
JM
3499 ev = wpas.wait_event(["WPS-SUCCESS"], timeout=15)
3500 if ev is None:
3501 raise Exception("WPS-SUCCESS event timed out")
5f35a5e2 3502 wpas.wait_connected(timeout=30)
4b9d79b6 3503 wpas.dump_monitor()
1531402e
JM
3504 wpas.request("DISCONNECT")
3505 wpas.request("BSS_FLUSH 0")
3506 wpas.dump_monitor()
3507 wpas.request("REASSOCIATE")
5f35a5e2 3508 wpas.wait_connected(timeout=30)
4b9d79b6 3509 wpas.dump_monitor()
a08fdb17
JM
3510
3511def test_ap_wps_eapol_workaround(dev, apdev):
3512 """EAPOL workaround code path for 802.1X header length mismatch"""
3513 ssid = "test-wps"
3514 hostapd.add_ap(apdev[0]['ifname'],
3515 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
3516 hapd = hostapd.Hostapd(apdev[0]['ifname'])
3517 bssid = apdev[0]['bssid']
3518 hapd.request("SET ext_eapol_frame_io 1")
3519 dev[0].request("SET ext_eapol_frame_io 1")
3520 hapd.request("WPS_PBC")
3521 dev[0].request("WPS_PBC")
3522
3523 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3524 if ev is None:
3525 raise Exception("Timeout on EAPOL-TX from hostapd")
3526
3527 res = dev[0].request("EAPOL_RX " + bssid + " 020000040193000501FFFF")
3528 if "OK" not in res:
3529 raise Exception("EAPOL_RX to wpa_supplicant failed")
46dea617
JM
3530
3531def test_ap_wps_iteration(dev, apdev):
3532 """WPS PIN and iterate through APs without selected registrar"""
3533 ssid = "test-wps-conf"
3534 hapd = hostapd.add_ap(apdev[0]['ifname'],
3535 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3536 "wpa_passphrase": "12345678", "wpa": "2",
3537 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3538
3539 ssid2 = "test-wps-conf2"
3540 hapd2 = hostapd.add_ap(apdev[1]['ifname'],
3541 { "ssid": ssid2, "eap_server": "1", "wps_state": "2",
3542 "wpa_passphrase": "12345678", "wpa": "2",
3543 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3544
3545 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3546 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
3547 dev[0].dump_monitor()
3548 pin = dev[0].request("WPS_PIN any")
3549
3550 # Wait for iteration through all WPS APs to happen before enabling any
3551 # Registrar.
3552 for i in range(2):
3553 ev = dev[0].wait_event(["Associated with"], timeout=30)
3554 if ev is None:
3555 raise Exception("No association seen")
3556 ev = dev[0].wait_event(["WPS-M2D"], timeout=10)
3557 if ev is None:
3558 raise Exception("No M2D from AP")
3559 dev[0].wait_disconnected()
3560
3561 # Verify that each AP requested PIN
3562 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3563 if ev is None:
3564 raise Exception("No WPS-PIN-NEEDED event from AP")
3565 ev = hapd2.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3566 if ev is None:
3567 raise Exception("No WPS-PIN-NEEDED event from AP2")
3568
3569 # Provide PIN to one of the APs and verify that connection gets formed
3570 hapd.request("WPS_PIN any " + pin)
3571 dev[0].wait_connected(timeout=30)
2272f5aa
JM
3572
3573def test_ap_wps_iteration_error(dev, apdev):
3574 """WPS AP iteration on no Selected Registrar and error case with an AP"""
3575 ssid = "test-wps-conf-pin"
3576 hapd = hostapd.add_ap(apdev[0]['ifname'],
3577 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3578 "wpa_passphrase": "12345678", "wpa": "2",
3579 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3580 "wps_independent": "1" })
3581 hapd.request("SET ext_eapol_frame_io 1")
3582 bssid = apdev[0]['bssid']
3583 pin = dev[0].wps_read_pin()
3584 dev[0].request("WPS_PIN any " + pin)
3585
3586 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3587 if ev is None:
3588 raise Exception("No EAPOL-TX (EAP-Request/Identity) from hostapd")
3589 dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
3590
3591 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3592 if ev is None:
3593 raise Exception("No EAPOL-TX (EAP-WSC/Start) from hostapd")
3594 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=5)
3595 if ev is None:
3596 raise Exception("No CTRL-EVENT-EAP-STARTED")
3597
3598 # Do not forward any more EAPOL frames to test wpa_supplicant behavior for
3599 # a case with an incorrectly behaving WPS AP.
3600
3601 # Start the real target AP and activate registrar on it.
3602 hapd2 = hostapd.add_ap(apdev[1]['ifname'],
3603 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3604 "wpa_passphrase": "12345678", "wpa": "2",
3605 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3606 "wps_independent": "1" })
3607 hapd2.request("WPS_PIN any " + pin)
3608
3609 dev[0].wait_disconnected(timeout=15)
3610 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
3611 if ev is None:
3612 raise Exception("No CTRL-EVENT-EAP-STARTED for the second AP")
3613 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
3614 if ev is None:
3615 raise Exception("No WPS-CRED-RECEIVED for the second AP")
3616 dev[0].wait_connected(timeout=15)
d6f6a86a
JM
3617
3618def test_ap_wps_priority(dev, apdev):
3619 """WPS PIN provisioning with configured AP and wps_priority"""
3620 ssid = "test-wps-conf-pin"
3621 hostapd.add_ap(apdev[0]['ifname'],
3622 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3623 "wpa_passphrase": "12345678", "wpa": "2",
3624 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3625 hapd = hostapd.Hostapd(apdev[0]['ifname'])
3626 logger.info("WPS provisioning step")
3627 pin = dev[0].wps_read_pin()
3628 hapd.request("WPS_PIN any " + pin)
3629 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3630 dev[0].dump_monitor()
3631 try:
3632 dev[0].request("SET wps_priority 6")
3633 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3634 dev[0].wait_connected(timeout=30)
3635 netw = dev[0].list_networks()
3636 prio = dev[0].get_network(netw[0]['id'], 'priority')
3637 if prio != '6':
3638 raise Exception("Unexpected network priority: " + prio)
3639 finally:
3640 dev[0].request("SET wps_priority 0")
2c3a0190 3641
df1d01cf
JM
3642def test_ap_wps_and_non_wps(dev, apdev):
3643 """WPS and non-WPS AP in single hostapd process"""
3644 params = { "ssid": "wps", "eap_server": "1", "wps_state": "1" }
3645 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
3646
3647 params = { "ssid": "no wps" }
3648 hapd2 = hostapd.add_ap(apdev[1]['ifname'], params)
3649
3650 appin = hapd.request("WPS_AP_PIN random")
3651 if "FAIL" in appin:
3652 raise Exception("Could not generate random AP PIN")
3653 if appin not in hapd.request("WPS_AP_PIN get"):
3654 raise Exception("Could not fetch current AP PIN")
3655
3656 if "FAIL" in hapd.request("WPS_PBC"):
3657 raise Exception("WPS_PBC failed")
3658 if "FAIL" in hapd.request("WPS_CANCEL"):
3659 raise Exception("WPS_CANCEL failed")
3660
2c3a0190
JM
3661def test_ap_wps_init_oom(dev, apdev):
3662 """Initial AP configuration and OOM during PSK generation"""
3663 ssid = "test-wps"
3664 params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
3665 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
3666
3667 with alloc_fail(hapd, 1, "base64_encode;wps_build_cred"):
3668 pin = dev[0].wps_read_pin()
3669 hapd.request("WPS_PIN any " + pin)
3670 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3671 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3672 dev[0].wait_disconnected()
3673
3674 hapd.request("WPS_PIN any " + pin)
3675 dev[0].wait_connected(timeout=30)
ccf4d764
JM
3676
3677def test_ap_wps_er_oom(dev, apdev):
3678 """WPS ER OOM in XML processing"""
3679 try:
3680 _test_ap_wps_er_oom(dev, apdev)
3681 finally:
3682 dev[0].request("WPS_ER_STOP")
3683 dev[1].request("WPS_CANCEL")
3684 dev[0].request("DISCONNECT")
3685
3686def _test_ap_wps_er_oom(dev, apdev):
3687 ssid = "wps-er-ap-config"
3688 ap_pin = "12345670"
3689 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3690 hostapd.add_ap(apdev[0]['ifname'],
3691 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3692 "wpa_passphrase": "12345678", "wpa": "2",
3693 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3694 "device_name": "Wireless AP", "manufacturer": "Company",
3695 "model_name": "WAP", "model_number": "123",
3696 "serial_number": "12345", "device_type": "6-0050F204-1",
3697 "os_version": "01020300",
3698 "config_methods": "label push_button",
3699 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
3700
3701 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
3702
3703 with alloc_fail(dev[0], 1, "base64_decode;xml_get_base64_item"):
3704 dev[0].request("WPS_ER_START ifname=lo")
3705 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=3)
3706 if ev is not None:
3707 raise Exception("Unexpected AP discovery")
3708
3709 dev[0].request("WPS_ER_STOP")
3710 dev[0].request("WPS_ER_START ifname=lo")
3711 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
3712 if ev is None:
3713 raise Exception("AP discovery timed out")
3714
3715 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3716 with alloc_fail(dev[0], 1, "base64_decode;xml_get_base64_item"):
3717 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
3718 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
3719 if ev is None:
3720 raise Exception("PBC scan failed")
3721 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
3722 if ev is None:
3723 raise Exception("Enrollee discovery timed out")
2602a2ff 3724
c965ae03
JM
3725def test_ap_wps_er_init_oom(dev, apdev):
3726 """WPS ER and OOM during init"""
3727 try:
3728 _test_ap_wps_er_init_oom(dev, apdev)
3729 finally:
3730 dev[0].request("WPS_ER_STOP")
3731
3732def _test_ap_wps_er_init_oom(dev, apdev):
3733 with alloc_fail(dev[0], 1, "wps_er_init"):
3734 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3735 raise Exception("WPS_ER_START succeeded during OOM")
3736 with alloc_fail(dev[0], 1, "http_server_init"):
3737 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3738 raise Exception("WPS_ER_START succeeded during OOM")
3739 with alloc_fail(dev[0], 2, "http_server_init"):
3740 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3741 raise Exception("WPS_ER_START succeeded during OOM")
9b35afd6 3742 with alloc_fail(dev[0], 1, "eloop_sock_table_add_sock;?eloop_register_sock;wps_er_ssdp_init"):
c965ae03
JM
3743 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3744 raise Exception("WPS_ER_START succeeded during OOM")
3745 with fail_test(dev[0], 1, "os_get_random;wps_er_init"):
3746 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3747 raise Exception("WPS_ER_START succeeded during os_get_random failure")
3748
07536b18
JM
3749def test_ap_wps_er_init_fail(dev, apdev):
3750 """WPS ER init failure"""
3751 if "FAIL" not in dev[0].request("WPS_ER_START ifname=does-not-exist"):
3752 dev[0].request("WPS_ER_STOP")
3753 raise Exception("WPS_ER_START with non-existing ifname succeeded")
3754
2602a2ff
JM
3755def test_ap_wps_wpa_cli_action(dev, apdev, test_params):
3756 """WPS events and wpa_cli action script"""
8936b095
JM
3757 logdir = os.path.abspath(test_params['logdir'])
3758 pidfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.pid')
3759 logfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.res')
3760 actionfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.action.sh')
2602a2ff
JM
3761
3762 with open(actionfile, 'w') as f:
3763 f.write('#!/bin/sh\n')
3764 f.write('echo $* >> %s\n' % logfile)
3765 # Kill the process and wait some time before returning to allow all the
3766 # pending events to be processed with some of this happening after the
3767 # eloop SIGALRM signal has been scheduled.
3768 f.write('if [ $2 = "WPS-SUCCESS" -a -r %s ]; then kill `cat %s`; sleep 1; fi\n' % (pidfile, pidfile))
3769
8936b095
JM
3770 os.chmod(actionfile, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC |
3771 stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
2602a2ff
JM
3772
3773 ssid = "test-wps-conf"
3774 hostapd.add_ap(apdev[0]['ifname'],
3775 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3776 "wpa_passphrase": "12345678", "wpa": "2",
3777 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3778 hapd = hostapd.Hostapd(apdev[0]['ifname'])
3779
3780 prg = os.path.join(test_params['logdir'],
3781 'alt-wpa_supplicant/wpa_supplicant/wpa_cli')
3782 if not os.path.exists(prg):
3783 prg = '../../wpa_supplicant/wpa_cli'
3784 arg = [ prg, '-P', pidfile, '-B', '-i', dev[0].ifname, '-a', actionfile ]
3785 subprocess.call(arg)
3786
3787 arg = [ 'ps', 'ax' ]
3788 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3789 out = cmd.communicate()[0]
3790 cmd.wait()
3791 logger.debug("Processes:\n" + out)
3792 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) not in out:
3793 raise Exception("Did not see wpa_cli running")
3794
3795 hapd.request("WPS_PIN any 12345670")
3796 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3797 dev[0].dump_monitor()
3798 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3799 dev[0].wait_connected(timeout=30)
3800
3801 for i in range(30):
3802 if not os.path.exists(pidfile):
3803 break
3804 time.sleep(0.1)
3805
3806 if not os.path.exists(logfile):
3807 raise Exception("wpa_cli action results file not found")
3808 with open(logfile, 'r') as f:
3809 res = f.read()
3810 if "WPS-SUCCESS" not in res:
3811 raise Exception("WPS-SUCCESS event not seen in action file")
3812
3813 arg = [ 'ps', 'ax' ]
3814 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3815 out = cmd.communicate()[0]
3816 cmd.wait()
3817 logger.debug("Remaining processes:\n" + out)
3818 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) in out:
3819 raise Exception("wpa_cli still running")
3820
3821 if os.path.exists(pidfile):
3822 raise Exception("PID file not removed")
c965ae03
JM
3823
3824def test_ap_wps_er_ssdp_proto(dev, apdev):
3825 """WPS ER SSDP protocol testing"""
3826 try:
3827 _test_ap_wps_er_ssdp_proto(dev, apdev)
3828 finally:
3829 dev[0].request("WPS_ER_STOP")
3830
3831def _test_ap_wps_er_ssdp_proto(dev, apdev):
3832 socket.setdefaulttimeout(1)
3833 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
3834 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
3835 sock.bind(("239.255.255.250", 1900))
3836 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo foo"):
3837 raise Exception("Invalid filter accepted")
3838 if "OK" not in dev[0].request("WPS_ER_START ifname=lo 1.2.3.4"):
3839 raise Exception("WPS_ER_START with filter failed")
3840 (msg,addr) = sock.recvfrom(1000)
3841 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3842 if "M-SEARCH" not in msg:
3843 raise Exception("Not an M-SEARCH")
3844 sock.sendto("FOO", addr)
3845 time.sleep(0.1)
3846 dev[0].request("WPS_ER_STOP")
3847
3848 dev[0].request("WPS_ER_START ifname=lo")
3849 (msg,addr) = sock.recvfrom(1000)
3850 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3851 if "M-SEARCH" not in msg:
3852 raise Exception("Not an M-SEARCH")
3853 sock.sendto("FOO", addr)
3854 sock.sendto("HTTP/1.1 200 OK\r\nFOO\r\n\r\n", addr)
3855 sock.sendto("HTTP/1.1 200 OK\r\nNTS:foo\r\n\r\n", addr)
3856 sock.sendto("HTTP/1.1 200 OK\r\nNTS:ssdp:byebye\r\n\r\n", addr)
3857 sock.sendto("HTTP/1.1 200 OK\r\ncache-control: foo=1\r\n\r\n", addr)
3858 sock.sendto("HTTP/1.1 200 OK\r\ncache-control: max-age=1\r\n\r\n", addr)
3859 sock.sendto("HTTP/1.1 200 OK\r\nusn:\r\n\r\n", addr)
3860 sock.sendto("HTTP/1.1 200 OK\r\nusn:foo\r\n\r\n", addr)
3861 sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid:\r\n\r\n", addr)
3862 sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid: \r\n\r\n", addr)
3863 sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid: foo\r\n\r\n", addr)
3864 sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\n\r\n", addr)
3865 sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nNTS:ssdp:byebye\r\n\r\n", addr)
3866 sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\n\r\n", addr)
3867 with alloc_fail(dev[0], 1, "wps_er_ap_add"):
3868 sock.sendto("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)
3869 time.sleep(0.1)
3870 with alloc_fail(dev[0], 2, "wps_er_ap_add"):
3871 sock.sendto("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)
3872 time.sleep(0.1)
3873
3874 # Add an AP with bogus URL
3875 sock.sendto("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)
3876 # Update timeout on AP without updating URL
3877 sock.sendto("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)
3878 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
3879 if ev is None:
3880 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3881
3882 # Add an AP with a valid URL (but no server listing to it)
3883 sock.sendto("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)
3884 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
3885 if ev is None:
3886 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3887
3888 sock.close()
3889
3890wps_event_url = None
3891
6aaa661a
JM
3892def gen_upnp_info(eventSubURL='wps_event', controlURL='wps_control',
3893 udn='uuid:27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'):
4c3ae1c0 3894 payload = '''<?xml version="1.0"?>
c965ae03
JM
3895<root xmlns="urn:schemas-upnp-org:device-1-0">
3896<specVersion>
3897<major>1</major>
3898<minor>0</minor>
3899</specVersion>
3900<device>
3901<deviceType>urn:schemas-wifialliance-org:device:WFADevice:1</deviceType>
3902<friendlyName>WPS Access Point</friendlyName>
3903<manufacturer>Company</manufacturer>
3904<modelName>WAP</modelName>
3905<modelNumber>123</modelNumber>
3906<serialNumber>12345</serialNumber>
6aaa661a
JM
3907'''
3908 if udn:
3909 payload += '<UDN>' + udn + '</UDN>'
3910 payload += '''<serviceList>
c965ae03
JM
3911<service>
3912<serviceType>urn:schemas-wifialliance-org:service:WFAWLANConfig:1</serviceType>
3913<serviceId>urn:wifialliance-org:serviceId:WFAWLANConfig1</serviceId>
3914<SCPDURL>wps_scpd.xml</SCPDURL>
4c3ae1c0 3915'''
6aaa661a
JM
3916 if controlURL:
3917 payload += '<controlURL>' + controlURL + '</controlURL>\n'
4c3ae1c0 3918 if eventSubURL:
6aaa661a 3919 payload += '<eventSubURL>' + eventSubURL + '</eventSubURL>\n'
4c3ae1c0 3920 payload += '''</service>
c965ae03
JM
3921</serviceList>
3922</device>
3923</root>
3924'''
4c3ae1c0
JM
3925 hdr = 'HTTP/1.1 200 OK\r\n' + \
3926 'Content-Type: text/xml; charset="utf-8"\r\n' + \
3927 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3928 'Connection: close\r\n' + \
3929 'Content-Length: ' + str(len(payload)) + '\r\n' + \
3930 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3931 return hdr + payload
3932
6aaa661a 3933def gen_wps_control(payload_override=None):
4c3ae1c0 3934 payload = '''<?xml version="1.0"?>
c965ae03
JM
3935<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
3936<s:Body>
3937<u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
3938<NewDeviceInfo>EEoAARAQIgABBBBHABAn6oAanlxOc72C+Jy80Q1+ECAABgIAAAADABAaABCJZ7DPtbU3Ust9
3939Z3wJF07WEDIAwH45D3i1OqB7eJGwTzqeapS71h3KyXncK2xJZ+xqScrlorNEg6LijBJzG2Ca
3940+FZli0iliDJd397yAx/jk4nFXco3q5ylBSvSw9dhJ5u1xBKSnTilKGlUHPhLP75PUqM3fot9
39417zwtFZ4bx6x1sBA6oEe2d0aUJmLumQGCiKEIWlnxs44zego/2tAe81bDzdPBM7o5HH/FUhD+
3942KoGzFXp51atP+1n9Vta6AkI0Vye99JKLcC6Md9dMJltSVBgd4Xc4lRAEAAIAIxAQAAIADRAN
3943AAEBEAgAAgAEEEQAAQIQIQAHQ29tcGFueRAjAANXQVAQJAADMTIzEEIABTEyMzQ1EFQACAAG
3944AFDyBAABEBEAC1dpcmVsZXNzIEFQEDwAAQEQAgACAAAQEgACAAAQCQACAAAQLQAEgQIDABBJ
3945AAYANyoAASA=
3946</NewDeviceInfo>
3947</u:GetDeviceInfoResponse>
3948</s:Body>
3949</s:Envelope>
3950'''
6aaa661a
JM
3951 if payload_override:
3952 payload = payload_override
4c3ae1c0
JM
3953 hdr = 'HTTP/1.1 200 OK\r\n' + \
3954 'Content-Type: text/xml; charset="utf-8"\r\n' + \
3955 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3956 'Connection: close\r\n' + \
3957 'Content-Length: ' + str(len(payload)) + '\r\n' + \
3958 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3959 return hdr + payload
3960
6aaa661a 3961def gen_wps_event(sid='uuid:7eb3342a-8a5f-47fe-a585-0785bfec6d8a'):
4c3ae1c0
JM
3962 payload = ""
3963 hdr = 'HTTP/1.1 200 OK\r\n' + \
3964 'Content-Type: text/xml; charset="utf-8"\r\n' + \
3965 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3966 'Connection: close\r\n' + \
6aaa661a
JM
3967 'Content-Length: ' + str(len(payload)) + '\r\n'
3968 if sid:
3969 hdr += 'SID: ' + sid + '\r\n'
3970 hdr += 'Timeout: Second-1801\r\n' + \
4c3ae1c0
JM
3971 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3972 return hdr + payload
3973
3974class WPSAPHTTPServer(SocketServer.StreamRequestHandler):
3975 def handle(self):
3976 data = self.rfile.readline().strip()
3977 logger.info("HTTP server received: " + data)
3978 while True:
3979 hdr = self.rfile.readline().strip()
3980 if len(hdr) == 0:
3981 break
3982 logger.info("HTTP header: " + hdr)
3983 if "CALLBACK:" in hdr:
3984 global wps_event_url
3985 wps_event_url = hdr.split(' ')[1].strip('<>')
3986
3987 if "GET /foo.xml" in data:
6aaa661a
JM
3988 self.handle_upnp_info()
3989 elif "POST /wps_control" in data:
3990 self.handle_wps_control()
3991 elif "SUBSCRIBE /wps_event" in data:
3992 self.handle_wps_event()
24b7f282
JM
3993 else:
3994 self.handle_others(data)
6aaa661a
JM
3995
3996 def handle_upnp_info(self):
3997 self.wfile.write(gen_upnp_info())
4c3ae1c0 3998
6aaa661a
JM
3999 def handle_wps_control(self):
4000 self.wfile.write(gen_wps_control())
c965ae03 4001
6aaa661a
JM
4002 def handle_wps_event(self):
4003 self.wfile.write(gen_wps_event())
c965ae03 4004
24b7f282
JM
4005 def handle_others(self, data):
4006 logger.info("Ignore HTTP request: " + data)
4007
4c3ae1c0
JM
4008class MyTCPServer(SocketServer.TCPServer):
4009 def __init__(self, addr, handler):
4010 self.allow_reuse_address = True
4011 SocketServer.TCPServer.__init__(self, addr, handler)
c965ae03 4012
24b7f282
JM
4013def wps_er_start(dev, http_server, max_age=1, wait_m_search=False,
4014 location_url=None):
c965ae03
JM
4015 socket.setdefaulttimeout(1)
4016 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4017 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4018 sock.bind(("239.255.255.250", 1900))
4c3ae1c0 4019 dev.request("WPS_ER_START ifname=lo")
24b7f282
JM
4020 for i in range(100):
4021 (msg,addr) = sock.recvfrom(1000)
4022 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4023 if "M-SEARCH" in msg:
4024 break
4025 if not wait_m_search:
4026 raise Exception("Not an M-SEARCH")
4027 if i == 99:
4028 raise Exception("No M-SEARCH seen")
c965ae03
JM
4029
4030 # Add an AP with a valid URL and server listing to it
4c3ae1c0 4031 server = MyTCPServer(("127.0.0.1", 12345), http_server)
24b7f282
JM
4032 if not location_url:
4033 location_url = 'http://127.0.0.1:12345/foo.xml'
4034 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), addr)
c965ae03 4035 server.timeout = 1
4c3ae1c0
JM
4036 return server,sock
4037
4038def wps_er_stop(dev, sock, server, on_alloc_fail=False):
4039 sock.close()
4040 server.server_close()
4041
4042 if on_alloc_fail:
4043 done = False
4044 for i in range(50):
4045 res = dev.request("GET_ALLOC_FAIL")
4046 if res.startswith("0:"):
4047 done = True
4048 break
4049 time.sleep(0.1)
4050 if not done:
4051 raise Exception("No allocation failure reported")
4052 else:
4053 ev = dev.wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4054 if ev is None:
4055 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4056 dev.request("WPS_ER_STOP")
4057
24b7f282 4058def run_wps_er_proto_test(dev, handler, no_event_url=False, location_url=None):
6aaa661a
JM
4059 try:
4060 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
24b7f282 4061 server,sock = wps_er_start(dev, handler, location_url=location_url)
6aaa661a
JM
4062 global wps_event_url
4063 wps_event_url = None
4064 server.handle_request()
4065 server.handle_request()
4066 server.handle_request()
4067 server.server_close()
4068 if no_event_url:
4069 if wps_event_url:
4070 raise Exception("Received event URL unexpectedly")
4071 return
4072 if wps_event_url is None:
4073 raise Exception("Did not get event URL")
4074 logger.info("Event URL: " + wps_event_url)
4075 finally:
24b7f282 4076 dev.request("WPS_ER_STOP")
6aaa661a 4077
18478107 4078def send_wlanevent(url, uuid, data, no_response=False):
6aaa661a
JM
4079 conn = httplib.HTTPConnection(url.netloc)
4080 payload = '''<?xml version="1.0" encoding="utf-8"?>
4081<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4082<e:property><STAStatus>1</STAStatus></e:property>
4083<e:property><APStatus>1</APStatus></e:property>
4084<e:property><WLANEvent>'''
4085 payload += base64.b64encode(data)
4086 payload += '</WLANEvent></e:property></e:propertyset>'
4087 headers = { "Content-type": 'text/xml; charset="utf-8"',
4088 "Server": "Unspecified, UPnP/1.0, Unspecified",
4089 "HOST": url.netloc,
4090 "NT": "upnp:event",
4091 "SID": "uuid:" + uuid,
4092 "SEQ": "0",
4093 "Content-Length": str(len(payload)) }
4094 conn.request("NOTIFY", url.path, payload, headers)
18478107
JM
4095 if no_response:
4096 try:
4097 conn.getresponse()
4098 except Exception, e:
4099 pass
4100 return
6aaa661a
JM
4101 resp = conn.getresponse()
4102 if resp.status != 200:
4103 raise Exception("Unexpected HTTP response: %d" % resp.status)
4104
4c3ae1c0
JM
4105def test_ap_wps_er_http_proto(dev, apdev):
4106 """WPS ER HTTP protocol testing"""
4107 try:
4108 _test_ap_wps_er_http_proto(dev, apdev)
4109 finally:
4110 dev[0].request("WPS_ER_STOP")
4111
4112def _test_ap_wps_er_http_proto(dev, apdev):
4113 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
6aaa661a 4114 server,sock = wps_er_start(dev[0], WPSAPHTTPServer, max_age=15)
c965ae03
JM
4115 global wps_event_url
4116 wps_event_url = None
4117 server.handle_request()
4118 server.handle_request()
4119 server.handle_request()
4120 server.server_close()
4121 if wps_event_url is None:
4122 raise Exception("Did not get event URL")
4123 logger.info("Event URL: " + wps_event_url)
4124
4125 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
4126 if ev is None:
4127 raise Exception("No WPS-ER-AP-ADD event")
4128 if uuid not in ev:
4129 raise Exception("UUID mismatch")
4130
4131 sock.close()
4132
4133 logger.info("Valid Probe Request notification")
4134 url = urlparse.urlparse(wps_event_url)
4135 conn = httplib.HTTPConnection(url.netloc)
4136 payload = '''<?xml version="1.0" encoding="utf-8"?>
4137<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4138<e:property><STAStatus>1</STAStatus></e:property>
4139<e:property><APStatus>1</APStatus></e:property>
4140<e:property><WLANEvent>ATAyOjAwOjAwOjAwOjAwOjAwEEoAARAQOgABAhAIAAIxSBBHABA2LbR7pTpRkYj7VFi5hrLk
4141EFQACAAAAAAAAAAAEDwAAQMQAgACAAAQCQACAAAQEgACAAAQIQABIBAjAAEgECQAASAQEQAI
4142RGV2aWNlIEEQSQAGADcqAAEg
4143</WLANEvent></e:property>
4144</e:propertyset>
4145'''
4146 headers = { "Content-type": 'text/xml; charset="utf-8"',
4147 "Server": "Unspecified, UPnP/1.0, Unspecified",
4148 "HOST": url.netloc,
4149 "NT": "upnp:event",
4150 "SID": "uuid:" + uuid,
4151 "SEQ": "0",
4152 "Content-Length": str(len(payload)) }
4153 conn.request("NOTIFY", url.path, payload, headers)
4154 resp = conn.getresponse()
4155 if resp.status != 200:
4156 raise Exception("Unexpected HTTP response: %d" % resp.status)
4157
4158 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=5)
4159 if ev is None:
4160 raise Exception("No WPS-ER-ENROLLEE-ADD event")
4161 if "362db47b-a53a-5191-88fb-5458b986b2e4" not in ev:
4162 raise Exception("No Enrollee UUID match")
4163
4164 logger.info("Incorrect event URL AP id")
4165 conn = httplib.HTTPConnection(url.netloc)
4166 conn.request("NOTIFY", url.path + '123', payload, headers)
4167 resp = conn.getresponse()
4168 if resp.status != 404:
4169 raise Exception("Unexpected HTTP response: %d" % resp.status)
4170
4171 logger.info("Missing AP id")
4172 conn = httplib.HTTPConnection(url.netloc)
4173 conn.request("NOTIFY", '/event/' + url.path.split('/')[2],
4174 payload, headers)
4175 time.sleep(0.1)
4176
4177 logger.info("Incorrect event URL event id")
4178 conn = httplib.HTTPConnection(url.netloc)
4179 conn.request("NOTIFY", '/event/123456789/123', payload, headers)
4180 time.sleep(0.1)
4181
4182 logger.info("Incorrect event URL prefix")
4183 conn = httplib.HTTPConnection(url.netloc)
4184 conn.request("NOTIFY", '/foobar/123456789/123', payload, headers)
4185 resp = conn.getresponse()
4186 if resp.status != 404:
4187 raise Exception("Unexpected HTTP response: %d" % resp.status)
4188
4189 logger.info("Unsupported request")
4190 conn = httplib.HTTPConnection(url.netloc)
4191 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4192 resp = conn.getresponse()
4193 if resp.status != 501:
4194 raise Exception("Unexpected HTTP response: %d" % resp.status)
4195
4196 logger.info("Unsupported request and OOM")
4197 with alloc_fail(dev[0], 1, "wps_er_http_req"):
4198 conn = httplib.HTTPConnection(url.netloc)
4199 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4200 time.sleep(0.5)
4c3ae1c0 4201
6aaa661a
JM
4202 logger.info("Too short WLANEvent")
4203 data = '\x00'
4204 send_wlanevent(url, uuid, data)
4205
4206 logger.info("Invalid WLANEventMAC")
4207 data = '\x00qwertyuiopasdfghjklzxcvbnm'
4208 send_wlanevent(url, uuid, data)
4209
4210 logger.info("Unknown WLANEventType")
4211 data = '\xff02:00:00:00:00:00'
4212 send_wlanevent(url, uuid, data)
4213
4214 logger.info("Probe Request notification without any attributes")
4215 data = '\x0102:00:00:00:00:00'
4216 send_wlanevent(url, uuid, data)
4217
4218 logger.info("Probe Request notification with invalid attribute")
4219 data = '\x0102:00:00:00:00:00\xff'
4220 send_wlanevent(url, uuid, data)
4221
4222 logger.info("EAP message without any attributes")
4223 data = '\x0202:00:00:00:00:00'
4224 send_wlanevent(url, uuid, data)
4225
4226 logger.info("EAP message with invalid attribute")
4227 data = '\x0202:00:00:00:00:00\xff'
4228 send_wlanevent(url, uuid, data)
4229
4230 logger.info("EAP message from new STA and not M1")
4231 data = '\x0202:ff:ff:ff:ff:ff' + '\x10\x22\x00\x01\x05'
4232 send_wlanevent(url, uuid, data)
4233
4234 logger.info("EAP message: M1")
4235 data = '\x0202:00:00:00:00:00'
4236 data += '\x10\x22\x00\x01\x04'
4237 data += '\x10\x47\x00\x10' + 16*'\x00'
4238 data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4239 data += '\x10\x1a\x00\x10' + 16*'\x00'
4240 data += '\x10\x32\x00\xc0' + 192*'\x00'
4241 data += '\x10\x04\x00\x02\x00\x00'
4242 data += '\x10\x10\x00\x02\x00\x00'
4243 data += '\x10\x0d\x00\x01\x00'
4244 data += '\x10\x08\x00\x02\x00\x00'
4245 data += '\x10\x44\x00\x01\x00'
4246 data += '\x10\x21\x00\x00'
4247 data += '\x10\x23\x00\x00'
4248 data += '\x10\x24\x00\x00'
4249 data += '\x10\x42\x00\x00'
4250 data += '\x10\x54\x00\x08' + 8*'\x00'
4251 data += '\x10\x11\x00\x00'
4252 data += '\x10\x3c\x00\x01\x00'
4253 data += '\x10\x02\x00\x02\x00\x00'
4254 data += '\x10\x12\x00\x02\x00\x00'
4255 data += '\x10\x09\x00\x02\x00\x00'
4256 data += '\x10\x2d\x00\x04\x00\x00\x00\x00'
4257 m1 = data
4258 send_wlanevent(url, uuid, data)
4259
4260 logger.info("EAP message: WSC_ACK")
4261 data = '\x0202:00:00:00:00:00' + '\x10\x22\x00\x01\x0d'
4262 send_wlanevent(url, uuid, data)
4263
4264 logger.info("EAP message: M1")
4265 send_wlanevent(url, uuid, m1)
4266
4267 logger.info("EAP message: WSC_NACK")
4268 data = '\x0202:00:00:00:00:00' + '\x10\x22\x00\x01\x0e'
4269 send_wlanevent(url, uuid, data)
4270
4271 logger.info("EAP message: M1 - Too long attribute values")
4272 data = '\x0202:00:00:00:00:00'
4273 data += '\x10\x11\x00\x21' + 33*'\x00'
4274 data += '\x10\x45\x00\x21' + 33*'\x00'
4275 data += '\x10\x42\x00\x21' + 33*'\x00'
4276 data += '\x10\x24\x00\x21' + 33*'\x00'
4277 data += '\x10\x23\x00\x21' + 33*'\x00'
4278 data += '\x10\x21\x00\x41' + 65*'\x00'
4279 data += '\x10\x49\x00\x09\x00\x37\x2a\x05\x02\x00\x00\x05\x00'
4280 send_wlanevent(url, uuid, data)
4281
4282 logger.info("EAP message: M1 missing UUID-E")
4283 data = '\x0202:00:00:00:00:00'
4284 data += '\x10\x22\x00\x01\x04'
4285 send_wlanevent(url, uuid, data)
4286
4287 logger.info("EAP message: M1 missing MAC Address")
4288 data += '\x10\x47\x00\x10' + 16*'\x00'
4289 send_wlanevent(url, uuid, data)
4290
4291 logger.info("EAP message: M1 missing Enrollee Nonce")
4292 data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4293 send_wlanevent(url, uuid, data)
4294
4295 logger.info("EAP message: M1 missing Public Key")
4296 data += '\x10\x1a\x00\x10' + 16*'\x00'
4297 send_wlanevent(url, uuid, data)
4298
4299 logger.info("EAP message: M1 missing Authentication Type flags")
4300 data += '\x10\x32\x00\xc0' + 192*'\x00'
4301 send_wlanevent(url, uuid, data)
4302
4303 logger.info("EAP message: M1 missing Encryption Type Flags")
4304 data += '\x10\x04\x00\x02\x00\x00'
4305 send_wlanevent(url, uuid, data)
4306
4307 logger.info("EAP message: M1 missing Connection Type flags")
4308 data += '\x10\x10\x00\x02\x00\x00'
4309 send_wlanevent(url, uuid, data)
4310
4311 logger.info("EAP message: M1 missing Config Methods")
4312 data += '\x10\x0d\x00\x01\x00'
4313 send_wlanevent(url, uuid, data)
4314
4315 logger.info("EAP message: M1 missing Wi-Fi Protected Setup State")
4316 data += '\x10\x08\x00\x02\x00\x00'
4317 send_wlanevent(url, uuid, data)
4318
4319 logger.info("EAP message: M1 missing Manufacturer")
4320 data += '\x10\x44\x00\x01\x00'
4321 send_wlanevent(url, uuid, data)
4322
4323 logger.info("EAP message: M1 missing Model Name")
4324 data += '\x10\x21\x00\x00'
4325 send_wlanevent(url, uuid, data)
4326
4327 logger.info("EAP message: M1 missing Model Number")
4328 data += '\x10\x23\x00\x00'
4329 send_wlanevent(url, uuid, data)
4330
4331 logger.info("EAP message: M1 missing Serial Number")
4332 data += '\x10\x24\x00\x00'
4333 send_wlanevent(url, uuid, data)
4334
4335 logger.info("EAP message: M1 missing Primary Device Type")
4336 data += '\x10\x42\x00\x00'
4337 send_wlanevent(url, uuid, data)
4338
4339 logger.info("EAP message: M1 missing Device Name")
4340 data += '\x10\x54\x00\x08' + 8*'\x00'
4341 send_wlanevent(url, uuid, data)
4342
4343 logger.info("EAP message: M1 missing RF Bands")
4344 data += '\x10\x11\x00\x00'
4345 send_wlanevent(url, uuid, data)
4346
4347 logger.info("EAP message: M1 missing Association State")
4348 data += '\x10\x3c\x00\x01\x00'
4349 send_wlanevent(url, uuid, data)
4350
4351 logger.info("EAP message: M1 missing Device Password ID")
4352 data += '\x10\x02\x00\x02\x00\x00'
4353 send_wlanevent(url, uuid, data)
4354
4355 logger.info("EAP message: M1 missing Configuration Error")
4356 data += '\x10\x12\x00\x02\x00\x00'
4357 send_wlanevent(url, uuid, data)
4358
4359 logger.info("EAP message: M1 missing OS Version")
4360 data += '\x10\x09\x00\x02\x00\x00'
4361 send_wlanevent(url, uuid, data)
4c3ae1c0 4362
24b7f282
JM
4363 logger.info("Check max concurrent requests")
4364 addr = (url.hostname, url.port)
4365 socks = {}
4366 for i in range(20):
4367 socks[i] = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4368 socket.IPPROTO_TCP)
4369 socks[i].connect(addr)
4370 for i in range(20):
4371 socks[i].send("GET / HTTP/1.1\r\n\r\n")
4372 count = 0
4373 for i in range(20):
4374 try:
4375 res = socks[i].recv(100)
4376 if "HTTP/1" in res:
4377 count += 1
4378 except:
4379 pass
4380 socks[i].close()
4381 logger.info("%d concurrent HTTP GET operations returned response" % count)
4382 if count < 10:
4383 raise Exception("Too few concurrent HTTP connections accepted")
4384
4385 logger.info("OOM in HTTP server")
4386 for func in [ "http_request_init", "httpread_create",
4387 "eloop_register_timeout;httpread_create",
9b35afd6 4388 "eloop_sock_table_add_sock;?eloop_register_sock;httpread_create",
24b7f282
JM
4389 "httpread_hdr_analyze" ]:
4390 with alloc_fail(dev[0], 1, func):
4391 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4392 socket.IPPROTO_TCP)
4393 sock.connect(addr)
4394 sock.send("GET / HTTP/1.1\r\n\r\n")
4395 try:
4396 sock.recv(100)
4397 except:
4398 pass
4399 sock.close()
4400
4401 logger.info("Invalid HTTP header")
4402 for req in [ " GET / HTTP/1.1\r\n\r\n",
4403 "HTTP/1.1 200 OK\r\n\r\n",
4404 "HTTP/\r\n\r\n",
4405 "GET %%a%aa% HTTP/1.1\r\n\r\n",
4406 "GET / HTTP/1.1\r\n FOO\r\n\r\n",
4407 "NOTIFY / HTTP/1.1\r\n" + 4097*'a' + '\r\n\r\n',
4408 "NOTIFY / HTTP/1.1\r\n\r\n" + 8193*'a',
4409 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n foo\r\n",
4410 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n1\r\nfoo\r\n",
4411 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\n",
4412 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\naa\ra\r\n\ra" ]:
4413 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4414 socket.IPPROTO_TCP)
4415 sock.settimeout(0.1)
4416 sock.connect(addr)
4417 sock.send(req)
4418 try:
4419 sock.recv(100)
4420 except:
4421 pass
4422 sock.close()
4423
4424 with alloc_fail(dev[0], 2, "httpread_read_handler"):
4425 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4426 socket.IPPROTO_TCP)
4427 sock.connect(addr)
4428 sock.send("NOTIFY / HTTP/1.1\r\n\r\n" + 4500*'a')
4429 try:
4430 sock.recv(100)
4431 except:
4432 pass
4433 sock.close()
4434
4435 conn = httplib.HTTPConnection(url.netloc)
4436 payload = '<foo'
4437 headers = { "Content-type": 'text/xml; charset="utf-8"',
4438 "Server": "Unspecified, UPnP/1.0, Unspecified",
4439 "HOST": url.netloc,
4440 "NT": "upnp:event",
4441 "SID": "uuid:" + uuid,
4442 "SEQ": "0",
4443 "Content-Length": str(len(payload)) }
4444 conn.request("NOTIFY", url.path, payload, headers)
4445 resp = conn.getresponse()
4446 if resp.status != 200:
4447 raise Exception("Unexpected HTTP response: %d" % resp.status)
4448
4449 conn = httplib.HTTPConnection(url.netloc)
4450 payload = '<WLANEvent foo></WLANEvent>'
4451 headers = { "Content-type": 'text/xml; charset="utf-8"',
4452 "Server": "Unspecified, UPnP/1.0, Unspecified",
4453 "HOST": url.netloc,
4454 "NT": "upnp:event",
4455 "SID": "uuid:" + uuid,
4456 "SEQ": "0",
4457 "Content-Length": str(len(payload)) }
4458 conn.request("NOTIFY", url.path, payload, headers)
4459 resp = conn.getresponse()
4460 if resp.status != 200:
4461 raise Exception("Unexpected HTTP response: %d" % resp.status)
4462
4463 with alloc_fail(dev[0], 1, "xml_get_first_item"):
4464 send_wlanevent(url, uuid, '')
4465
4466 with alloc_fail(dev[0], 1, "wpabuf_alloc_ext_data;xml_get_base64_item"):
4467 send_wlanevent(url, uuid, 'foo')
4468
4469 for func in [ "wps_init",
4470 "wps_process_manufacturer",
4471 "wps_process_model_name",
4472 "wps_process_model_number",
4473 "wps_process_serial_number",
4474 "wps_process_dev_name" ]:
4475 with alloc_fail(dev[0], 1, func):
4476 send_wlanevent(url, uuid, m1)
4477
18478107
JM
4478 with alloc_fail(dev[0], 1, "wps_er_http_resp_ok"):
4479 send_wlanevent(url, uuid, m1, no_response=True)
4480
4481 with alloc_fail(dev[0], 1, "wps_er_http_resp_not_found"):
4482 url2 = urlparse.urlparse(wps_event_url.replace('/event/', '/notfound/'))
4483 send_wlanevent(url2, uuid, m1, no_response=True)
4484
3d105cdf
JM
4485 logger.info("EAP message: M1")
4486 data = '\x0202:11:22:00:00:00'
4487 data += '\x10\x22\x00\x01\x04'
4488 data += '\x10\x47\x00\x10' + 16*'\x00'
4489 data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4490 data += '\x10\x1a\x00\x10' + 16*'\x00'
4491 data += '\x10\x32\x00\xc0' + 192*'\x00'
4492 data += '\x10\x04\x00\x02\x00\x00'
4493 data += '\x10\x10\x00\x02\x00\x00'
4494 data += '\x10\x0d\x00\x01\x00'
4495 data += '\x10\x08\x00\x02\x00\x00'
4496 data += '\x10\x44\x00\x01\x00'
4497 data += '\x10\x21\x00\x00'
4498 data += '\x10\x23\x00\x00'
4499 data += '\x10\x24\x00\x00'
4500 data += '\x10\x42\x00\x00'
4501 data += '\x10\x54\x00\x08' + 8*'\x00'
4502 data += '\x10\x11\x00\x00'
4503 data += '\x10\x3c\x00\x01\x00'
4504 data += '\x10\x02\x00\x02\x00\x00'
4505 data += '\x10\x12\x00\x02\x00\x00'
4506 data += '\x10\x09\x00\x02\x00\x00'
4507 data += '\x10\x2d\x00\x04\x00\x00\x00\x00'
4508 dev[0].dump_monitor()
4509 with alloc_fail(dev[0], 1, "wps_er_add_sta_data"):
4510 send_wlanevent(url, uuid, data)
4511 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=0.1)
4512 if ev is not None:
4513 raise Exception("Unexpected enrollee add event")
4514 send_wlanevent(url, uuid, data)
4515 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=2)
4516 if ev is None:
4517 raise Exception("Enrollee add event not seen")
4518
fe67b945
JM
4519 with alloc_fail(dev[0], 1, "base64_encode;wps_er_soap_hdr"):
4520 send_wlanevent(url, uuid, data)
4521
4522 with alloc_fail(dev[0], 1, "wpabuf_alloc;wps_er_soap_hdr"):
4523 send_wlanevent(url, uuid, data)
4524
4525 with alloc_fail(dev[0], 1, "http_client_url_parse;wps_er_sta_send_msg"):
4526 send_wlanevent(url, uuid, data)
4527
4528 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_sta_send_msg"):
4529 send_wlanevent(url, uuid, data)
4530
4c3ae1c0
JM
4531def test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
4532 """WPS ER HTTP protocol testing - no eventSubURL"""
6aaa661a
JM
4533 class WPSAPHTTPServer_no_event_sub_url(WPSAPHTTPServer):
4534 def handle_upnp_info(self):
4535 self.wfile.write(gen_upnp_info(eventSubURL=None))
4536 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_event_sub_url,
4537 no_event_url=True)
4c3ae1c0
JM
4538
4539def test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev):
4540 """WPS ER HTTP protocol testing - DNS name in eventSubURL"""
6aaa661a
JM
4541 class WPSAPHTTPServer_event_sub_url_dns(WPSAPHTTPServer):
4542 def handle_upnp_info(self):
4543 self.wfile.write(gen_upnp_info(eventSubURL='http://example.com/wps_event'))
4544 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_event_sub_url_dns,
4545 no_event_url=True)
4c3ae1c0
JM
4546
4547def test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4548 """WPS ER HTTP protocol testing - subscribe OOM"""
4549 try:
4550 _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev)
4551 finally:
4552 dev[0].request("WPS_ER_STOP")
4553
4554def _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4555 tests = [ (1, "http_client_url_parse"),
4556 (1, "wpabuf_alloc;wps_er_subscribe"),
4557 (1, "http_client_addr"),
9b35afd6 4558 (1, "eloop_sock_table_add_sock;?eloop_register_sock;http_client_addr"),
4c3ae1c0
JM
4559 (1, "eloop_register_timeout;http_client_addr") ]
4560 for count,func in tests:
4561 with alloc_fail(dev[0], count, func):
4562 server,sock = wps_er_start(dev[0], WPSAPHTTPServer)
4563 server.handle_request()
4564 server.handle_request()
4565 wps_er_stop(dev[0], sock, server, on_alloc_fail=True)
6aaa661a
JM
4566
4567def test_ap_wps_er_http_proto_no_sid(dev, apdev):
4568 """WPS ER HTTP protocol testing - no SID"""
4569 class WPSAPHTTPServer_no_sid(WPSAPHTTPServer):
4570 def handle_wps_event(self):
4571 self.wfile.write(gen_wps_event(sid=None))
4572 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_sid)
4573
4574def test_ap_wps_er_http_proto_invalid_sid_no_uuid(dev, apdev):
4575 """WPS ER HTTP protocol testing - invalid SID - no UUID"""
4576 class WPSAPHTTPServer_invalid_sid_no_uuid(WPSAPHTTPServer):
4577 def handle_wps_event(self):
4578 self.wfile.write(gen_wps_event(sid='FOO'))
4579 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_no_uuid)
4580
4581def test_ap_wps_er_http_proto_invalid_sid_uuid(dev, apdev):
4582 """WPS ER HTTP protocol testing - invalid SID UUID"""
4583 class WPSAPHTTPServer_invalid_sid_uuid(WPSAPHTTPServer):
4584 def handle_wps_event(self):
4585 self.wfile.write(gen_wps_event(sid='uuid:FOO'))
4586 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_uuid)
4587
4588def test_ap_wps_er_http_proto_subscribe_failing(dev, apdev):
4589 """WPS ER HTTP protocol testing - SUBSCRIBE failing"""
4590 class WPSAPHTTPServer_fail_subscribe(WPSAPHTTPServer):
4591 def handle_wps_event(self):
4592 payload = ""
4593 hdr = 'HTTP/1.1 404 Not Found\r\n' + \
4594 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4595 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4596 'Connection: close\r\n' + \
4597 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4598 'Timeout: Second-1801\r\n' + \
4599 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4600 self.wfile.write(hdr + payload)
4601 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_fail_subscribe)
4602
4603def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4604 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4605 class WPSAPHTTPServer_subscribe_invalid_response(WPSAPHTTPServer):
4606 def handle_wps_event(self):
4607 payload = ""
4608 hdr = 'HTTP/1.1 FOO\r\n' + \
4609 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4610 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4611 'Connection: close\r\n' + \
4612 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4613 'Timeout: Second-1801\r\n' + \
4614 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4615 self.wfile.write(hdr + payload)
4616 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_subscribe_invalid_response)
4617
4618def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4619 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4620 class WPSAPHTTPServer_invalid_m1(WPSAPHTTPServer):
4621 def handle_wps_control(self):
4622 payload = '''<?xml version="1.0"?>
4623<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4624<s:Body>
4625<u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4626<NewDeviceInfo>Rk9P</NewDeviceInfo>
4627</u:GetDeviceInfoResponse>
4628</s:Body>
4629</s:Envelope>
4630'''
4631 self.wfile.write(gen_wps_control(payload_override=payload))
4632 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_m1, no_event_url=True)
4633
4634def test_ap_wps_er_http_proto_upnp_info_no_device(dev, apdev):
4635 """WPS ER HTTP protocol testing - No device in UPnP info"""
4636 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4637 def handle_upnp_info(self):
4638 payload = '''<?xml version="1.0"?>
4639<root xmlns="urn:schemas-upnp-org:device-1-0">
4640<specVersion>
4641<major>1</major>
4642<minor>0</minor>
4643</specVersion>
4644</root>
4645'''
4646 hdr = 'HTTP/1.1 200 OK\r\n' + \
4647 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4648 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4649 'Connection: close\r\n' + \
4650 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4651 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4652 self.wfile.write(hdr + payload)
4653 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4654
4655def test_ap_wps_er_http_proto_upnp_info_no_device_type(dev, apdev):
4656 """WPS ER HTTP protocol testing - No deviceType in UPnP info"""
4657 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4658 def handle_upnp_info(self):
4659 payload = '''<?xml version="1.0"?>
4660<root xmlns="urn:schemas-upnp-org:device-1-0">
4661<specVersion>
4662<major>1</major>
4663<minor>0</minor>
4664</specVersion>
4665<device>
4666</device>
4667</root>
4668'''
4669 hdr = 'HTTP/1.1 200 OK\r\n' + \
4670 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4671 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4672 'Connection: close\r\n' + \
4673 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4674 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4675 self.wfile.write(hdr + payload)
4676 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4677
4678def test_ap_wps_er_http_proto_upnp_info_invalid_udn_uuid(dev, apdev):
4679 """WPS ER HTTP protocol testing - Invalid UDN UUID"""
4680 class WPSAPHTTPServer_invalid_udn_uuid(WPSAPHTTPServer):
4681 def handle_upnp_info(self):
4682 self.wfile.write(gen_upnp_info(udn='uuid:foo'))
4683 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_udn_uuid)
4684
4685def test_ap_wps_er_http_proto_no_control_url(dev, apdev):
4686 """WPS ER HTTP protocol testing - no controlURL"""
4687 class WPSAPHTTPServer_no_control_url(WPSAPHTTPServer):
4688 def handle_upnp_info(self):
4689 self.wfile.write(gen_upnp_info(controlURL=None))
4690 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_control_url,
4691 no_event_url=True)
4692
4693def test_ap_wps_er_http_proto_control_url_dns(dev, apdev):
4694 """WPS ER HTTP protocol testing - DNS name in controlURL"""
4695 class WPSAPHTTPServer_control_url_dns(WPSAPHTTPServer):
4696 def handle_upnp_info(self):
4697 self.wfile.write(gen_upnp_info(controlURL='http://example.com/wps_control'))
4698 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_control_url_dns,
4699 no_event_url=True)
24b7f282
JM
4700
4701def test_ap_wps_http_timeout(dev, apdev):
4702 """WPS AP/ER and HTTP timeout"""
4703 try:
4704 _test_ap_wps_http_timeout(dev, apdev)
4705 finally:
4706 dev[0].request("WPS_ER_STOP")
4707
4708def _test_ap_wps_http_timeout(dev, apdev):
4709 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
4710 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
4711
4712 location = ssdp_get_location(ap_uuid)
4713 url = urlparse.urlparse(location)
4714 addr = (url.hostname, url.port)
4715 logger.debug("Open HTTP connection to hostapd, but do not complete request")
4716 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4717 socket.IPPROTO_TCP)
4718 sock.connect(addr)
4719 sock.send("G")
4720
4721 class DummyServer(SocketServer.StreamRequestHandler):
4722 def handle(self):
4723 logger.debug("DummyServer - start 31 sec wait")
4724 time.sleep(31)
4725 logger.debug("DummyServer - wait done")
4726
4727 logger.debug("Start WPS ER")
4728 server,sock2 = wps_er_start(dev[0], DummyServer, max_age=40,
4729 wait_m_search=True)
4730
4731 logger.debug("Start server to accept, but not complete, HTTP connection from WPS ER")
4732 # This will wait for 31 seconds..
4733 server.handle_request()
4734
4735 logger.debug("Complete HTTP connection with hostapd (that should have already closed the connection)")
4736 try:
4737 sock.send("ET / HTTP/1.1\r\n\r\n")
4738 res = sock.recv(100)
4739 sock.close()
4740 except:
4741 pass
4742
4743def test_ap_wps_er_url_parse(dev, apdev):
4744 """WPS ER and URL parsing special cases"""
4745 try:
4746 _test_ap_wps_er_url_parse(dev, apdev)
4747 finally:
4748 dev[0].request("WPS_ER_STOP")
4749
4750def _test_ap_wps_er_url_parse(dev, apdev):
4751 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4752 sock.settimeout(1)
4753 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4754 sock.bind(("239.255.255.250", 1900))
4755 dev[0].request("WPS_ER_START ifname=lo")
4756 (msg,addr) = sock.recvfrom(1000)
4757 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4758 if "M-SEARCH" not in msg:
4759 raise Exception("Not an M-SEARCH")
4760 sock.sendto("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)
4761 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4762 sock.sendto("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)
4763 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4764 sock.sendto("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)
4765 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4766
4767 sock.close()
4768
4769def test_ap_wps_er_link_update(dev, apdev):
4770 """WPS ER and link update special cases"""
4771 class WPSAPHTTPServer_link_update(WPSAPHTTPServer):
4772 def handle_upnp_info(self):
4773 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4774 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update)
4775
4776 class WPSAPHTTPServer_link_update2(WPSAPHTTPServer):
4777 def handle_others(self, data):
4778 if "GET / " in data:
4779 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4780 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update2,
4781 location_url='http://127.0.0.1:12345')
4782
4783def test_ap_wps_er_http_client(dev, apdev):
4784 """WPS ER and HTTP client special cases"""
4785 with alloc_fail(dev[0], 1, "http_link_update"):
4786 run_wps_er_proto_test(dev[0], WPSAPHTTPServer)
4787
4788 with alloc_fail(dev[0], 1, "wpabuf_alloc;http_client_url"):
4789 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4790
4791 with alloc_fail(dev[0], 1, "httpread_create;http_client_tx_ready"):
4792 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4793
4794 class WPSAPHTTPServer_req_as_resp(WPSAPHTTPServer):
4795 def handle_upnp_info(self):
4796 self.wfile.write("GET / HTTP/1.1\r\n\r\n")
4797 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_req_as_resp,
4798 no_event_url=True)
4799
4800def test_ap_wps_init_oom(dev, apdev):
4801 """wps_init OOM cases"""
4802 ssid = "test-wps"
4803 appin = "12345670"
4804 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4805 "ap_pin": appin }
4806 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4807 pin = dev[0].wps_read_pin()
4808
4809 with alloc_fail(hapd, 1, "wps_init"):
4810 hapd.request("WPS_PIN any " + pin)
4811 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4812 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4813 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4814 if ev is None:
4815 raise Exception("No EAP failure reported")
4816 dev[0].request("WPS_CANCEL")
4817
4818 with alloc_fail(dev[0], 2, "wps_init"):
4819 hapd.request("WPS_PIN any " + pin)
4820 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4821 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4822 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4823 if ev is None:
4824 raise Exception("No EAP failure reported")
4825 dev[0].request("WPS_CANCEL")
4826
4827 with alloc_fail(dev[0], 2, "wps_init"):
4828 hapd.request("WPS_PBC")
4829 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4830 dev[0].request("WPS_PBC %s" % (apdev[0]['bssid']))
4831 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4832 if ev is None:
4833 raise Exception("No EAP failure reported")
4834 dev[0].request("WPS_CANCEL")
4835
4836 dev[0].dump_monitor()
4837 new_ssid = "wps-new-ssid"
4838 new_passphrase = "1234567890"
4839 with alloc_fail(dev[0], 3, "wps_init"):
4840 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
4841 new_passphrase, no_wait=True)
4842 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4843 if ev is None:
4844 raise Exception("No EAP failure reported")
4845
4846 dev[0].flush_scan_cache()
4847
4848def test_ap_wps_invalid_assoc_req_elem(dev, apdev):
4849 """WPS and invalid IE in Association Request frame"""
4850 ssid = "test-wps"
4851 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4852 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4853 pin = "12345670"
4854 hapd.request("WPS_PIN any " + pin)
4855 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4856 try:
4857 dev[0].request("VENDOR_ELEM_ADD 13 dd050050f20410")
4858 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4859 for i in range(5):
4860 ev = hapd.wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=10)
4861 if ev and "vendor=14122" in ev:
4862 break
4863 if ev is None or "vendor=14122" not in ev:
4864 raise Exception("EAP-WSC not started")
4865 dev[0].request("WPS_CANCEL")
4866 finally:
4867 dev[0].request("VENDOR_ELEM_REMOVE 13 *")
4868
4869def test_ap_wps_pbc_pin_mismatch(dev, apdev):
4870 """WPS PBC/PIN mismatch"""
4871 ssid = "test-wps"
4872 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4873 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4874 hapd.request("SET wps_version_number 0x10")
4875 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4876 hapd.request("WPS_PBC")
4877 pin = dev[0].wps_read_pin()
4878 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4879 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4880 if ev is None:
4881 raise Exception("Scan did not complete")
4882 dev[0].request("WPS_CANCEL")
4883
4884 hapd.request("WPS_CANCEL")
4885 dev[0].flush_scan_cache()
4886
4887def test_ap_wps_ie_invalid(dev, apdev):
4888 """WPS PIN attempt with AP that has invalid WSC IE"""
4889 ssid = "test-wps"
4890 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4891 "vendor_elements": "dd050050f20410" }
4892 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4893 params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
4894 hostapd.add_ap(apdev[1]['ifname'], params)
4895 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4896 pin = dev[0].wps_read_pin()
4897 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4898 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4899 if ev is None:
4900 raise Exception("Scan did not complete")
4901 dev[0].request("WPS_CANCEL")
4902
4903def test_ap_wps_scan_prio_order(dev, apdev):
4904 """WPS scan priority ordering"""
4905 ssid = "test-wps"
4906 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4907 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4908 params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
4909 hostapd.add_ap(apdev[1]['ifname'], params)
4910 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4911 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
4912 pin = dev[0].wps_read_pin()
4913 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4914 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4915 if ev is None:
4916 raise Exception("Scan did not complete")
4917 dev[0].request("WPS_CANCEL")
4918
4919def test_ap_wps_probe_req_ie_oom(dev, apdev):
4920 """WPS ProbeReq IE OOM"""
4921 ssid = "test-wps"
4922 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4923 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4924 pin = dev[0].wps_read_pin()
4925 hapd.request("WPS_PIN any " + pin)
4926 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4927 with alloc_fail(dev[0], 1, "wps_build_probe_req_ie"):
4928 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4929 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4930 if ev is None:
4931 raise Exception("Association not seen")
4932 dev[0].request("WPS_CANCEL")
4933
4934 with alloc_fail(dev[0], 1, "wps_ie_encapsulate"):
4935 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4936 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4937 if ev is None:
4938 raise Exception("Association not seen")
4939 dev[0].request("WPS_CANCEL")
4940
4941def test_ap_wps_assoc_req_ie_oom(dev, apdev):
4942 """WPS AssocReq IE OOM"""
4943 ssid = "test-wps"
4944 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4945 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4946 pin = dev[0].wps_read_pin()
4947 hapd.request("WPS_PIN any " + pin)
4948 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4949 with alloc_fail(dev[0], 1, "wps_build_assoc_req_ie"):
4950 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4951 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4952 if ev is None:
4953 raise Exception("Association not seen")
4954 dev[0].request("WPS_CANCEL")
4955
4956def test_ap_wps_assoc_resp_ie_oom(dev, apdev):
4957 """WPS AssocResp IE OOM"""
4958 ssid = "test-wps"
4959 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4960 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4961 pin = dev[0].wps_read_pin()
4962 hapd.request("WPS_PIN any " + pin)
4963 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4964 with alloc_fail(hapd, 1, "wps_build_assoc_resp_ie"):
4965 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4966 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4967 if ev is None:
4968 raise Exception("Association not seen")
4969 dev[0].request("WPS_CANCEL")
4970
4971def test_ap_wps_bss_info_errors(dev, apdev):
4972 """WPS BSS info errors"""
4973 params = { "ssid": "1",
4974 "vendor_elements": "dd0e0050f20410440001ff101100010a" }
4975 hostapd.add_ap(apdev[0]['ifname'], params)
4976 params = { 'ssid': "2", "vendor_elements": "dd050050f20410" }
4977 hostapd.add_ap(apdev[1]['ifname'], params)
4978 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4979 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
4980 bss = dev[0].get_bss(apdev[0]['bssid'])
4981 logger.info("BSS: " + str(bss))
4982 if "wps_state" in bss:
4983 raise Exception("Unexpected wps_state in BSS info")
4984 if 'wps_device_name' not in bss:
4985 raise Exception("No wps_device_name in BSS info")
4986 if bss['wps_device_name'] != '_':
4987 raise Exception("Unexpected wps_device_name value")
4988 bss = dev[0].get_bss(apdev[1]['bssid'])
4989 logger.info("BSS: " + str(bss))
4990
4991 with alloc_fail(dev[0], 1, "=wps_attr_text"):
4992 bss = dev[0].get_bss(apdev[0]['bssid'])
4993 logger.info("BSS(OOM): " + str(bss))
4994
4995def wps_run_pbc_fail_ap(apdev, dev, hapd):
4996 hapd.request("WPS_PBC")
4997 dev.scan_for_bss(apdev['bssid'], freq="2412")
4998 dev.request("WPS_PBC " + apdev['bssid'])
4999 ev = dev.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5000 if ev is None:
5001 raise Exception("No EAP failure reported")
5002 dev.request("WPS_CANCEL")
5003 dev.wait_disconnected()
5004 for i in range(5):
5005 try:
5006 dev.flush_scan_cache()
5007 break
5008 except Exception, e:
5009 if str(e).startswith("Failed to trigger scan"):
5010 # Try again
5011 time.sleep(1)
5012 else:
5013 raise
5014
5015def wps_run_pbc_fail(apdev, dev):
5016 hapd = wps_start_ap(apdev)
5017 wps_run_pbc_fail_ap(apdev, dev, hapd)
5018
5019def test_ap_wps_pk_oom(dev, apdev):
5020 """WPS and public key OOM"""
5021 with alloc_fail(dev[0], 1, "wps_build_public_key"):
5022 wps_run_pbc_fail(apdev[0], dev[0])
5023
5024def test_ap_wps_pk_oom_ap(dev, apdev):
5025 """WPS and public key OOM on AP"""
5026 hapd = wps_start_ap(apdev[0])
5027 with alloc_fail(hapd, 1, "wps_build_public_key"):
5028 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5029
5030def test_ap_wps_encr_oom_ap(dev, apdev):
5031 """WPS and encrypted settings decryption OOM on AP"""
5032 hapd = wps_start_ap(apdev[0])
5033 pin = dev[0].wps_read_pin()
5034 hapd.request("WPS_PIN any " + pin)
5035 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5036 with alloc_fail(hapd, 1, "wps_decrypt_encr_settings"):
5037 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
5038 ev = hapd.wait_event(["WPS-FAIL"], timeout=10)
5039 if ev is None:
5040 raise Exception("No WPS-FAIL reported")
5041 dev[0].request("WPS_CANCEL")
5042 dev[0].wait_disconnected()
5043
5044def test_ap_wps_encr_no_random_ap(dev, apdev):
5045 """WPS and no random data available for encryption on AP"""
5046 hapd = wps_start_ap(apdev[0])
5047 with fail_test(hapd, 1, "os_get_random;wps_build_encr_settings"):
5048 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5049
5050def test_ap_wps_e_hash_no_random_sta(dev, apdev):
5051 """WPS and no random data available for e-hash on STA"""
5052 with fail_test(dev[0], 1, "os_get_random;wps_build_e_hash"):
5053 wps_run_pbc_fail(apdev[0], dev[0])
5054
5055def test_ap_wps_m1_no_random(dev, apdev):
5056 """WPS and no random for M1 on STA"""
5057 with fail_test(dev[0], 1, "os_get_random;wps_build_m1"):
5058 wps_run_pbc_fail(apdev[0], dev[0])
5059
5060def test_ap_wps_m1_oom(dev, apdev):
5061 """WPS and OOM for M1 on STA"""
5062 with alloc_fail(dev[0], 1, "wps_build_m1"):
5063 wps_run_pbc_fail(apdev[0], dev[0])
5064
5065def test_ap_wps_m3_oom(dev, apdev):
5066 """WPS and OOM for M3 on STA"""
5067 with alloc_fail(dev[0], 1, "wps_build_m3"):
5068 wps_run_pbc_fail(apdev[0], dev[0])
5069
5070def test_ap_wps_m5_oom(dev, apdev):
5071 """WPS and OOM for M5 on STA"""
5072 hapd = wps_start_ap(apdev[0])
5073 hapd.request("WPS_PBC")
5074 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5075 for i in range(1, 3):
5076 with alloc_fail(dev[0], i, "wps_build_m5"):
5077 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5078 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5079 if ev is None:
5080 raise Exception("No EAP failure reported")
5081 dev[0].request("WPS_CANCEL")
5082 dev[0].wait_disconnected()
5083 dev[0].flush_scan_cache()
5084
5085def test_ap_wps_m5_no_random(dev, apdev):
5086 """WPS and no random for M5 on STA"""
5087 with fail_test(dev[0], 1,
5088 "os_get_random;wps_build_encr_settings;wps_build_m5"):
5089 wps_run_pbc_fail(apdev[0], dev[0])
5090
5091def test_ap_wps_m7_oom(dev, apdev):
5092 """WPS and OOM for M7 on STA"""
5093 hapd = wps_start_ap(apdev[0])
5094 hapd.request("WPS_PBC")
5095 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5096 for i in range(1, 3):
5097 with alloc_fail(dev[0], i, "wps_build_m7"):
5098 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5099 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5100 if ev is None:
5101 raise Exception("No EAP failure reported")
5102 dev[0].request("WPS_CANCEL")
5103 dev[0].wait_disconnected()
5104 dev[0].flush_scan_cache()
5105
5106def test_ap_wps_m7_no_random(dev, apdev):
5107 """WPS and no random for M7 on STA"""
5108 with fail_test(dev[0], 1,
5109 "os_get_random;wps_build_encr_settings;wps_build_m7"):
5110 wps_run_pbc_fail(apdev[0], dev[0])
5111
5112def test_ap_wps_wsc_done_oom(dev, apdev):
5113 """WPS and OOM for WSC_Done on STA"""
5114 with alloc_fail(dev[0], 1, "wps_build_wsc_done"):
5115 wps_run_pbc_fail(apdev[0], dev[0])
5116
5117def test_ap_wps_random_psk_fail(dev, apdev):
5118 """WPS and no random for PSK on AP"""
5119 ssid = "test-wps"
5120 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
5121 appin = "12345670"
5122 try:
5123 os.remove(pskfile)
5124 except:
5125 pass
5126
5127 try:
5128 with open(pskfile, "w") as f:
5129 f.write("# WPA PSKs\n")
5130
5131 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5132 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
5133 "rsn_pairwise": "CCMP", "ap_pin": appin,
5134 "wpa_psk_file": pskfile }
5135 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
5136
5137 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5138 with fail_test(hapd, 1, "os_get_random;wps_build_cred_network_key"):
5139 dev[0].request("WPS_REG " + apdev[0]['bssid'] + " " + appin)
5140 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5141 if ev is None:
5142 raise Exception("No EAP failure reported")
5143 dev[0].request("WPS_CANCEL")
5144 dev[0].wait_disconnected()
5145
5146 with fail_test(hapd, 1, "os_get_random;wps_build_cred"):
5147 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5148
5149 with alloc_fail(hapd, 1, "wps_build_cred"):
5150 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5151
5152 with alloc_fail(hapd, 2, "wps_build_cred"):
5153 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5154 finally:
5155 os.remove(pskfile)
5156
5157def wps_ext_eap_identity_req(dev, hapd, bssid):
5158 logger.debug("EAP-Identity/Request")
5159 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5160 if ev is None:
5161 raise Exception("Timeout on EAPOL-TX from hostapd")
5162 res = dev.request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
5163 if "OK" not in res:
5164 raise Exception("EAPOL_RX to wpa_supplicant failed")
5165
5166def wps_ext_eap_identity_resp(hapd, dev, addr):
5167 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
5168 if ev is None:
5169 raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
5170 res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
5171 if "OK" not in res:
5172 raise Exception("EAPOL_RX to hostapd failed")
5173
5174def wps_ext_eap_wsc(dst, src, src_addr, msg):
5175 logger.debug(msg)
5176 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5177 if ev is None:
5178 raise Exception("Timeout on EAPOL-TX")
5179 res = dst.request("EAPOL_RX " + src_addr + " " + ev.split(' ')[2])
5180 if "OK" not in res:
5181 raise Exception("EAPOL_RX failed")
5182
7511ead0 5183def wps_start_ext(apdev, dev, pbc=False, pin=None):
24b7f282
JM
5184 addr = dev.own_addr()
5185 bssid = apdev['bssid']
5186 ssid = "test-wps-conf"
5187 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5188 "wpa_passphrase": "12345678", "wpa": "2",
5189 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
5190 hapd = hostapd.add_ap(apdev['ifname'], params)
5191
d1883671
JM
5192 if pbc:
5193 hapd.request("WPS_PBC")
5194 else:
7511ead0
JM
5195 if pin is None:
5196 pin = dev.wps_read_pin()
d1883671 5197 hapd.request("WPS_PIN any " + pin)
24b7f282
JM
5198 dev.scan_for_bss(bssid, freq="2412")
5199 hapd.request("SET ext_eapol_frame_io 1")
5200 dev.request("SET ext_eapol_frame_io 1")
5201
d1883671
JM
5202 if pbc:
5203 dev.request("WPS_PBC " + bssid)
5204 else:
5205 dev.request("WPS_PIN " + bssid + " " + pin)
24b7f282
JM
5206 return addr,bssid,hapd
5207
5208def wps_auth_corrupt(dst, src, addr):
5209 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5210 if ev is None:
5211 raise Exception("Timeout on EAPOL-TX")
5212 src.request("SET ext_eapol_frame_io 0")
5213 dst.request("SET ext_eapol_frame_io 0")
5214 msg = ev.split(' ')[2]
5215 if msg[-24:-16] != '10050008':
5216 raise Exception("Could not find Authenticator attribute")
5217 # Corrupt Authenticator value
5218 msg = msg[:-1] + '%x' % ((int(msg[-1], 16) + 1) % 16)
5219 res = dst.request("EAPOL_RX " + addr + " " + msg)
5220 if "OK" not in res:
5221 raise Exception("EAPOL_RX failed")
5222
5223def wps_fail_finish(hapd, dev, fail_str):
5224 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5225 if ev is None:
5226 raise Exception("WPS-FAIL not indicated")
5227 if fail_str not in ev:
5228 raise Exception("Unexpected WPS-FAIL value: " + ev)
5229 dev.request("WPS_CANCEL")
5230 dev.wait_disconnected()
5231
5232def wps_auth_corrupt_from_ap(dev, hapd, bssid, fail_str):
5233 wps_auth_corrupt(dev, hapd, bssid)
5234 wps_fail_finish(hapd, dev, fail_str)
5235
5236def wps_auth_corrupt_to_ap(dev, hapd, addr, fail_str):
5237 wps_auth_corrupt(hapd, dev, addr)
5238 wps_fail_finish(hapd, dev, fail_str)
5239
5240def test_ap_wps_authenticator_mismatch_m2(dev, apdev):
5241 """WPS and Authenticator attribute mismatch in M2"""
5242 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5243 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5244 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5245 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5246 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5247 logger.debug("M2")
5248 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=5")
5249
5250def test_ap_wps_authenticator_mismatch_m3(dev, apdev):
5251 """WPS and Authenticator attribute mismatch in M3"""
5252 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5253 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5254 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5255 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5256 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5257 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5258 logger.debug("M3")
5259 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=7")
5260
5261def test_ap_wps_authenticator_mismatch_m4(dev, apdev):
5262 """WPS and Authenticator attribute mismatch in M4"""
5263 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5264 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5265 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5266 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5267 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5268 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5269 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5270 logger.debug("M4")
5271 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=8")
5272
5273def test_ap_wps_authenticator_mismatch_m5(dev, apdev):
5274 """WPS and Authenticator attribute mismatch in M5"""
5275 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5276 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5277 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5278 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5279 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5280 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5281 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5282 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5283 logger.debug("M5")
5284 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=9")
5285
5286def test_ap_wps_authenticator_mismatch_m6(dev, apdev):
5287 """WPS and Authenticator attribute mismatch in M6"""
5288 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5289 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5290 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5291 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5292 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5293 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5294 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5295 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5296 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5297 logger.debug("M6")
5298 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=10")
5299
5300def test_ap_wps_authenticator_mismatch_m7(dev, apdev):
5301 """WPS and Authenticator attribute mismatch in M7"""
5302 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5303 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5304 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5305 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5306 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5307 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5308 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5309 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5310 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5311 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5312 logger.debug("M7")
5313 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=11")
5314
5315def test_ap_wps_authenticator_mismatch_m8(dev, apdev):
5316 """WPS and Authenticator attribute mismatch in M8"""
5317 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5318 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5319 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5320 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5321 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5322 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5323 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5324 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5325 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5326 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5327 wps_ext_eap_wsc(hapd, dev[0], addr, "M7")
5328 logger.debug("M8")
5329 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=12")
5330
5331def test_ap_wps_authenticator_missing_m2(dev, apdev):
5332 """WPS and Authenticator attribute missing from M2"""
5333 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5334 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5335 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5336 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5337 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5338 logger.debug("M2")
5339 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5340 if ev is None:
5341 raise Exception("Timeout on EAPOL-TX")
5342 hapd.request("SET ext_eapol_frame_io 0")
5343 dev[0].request("SET ext_eapol_frame_io 0")
5344 msg = ev.split(' ')[2]
5345 if msg[-24:-16] != '10050008':
5346 raise Exception("Could not find Authenticator attribute")
5347 # Remove Authenticator value
5348 msg = msg[:-24]
5349 mlen = "%04x" % (int(msg[4:8], 16) - 12)
5350 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:]
5351 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5352 if "OK" not in res:
5353 raise Exception("EAPOL_RX failed")
5354 wps_fail_finish(hapd, dev[0], "msg=5")
5355
d1883671
JM
5356def test_ap_wps_m2_dev_passwd_id_p2p(dev, apdev):
5357 """WPS and M2 with different Device Password ID (P2P)"""
5358 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5359 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5360 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5361 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5362 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5363 logger.debug("M2")
5364 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5365 if ev is None:
5366 raise Exception("Timeout on EAPOL-TX")
5367 hapd.request("SET ext_eapol_frame_io 0")
5368 dev[0].request("SET ext_eapol_frame_io 0")
5369 msg = ev.split(' ')[2]
5370 if msg[722:730] != '10120002':
5371 raise Exception("Could not find Device Password ID attribute")
5372 # Replace Device Password ID value. This will fail Authenticator check, but
5373 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5374 # log.
5375 msg = msg[0:730] + "0005" + msg[734:]
5376 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5377 if "OK" not in res:
5378 raise Exception("EAPOL_RX failed")
5379 wps_fail_finish(hapd, dev[0], "msg=5")
5380
5381def test_ap_wps_m2_dev_passwd_id_change_pin_to_pbc(dev, apdev):
5382 """WPS and M2 with different Device Password ID (PIN to PBC)"""
5383 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5384 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5385 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5386 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5387 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5388 logger.debug("M2")
5389 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5390 if ev is None:
5391 raise Exception("Timeout on EAPOL-TX")
5392 hapd.request("SET ext_eapol_frame_io 0")
5393 dev[0].request("SET ext_eapol_frame_io 0")
5394 msg = ev.split(' ')[2]
5395 if msg[722:730] != '10120002':
5396 raise Exception("Could not find Device Password ID attribute")
5397 # Replace Device Password ID value (PIN --> PBC). This will be rejected.
5398 msg = msg[0:730] + "0004" + msg[734:]
5399 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5400 if "OK" not in res:
5401 raise Exception("EAPOL_RX failed")
5402 wps_fail_finish(hapd, dev[0], "msg=5")
5403
5404def test_ap_wps_m2_dev_passwd_id_change_pbc_to_pin(dev, apdev):
5405 """WPS and M2 with different Device Password ID (PBC to PIN)"""
5406 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5407 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5408 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5409 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5410 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5411 logger.debug("M2")
5412 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5413 if ev is None:
5414 raise Exception("Timeout on EAPOL-TX")
5415 hapd.request("SET ext_eapol_frame_io 0")
5416 dev[0].request("SET ext_eapol_frame_io 0")
5417 msg = ev.split(' ')[2]
5418 if msg[722:730] != '10120002':
5419 raise Exception("Could not find Device Password ID attribute")
5420 # Replace Device Password ID value. This will fail Authenticator check, but
5421 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5422 # log.
5423 msg = msg[0:730] + "0000" + msg[734:]
5424 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5425 if "OK" not in res:
5426 raise Exception("EAPOL_RX failed")
5427 wps_fail_finish(hapd, dev[0], "msg=5")
5428 dev[0].flush_scan_cache()
5429
5430def test_ap_wps_m2_missing_dev_passwd_id(dev, apdev):
5431 """WPS and M2 without Device Password ID"""
5432 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5433 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5434 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5435 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5436 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5437 logger.debug("M2")
5438 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5439 if ev is None:
5440 raise Exception("Timeout on EAPOL-TX")
5441 hapd.request("SET ext_eapol_frame_io 0")
5442 dev[0].request("SET ext_eapol_frame_io 0")
5443 msg = ev.split(' ')[2]
5444 if msg[722:730] != '10120002':
5445 raise Exception("Could not find Device Password ID attribute")
5446 # Remove Device Password ID value. This will fail Authenticator check, but
5447 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5448 # log.
5449 mlen = "%04x" % (int(msg[4:8], 16) - 6)
5450 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:722] + msg[734:]
5451 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5452 if "OK" not in res:
5453 raise Exception("EAPOL_RX failed")
5454 wps_fail_finish(hapd, dev[0], "msg=5")
5455
5456def test_ap_wps_m2_missing_registrar_nonce(dev, apdev):
5457 """WPS and M2 without Registrar Nonce"""
5458 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5459 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5460 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5461 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5462 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5463 logger.debug("M2")
5464 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5465 if ev is None:
5466 raise Exception("Timeout on EAPOL-TX")
5467 hapd.request("SET ext_eapol_frame_io 0")
5468 dev[0].request("SET ext_eapol_frame_io 0")
5469 msg = ev.split(' ')[2]
5470 if msg[96:104] != '10390010':
5471 raise Exception("Could not find Registrar Nonce attribute")
5472 # Remove Registrar Nonce. This will fail Authenticator check, but
5473 # allows the code path in wps_process_registrar_nonce() to be checked from
5474 # the debug log.
5475 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5476 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:96] + msg[136:]
5477 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5478 if "OK" not in res:
5479 raise Exception("EAPOL_RX failed")
5480 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5481 if ev is None:
5482 raise Exception("Disconnect event not seen")
5483 dev[0].request("WPS_CANCEL")
5484 dev[0].flush_scan_cache()
5485
5486def test_ap_wps_m2_missing_enrollee_nonce(dev, apdev):
5487 """WPS and M2 without Enrollee Nonce"""
5488 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5489 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5490 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5491 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5492 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5493 logger.debug("M2")
5494 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5495 if ev is None:
5496 raise Exception("Timeout on EAPOL-TX")
5497 hapd.request("SET ext_eapol_frame_io 0")
5498 dev[0].request("SET ext_eapol_frame_io 0")
5499 msg = ev.split(' ')[2]
5500 if msg[56:64] != '101a0010':
5501 raise Exception("Could not find enrollee Nonce attribute")
5502 # Remove Enrollee Nonce. This will fail Authenticator check, but
5503 # allows the code path in wps_process_enrollee_nonce() to be checked from
5504 # the debug log.
5505 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5506 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:56] + msg[96:]
5507 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5508 if "OK" not in res:
5509 raise Exception("EAPOL_RX failed")
5510 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5511 if ev is None:
5512 raise Exception("Disconnect event not seen")
5513 dev[0].request("WPS_CANCEL")
5514 dev[0].flush_scan_cache()
5515
5516def test_ap_wps_m2_missing_uuid_r(dev, apdev):
5517 """WPS and M2 without UUID-R"""
5518 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5519 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5520 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5521 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5522 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5523 logger.debug("M2")
5524 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5525 if ev is None:
5526 raise Exception("Timeout on EAPOL-TX")
5527 hapd.request("SET ext_eapol_frame_io 0")
5528 dev[0].request("SET ext_eapol_frame_io 0")
5529 msg = ev.split(' ')[2]
5530 if msg[136:144] != '10480010':
5531 raise Exception("Could not find enrollee Nonce attribute")
5532 # Remove UUID-R. This will fail Authenticator check, but allows the code
5533 # path in wps_process_uuid_r() to be checked from the debug log.
5534 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5535 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:136] + msg[176:]
5536 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5537 if "OK" not in res:
5538 raise Exception("EAPOL_RX failed")
5539 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5540 if ev is None:
5541 raise Exception("Disconnect event not seen")
5542 dev[0].request("WPS_CANCEL")
5543 dev[0].flush_scan_cache()
5544
5545def test_ap_wps_m2_invalid(dev, apdev):
5546 """WPS and M2 parsing failure"""
5547 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5548 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5549 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5550 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5551 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5552 logger.debug("M2")
5553 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5554 if ev is None:
5555 raise Exception("Timeout on EAPOL-TX")
5556 hapd.request("SET ext_eapol_frame_io 0")
5557 dev[0].request("SET ext_eapol_frame_io 0")
5558 msg = ev.split(' ')[2]
5559 if msg[136:144] != '10480010':
5560 raise Exception("Could not find enrollee Nonce attribute")
5561 # Remove UUID-R. This will fail Authenticator check, but allows the code
5562 # path in wps_process_uuid_r() to be checked from the debug log.
5563 mlen = "%04x" % (int(msg[4:8], 16) - 1)
5564 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:-2]
5565 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5566 if "OK" not in res:
5567 raise Exception("EAPOL_RX failed")
5568 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5569 if ev is None:
5570 raise Exception("Disconnect event not seen")
5571 dev[0].request("WPS_CANCEL")
5572 dev[0].flush_scan_cache()
5573
5574def test_ap_wps_m2_missing_msg_type(dev, apdev):
5575 """WPS and M2 without Message Type"""
5576 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5577 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5578 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5579 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5580 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5581 logger.debug("M2")
5582 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5583 if ev is None:
5584 raise Exception("Timeout on EAPOL-TX")
5585 hapd.request("SET ext_eapol_frame_io 0")
5586 dev[0].request("SET ext_eapol_frame_io 0")
5587 msg = ev.split(' ')[2]
5588 if msg[46:54] != '10220001':
5589 raise Exception("Could not find Message Type attribute")
5590 # Remove Message Type. This will fail Authenticator check, but allows the
5591 # code path in wps_process_wsc_msg() to be checked from the debug log.
5592 mlen = "%04x" % (int(msg[4:8], 16) - 5)
5593 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:46] + msg[56:]
5594 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5595 if "OK" not in res:
5596 raise Exception("EAPOL_RX failed")
5597 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5598 if ev is None:
5599 raise Exception("Disconnect event not seen")
5600 dev[0].request("WPS_CANCEL")
5601 dev[0].flush_scan_cache()
5602
5603def test_ap_wps_m2_unknown_msg_type(dev, apdev):
5604 """WPS and M2 but unknown Message Type"""
5605 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5606 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5607 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5608 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5609 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5610 logger.debug("M2")
5611 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5612 if ev is None:
5613 raise Exception("Timeout on EAPOL-TX")
5614 hapd.request("SET ext_eapol_frame_io 0")
5615 dev[0].request("SET ext_eapol_frame_io 0")
5616 msg = ev.split(' ')[2]
5617 if msg[46:54] != '10220001':
5618 raise Exception("Could not find Message Type attribute")
5619 # Replace Message Type value. This will be rejected.
5620 msg = msg[0:54] + "00" + msg[56:]
5621 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5622 if "OK" not in res:
5623 raise Exception("EAPOL_RX failed")
5624 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5625 if ev is None:
5626 raise Exception("Disconnect event not seen")
5627 dev[0].request("WPS_CANCEL")
5628 dev[0].flush_scan_cache()
5629
5630def test_ap_wps_m2_unknown_opcode(dev, apdev):
5631 """WPS and M2 but unknown opcode"""
5632 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5633 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5634 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5635 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5636 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5637 logger.debug("M2")
5638 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5639 if ev is None:
5640 raise Exception("Timeout on EAPOL-TX")
5641 hapd.request("SET ext_eapol_frame_io 0")
5642 dev[0].request("SET ext_eapol_frame_io 0")
5643 msg = ev.split(' ')[2]
5644 # Replace opcode. This will be discarded in EAP-WSC processing.
5645 msg = msg[0:32] + "00" + msg[34:]
5646 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5647 if "OK" not in res:
5648 raise Exception("EAPOL_RX failed")
5649 dev[0].request("WPS_CANCEL")
5650 dev[0].wait_disconnected()
5651 dev[0].flush_scan_cache()
5652
5653def test_ap_wps_m2_unknown_opcode2(dev, apdev):
5654 """WPS and M2 but unknown opcode (WSC_Start)"""
5655 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5656 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5657 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5658 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5659 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5660 logger.debug("M2")
5661 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5662 if ev is None:
5663 raise Exception("Timeout on EAPOL-TX")
5664 hapd.request("SET ext_eapol_frame_io 0")
5665 dev[0].request("SET ext_eapol_frame_io 0")
5666 msg = ev.split(' ')[2]
5667 # Replace opcode. This will be discarded in EAP-WSC processing.
5668 msg = msg[0:32] + "01" + msg[34:]
5669 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5670 if "OK" not in res:
5671 raise Exception("EAPOL_RX failed")
5672 dev[0].request("WPS_CANCEL")
5673 dev[0].wait_disconnected()
5674 dev[0].flush_scan_cache()
5675
5676def test_ap_wps_m2_unknown_opcode3(dev, apdev):
5677 """WPS and M2 but unknown opcode (WSC_Done)"""
5678 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5679 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5680 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5681 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5682 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5683 logger.debug("M2")
5684 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5685 if ev is None:
5686 raise Exception("Timeout on EAPOL-TX")
5687 hapd.request("SET ext_eapol_frame_io 0")
5688 dev[0].request("SET ext_eapol_frame_io 0")
5689 msg = ev.split(' ')[2]
5690 # Replace opcode. This will be discarded in WPS Enrollee processing.
5691 msg = msg[0:32] + "05" + msg[34:]
5692 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5693 if "OK" not in res:
5694 raise Exception("EAPOL_RX failed")
5695 dev[0].request("WPS_CANCEL")
5696 dev[0].wait_disconnected()
5697 dev[0].flush_scan_cache()
5698
5699def wps_m2_but_other(dev, apdev, title, msgtype):
5700 addr,bssid,hapd = wps_start_ext(apdev, dev)
5701 wps_ext_eap_identity_req(dev, hapd, bssid)
5702 wps_ext_eap_identity_resp(hapd, dev, addr)
5703 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5704 wps_ext_eap_wsc(hapd, dev, addr, "M1")
5705 logger.debug(title)
5706 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5707 if ev is None:
5708 raise Exception("Timeout on EAPOL-TX")
5709 hapd.request("SET ext_eapol_frame_io 0")
5710 dev.request("SET ext_eapol_frame_io 0")
5711 msg = ev.split(' ')[2]
5712 if msg[46:54] != '10220001':
5713 raise Exception("Could not find Message Type attribute")
5714 # Replace Message Type value. This will be rejected.
5715 msg = msg[0:54] + msgtype + msg[56:]
5716 res = dev.request("EAPOL_RX " + bssid + " " + msg)
5717 if "OK" not in res:
5718 raise Exception("EAPOL_RX failed")
5719 ev = dev.wait_event(["WPS-FAIL"], timeout=5)
5720 if ev is None:
5721 raise Exception("WPS-FAIL event not seen")
5722 dev.request("WPS_CANCEL")
5723 dev.wait_disconnected()
5724
5725def wps_m4_but_other(dev, apdev, title, msgtype):
5726 addr,bssid,hapd = wps_start_ext(apdev, dev)
5727 wps_ext_eap_identity_req(dev, hapd, bssid)
5728 wps_ext_eap_identity_resp(hapd, dev, addr)
5729 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5730 wps_ext_eap_wsc(hapd, dev, addr, "M1")
5731 wps_ext_eap_wsc(dev, hapd, bssid, "M2")
5732 wps_ext_eap_wsc(hapd, dev, addr, "M3")
5733 logger.debug(title)
5734 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5735 if ev is None:
5736 raise Exception("Timeout on EAPOL-TX")
5737 hapd.request("SET ext_eapol_frame_io 0")
5738 dev.request("SET ext_eapol_frame_io 0")
5739 msg = ev.split(' ')[2]
5740 if msg[46:54] != '10220001':
5741 raise Exception("Could not find Message Type attribute")
5742 # Replace Message Type value. This will be rejected.
5743 msg = msg[0:54] + msgtype + msg[56:]
5744 res = dev.request("EAPOL_RX " + bssid + " " + msg)
5745 if "OK" not in res:
5746 raise Exception("EAPOL_RX failed")
5747 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5748 if ev is None:
5749 raise Exception("WPS-FAIL event not seen")
5750 dev.request("WPS_CANCEL")
5751 dev.wait_disconnected()
5752
5753def test_ap_wps_m2_msg_type_m4(dev, apdev):
5754 """WPS and M2 but Message Type M4"""
5755 wps_m2_but_other(dev[0], apdev[0], "M2/M4", "08")
5756
5757def test_ap_wps_m2_msg_type_m6(dev, apdev):
5758 """WPS and M2 but Message Type M6"""
5759 wps_m2_but_other(dev[0], apdev[0], "M2/M6", "0a")
5760
5761def test_ap_wps_m2_msg_type_m8(dev, apdev):
5762 """WPS and M2 but Message Type M8"""
5763 wps_m2_but_other(dev[0], apdev[0], "M2/M8", "0c")
5764
5765def test_ap_wps_m4_msg_type_m2(dev, apdev):
5766 """WPS and M4 but Message Type M2"""
5767 wps_m4_but_other(dev[0], apdev[0], "M4/M2", "05")
5768
5769def test_ap_wps_m4_msg_type_m2d(dev, apdev):
5770 """WPS and M4 but Message Type M2D"""
5771 wps_m4_but_other(dev[0], apdev[0], "M4/M2D", "06")
5772
24b7f282
JM
5773def test_ap_wps_config_methods(dev, apdev):
5774 """WPS configuration method parsing"""
5775 ssid = "test-wps-conf"
5776 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5777 "wpa_passphrase": "12345678", "wpa": "2",
5778 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5779 "config_methods": "ethernet display ext_nfc_token int_nfc_token physical_display physical_push_button" }
5780 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
5781 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5782 "wpa_passphrase": "12345678", "wpa": "2",
5783 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5784 "config_methods": "display push_button" }
5785 hapd2 = hostapd.add_ap(apdev[1]['ifname'], params)
476daa05
JM
5786
5787def test_ap_wps_set_selected_registrar_proto(dev, apdev):
5788 """WPS UPnP SetSelectedRegistrar protocol testing"""
5789 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
5790 hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
5791
5792 location = ssdp_get_location(ap_uuid)
5793 urls = upnp_get_urls(location)
5794 eventurl = urlparse.urlparse(urls['event_sub_url'])
5795 ctrlurl = urlparse.urlparse(urls['control_url'])
5796 url = urlparse.urlparse(location)
5797 conn = httplib.HTTPConnection(url.netloc)
5798
5799 class WPSERHTTPServer(SocketServer.StreamRequestHandler):
5800 def handle(self):
5801 data = self.rfile.readline().strip()
5802 logger.debug(data)
5803 self.wfile.write(gen_wps_event())
5804
5805 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
5806 server.timeout = 1
5807
5808 headers = { "callback": '<http://127.0.0.1:12345/event>',
5809 "NT": "upnp:event",
5810 "timeout": "Second-1234" }
5811 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
5812 resp = conn.getresponse()
5813 if resp.status != 200:
5814 raise Exception("Unexpected HTTP response: %d" % resp.status)
5815 sid = resp.getheader("sid")
5816 logger.debug("Subscription SID " + sid)
5817 server.handle_request()
5818
5819 tests = [ (500, "10"),
5820 (200, "104a000110" + "1041000101" + "101200020000" +
5821 "105300023148" +
5822 "1049002c00372a0001200124111111111111222222222222333333333333444444444444555555555555666666666666" +
5823 "10480010362db47ba53a519188fb5458b986b2e4"),
5824 (200, "104a000110" + "1041000100" + "101200020000" +
5825 "105300020000"),
5826 (200, "104a000110" + "1041000100"),
5827 (200, "104a000110") ]
5828 for status,test in tests:
5829 tlvs = binascii.unhexlify(test)
5830 newmsg = base64.b64encode(tlvs)
5831 msg = '<?xml version="1.0"?>\n'
5832 msg += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
5833 msg += '<s:Body>'
5834 msg += '<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">'
5835 msg += '<NewMessage>'
5836 msg += newmsg
5837 msg += "</NewMessage></u:SetSelectedRegistrar></s:Body></s:Envelope>"
5838 headers = { "Content-type": 'text/xml; charset="utf-8"' }
5839 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
5840 conn.request("POST", ctrlurl.path, msg, headers)
5841 resp = conn.getresponse()
5842 if resp.status != status:
5843 raise Exception("Unexpected HTTP response: %d (expected %d)" % (resp.status, status))
96038a5f
JM
5844
5845def test_ap_wps_adv_oom(dev, apdev):
5846 """WPS AP and advertisement OOM"""
5847 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
5848 hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
5849
5850 with alloc_fail(hapd, 1, "=msearchreply_state_machine_start"):
5851 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
5852 no_recv=True)
5853 time.sleep(0.2)
5854
5855 with alloc_fail(hapd, 1, "eloop_register_timeout;msearchreply_state_machine_start"):
5856 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
5857 no_recv=True)
5858 time.sleep(0.2)
5859
5860 with alloc_fail(hapd, 1,
5861 "next_advertisement;advertisement_state_machine_stop"):
5862 hapd.disable()
5863
5864 with alloc_fail(hapd, 1, "ssdp_listener_start"):
5865 if "FAIL" not in hapd.request("ENABLE"):
5866 raise Exception("ENABLE succeeded during OOM")
926404a6
JM
5867
5868def test_wps_config_methods(dev):
5869 """WPS config method update"""
5870 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
5871 wpas.interface_add("wlan5")
5872 if "OK" not in wpas.request("SET config_methods display label"):
5873 raise Exception("Failed to set config_methods")
5874 if wpas.request("GET config_methods").strip() != "display label":
5875 raise Exception("config_methods were not updated")
5876 if "OK" not in wpas.request("SET config_methods "):
5877 raise Exception("Failed to clear config_methods")
5878 if wpas.request("GET config_methods").strip() != "":
5879 raise Exception("config_methods were not cleared")
7511ead0
JM
5880
5881WPS_VENDOR_ID_WFA = 14122
5882WPS_VENDOR_TYPE = 1
5883
5884# EAP-WSC Op-Code values
5885WSC_Start = 0x01
5886WSC_ACK = 0x02
5887WSC_NACK = 0x03
5888WSC_MSG = 0x04
5889WSC_Done = 0x05
5890WSC_FRAG_ACK = 0x06
5891
5892ATTR_AP_CHANNEL = 0x1001
5893ATTR_ASSOC_STATE = 0x1002
5894ATTR_AUTH_TYPE = 0x1003
5895ATTR_AUTH_TYPE_FLAGS = 0x1004
5896ATTR_AUTHENTICATOR = 0x1005
5897ATTR_CONFIG_METHODS = 0x1008
5898ATTR_CONFIG_ERROR = 0x1009
5899ATTR_CONFIRM_URL4 = 0x100a
5900ATTR_CONFIRM_URL6 = 0x100b
5901ATTR_CONN_TYPE = 0x100c
5902ATTR_CONN_TYPE_FLAGS = 0x100d
5903ATTR_CRED = 0x100e
5904ATTR_ENCR_TYPE = 0x100f
5905ATTR_ENCR_TYPE_FLAGS = 0x1010
5906ATTR_DEV_NAME = 0x1011
5907ATTR_DEV_PASSWORD_ID = 0x1012
5908ATTR_E_HASH1 = 0x1014
5909ATTR_E_HASH2 = 0x1015
5910ATTR_E_SNONCE1 = 0x1016
5911ATTR_E_SNONCE2 = 0x1017
5912ATTR_ENCR_SETTINGS = 0x1018
5913ATTR_ENROLLEE_NONCE = 0x101a
5914ATTR_FEATURE_ID = 0x101b
5915ATTR_IDENTITY = 0x101c
5916ATTR_IDENTITY_PROOF = 0x101d
5917ATTR_KEY_WRAP_AUTH = 0x101e
5918ATTR_KEY_ID = 0x101f
5919ATTR_MAC_ADDR = 0x1020
5920ATTR_MANUFACTURER = 0x1021
5921ATTR_MSG_TYPE = 0x1022
5922ATTR_MODEL_NAME = 0x1023
5923ATTR_MODEL_NUMBER = 0x1024
5924ATTR_NETWORK_INDEX = 0x1026
5925ATTR_NETWORK_KEY = 0x1027
5926ATTR_NETWORK_KEY_INDEX = 0x1028
5927ATTR_NEW_DEVICE_NAME = 0x1029
5928ATTR_NEW_PASSWORD = 0x102a
5929ATTR_OOB_DEVICE_PASSWORD = 0x102c
5930ATTR_OS_VERSION = 0x102d
5931ATTR_POWER_LEVEL = 0x102f
5932ATTR_PSK_CURRENT = 0x1030
5933ATTR_PSK_MAX = 0x1031
5934ATTR_PUBLIC_KEY = 0x1032
5935ATTR_RADIO_ENABLE = 0x1033
5936ATTR_REBOOT = 0x1034
5937ATTR_REGISTRAR_CURRENT = 0x1035
5938ATTR_REGISTRAR_ESTABLISHED = 0x1036
5939ATTR_REGISTRAR_LIST = 0x1037
5940ATTR_REGISTRAR_MAX = 0x1038
5941ATTR_REGISTRAR_NONCE = 0x1039
5942ATTR_REQUEST_TYPE = 0x103a
5943ATTR_RESPONSE_TYPE = 0x103b
5944ATTR_RF_BANDS = 0x103c
5945ATTR_R_HASH1 = 0x103d
5946ATTR_R_HASH2 = 0x103e
5947ATTR_R_SNONCE1 = 0x103f
5948ATTR_R_SNONCE2 = 0x1040
5949ATTR_SELECTED_REGISTRAR = 0x1041
5950ATTR_SERIAL_NUMBER = 0x1042
5951ATTR_WPS_STATE = 0x1044
5952ATTR_SSID = 0x1045
5953ATTR_TOTAL_NETWORKS = 0x1046
5954ATTR_UUID_E = 0x1047
5955ATTR_UUID_R = 0x1048
5956ATTR_VENDOR_EXT = 0x1049
5957ATTR_VERSION = 0x104a
5958ATTR_X509_CERT_REQ = 0x104b
5959ATTR_X509_CERT = 0x104c
5960ATTR_EAP_IDENTITY = 0x104d
5961ATTR_MSG_COUNTER = 0x104e
5962ATTR_PUBKEY_HASH = 0x104f
5963ATTR_REKEY_KEY = 0x1050
5964ATTR_KEY_LIFETIME = 0x1051
5965ATTR_PERMITTED_CFG_METHODS = 0x1052
5966ATTR_SELECTED_REGISTRAR_CONFIG_METHODS = 0x1053
5967ATTR_PRIMARY_DEV_TYPE = 0x1054
5968ATTR_SECONDARY_DEV_TYPE_LIST = 0x1055
5969ATTR_PORTABLE_DEV = 0x1056
5970ATTR_AP_SETUP_LOCKED = 0x1057
5971ATTR_APPLICATION_EXT = 0x1058
5972ATTR_EAP_TYPE = 0x1059
5973ATTR_IV = 0x1060
5974ATTR_KEY_PROVIDED_AUTO = 0x1061
5975ATTR_802_1X_ENABLED = 0x1062
5976ATTR_APPSESSIONKEY = 0x1063
5977ATTR_WEPTRANSMITKEY = 0x1064
5978ATTR_REQUESTED_DEV_TYPE = 0x106a
5979
5980# Message Type
5981WPS_Beacon = 0x01
5982WPS_ProbeRequest = 0x02
5983WPS_ProbeResponse = 0x03
5984WPS_M1 = 0x04
5985WPS_M2 = 0x05
5986WPS_M2D = 0x06
5987WPS_M3 = 0x07
5988WPS_M4 = 0x08
5989WPS_M5 = 0x09
5990WPS_M6 = 0x0a
5991WPS_M7 = 0x0b
5992WPS_M8 = 0x0c
5993WPS_WSC_ACK = 0x0d
5994WPS_WSC_NACK = 0x0e
5995WPS_WSC_DONE = 0x0f
5996
5997def get_wsc_msg(dev):
5998 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
5999 if ev is None:
6000 raise Exception("Timeout on EAPOL-TX")
6001 data = binascii.unhexlify(ev.split(' ')[2])
6002 msg = {}
6003
6004 # Parse EAPOL header
6005 if len(data) < 4:
6006 raise Exception("No room for EAPOL header")
6007 version,type,length = struct.unpack('>BBH', data[0:4])
6008 msg['eapol_version'] = version
6009 msg['eapol_type'] = type
6010 msg['eapol_length'] = length
6011 data = data[4:]
6012 if length != len(data):
6013 raise Exception("EAPOL header length mismatch (%d != %d)" % (length, len(data)))
6014 if type != 0:
6015 raise Exception("Unexpected EAPOL header type: %d" % type)
6016
6017 # Parse EAP header
6018 if len(data) < 4:
6019 raise Exception("No room for EAP header")
6020 code,identifier,length = struct.unpack('>BBH', data[0:4])
6021 msg['eap_code'] = code
6022 msg['eap_identifier'] = identifier
6023 msg['eap_length'] = length
6024 data = data[4:]
6025 if msg['eapol_length'] != msg['eap_length']:
6026 raise Exception("EAP header length mismatch (%d != %d)" % (msg['eapol_length'], length))
6027
6028 # Parse EAP expanded header
6029 if len(data) < 1:
6030 raise Exception("No EAP type included")
6031 msg['eap_type'], = struct.unpack('B', data[0])
6032 data = data[1:]
6033
6034 if msg['eap_type'] == 254:
6035 if len(data) < 3 + 4:
6036 raise Exception("Truncated EAP expanded header")
6037 msg['eap_vendor_id'], msg['eap_vendor_type'] = struct.unpack('>LL', '\0' + data[0:7])
6038 data = data[7:]
6039 else:
6040 raise Exception("Unexpected EAP type")
6041
6042 if msg['eap_vendor_id'] != WPS_VENDOR_ID_WFA:
6043 raise Exception("Unexpected Vendor-Id")
6044 if msg['eap_vendor_type'] != WPS_VENDOR_TYPE:
6045 raise Exception("Unexpected Vendor-Type")
6046
6047 # Parse EAP-WSC header
6048 if len(data) < 2:
6049 raise Exception("Truncated EAP-WSC header")
6050 msg['wsc_opcode'], msg['wsc_flags'] = struct.unpack('BB', data[0:2])
6051 data = data[2:]
6052
6053 # Parse WSC attributes
6054 msg['raw_attrs'] = data
6055 attrs = {}
6056 while len(data) > 0:
6057 if len(data) < 4:
6058 raise Exception("Truncated attribute header")
6059 attr,length = struct.unpack('>HH', data[0:4])
6060 data = data[4:]
6061 if length > len(data):
6062 raise Exception("Truncated attribute 0x%04x" % attr)
6063 attrs[attr] = data[0:length]
6064 data = data[length:]
6065 msg['wsc_attrs'] = attrs
6066
6067 if ATTR_MSG_TYPE in attrs:
6068 msg['wsc_msg_type'], = struct.unpack('B', attrs[ATTR_MSG_TYPE])
6069
6070 return msg
6071
6072def recv_wsc_msg(dev, opcode, msg_type):
6073 msg = get_wsc_msg(dev)
6074 if msg['wsc_opcode'] != opcode or msg['wsc_msg_type'] != msg_type:
6075 raise Exception("Unexpected Op-Code/MsgType")
6076 return msg, msg['wsc_attrs'], msg['raw_attrs']
6077
6078def build_wsc_attr(attr, payload):
6079 return struct.pack('>HH', attr, len(payload)) + payload
6080
6081def build_attr_msg_type(msg_type):
6082 return build_wsc_attr(ATTR_MSG_TYPE, struct.pack('B', msg_type))
6083
6084def build_eap_wsc(eap_code, eap_id, payload, opcode=WSC_MSG):
6085 length = 4 + 8 + 2 + len(payload)
6086 # EAPOL header
6087 msg = struct.pack('>BBH', 2, 0, length)
6088 # EAP header
6089 msg += struct.pack('>BBH', eap_code, eap_id, length)
6090 # EAP expanded header for EAP-WSC
6091 msg += struct.pack('B', 254)
6092 msg += struct.pack('>L', WPS_VENDOR_ID_WFA)[1:4]
6093 msg += struct.pack('>L', WPS_VENDOR_TYPE)
6094 # EAP-WSC header
6095 msg += struct.pack('BB', opcode, 0)
6096 # WSC attributes
6097 msg += payload
6098 return msg
6099
6100def build_eap_success(eap_id):
6101 length = 4
6102 # EAPOL header
6103 msg = struct.pack('>BBH', 2, 0, length)
6104 # EAP header
6105 msg += struct.pack('>BBH', 3, eap_id, length)
6106 return msg
6107
6108def build_eap_failure(eap_id):
6109 length = 4
6110 # EAPOL header
6111 msg = struct.pack('>BBH', 2, 0, length)
6112 # EAP header
6113 msg += struct.pack('>BBH', 4, eap_id, length)
6114 return msg
6115
6116def send_wsc_msg(dev, src, msg):
6117 res = dev.request("EAPOL_RX " + src + " " + binascii.hexlify(msg))
6118 if "OK" not in res:
6119 raise Exception("EAPOL_RX failed")
6120
6121group_5_prime = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF
6122group_5_generator = 2
6123
6124def wsc_kdf(key, label, bits):
6125 result = ''
6126 i = 1
6127 while len(result) * 8 < bits:
6128 data = struct.pack('>L', i) + label + struct.pack('>L', bits)
6129 m = hmac.new(key, data, hashlib.sha256)
6130 result += m.digest()
6131 i += 1
6132 return result[0:bits / 8]
6133
6134def wsc_keys(kdk):
6135 keys = wsc_kdf(kdk, "Wi-Fi Easy and Secure Key Derivation", 640)
6136 authkey = keys[0:32]
6137 keywrapkey = keys[32:48]
6138 emsk = keys[48:80]
6139 return authkey,keywrapkey,emsk
6140
6141def wsc_dev_pw_half_psk(authkey, dev_pw):
6142 m = hmac.new(authkey, dev_pw, hashlib.sha256)
6143 return m.digest()[0:16]
6144
6145def wsc_dev_pw_psk(authkey, dev_pw):
6146 dev_pw_1 = dev_pw[0:len(dev_pw) / 2]
6147 dev_pw_2 = dev_pw[len(dev_pw) / 2:]
6148 psk1 = wsc_dev_pw_half_psk(authkey, dev_pw_1)
6149 psk2 = wsc_dev_pw_half_psk(authkey, dev_pw_2)
6150 return psk1,psk2
6151
6152def build_attr_authenticator(authkey, prev_msg, curr_msg):
6153 m = hmac.new(authkey, prev_msg + curr_msg, hashlib.sha256)
6154 auth = m.digest()[0:8]
6155 return build_wsc_attr(ATTR_AUTHENTICATOR, auth)
6156
6157def build_attr_encr_settings(authkey, keywrapkey, data):
6158 m = hmac.new(authkey, data, hashlib.sha256)
6159 kwa = m.digest()[0:8]
6160 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6161 iv = 16*'\x99'
6162 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6163 pad_len = 16 - len(data) % 16
6164 ps = pad_len * struct.pack('B', pad_len)
6165 data += ps
6166 wrapped = aes.encrypt(data)
6167 return build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6168
6169def decrypt_attr_encr_settings(authkey, keywrapkey, data):
6170 if len(data) < 32 or len(data) % 16 != 0:
6171 raise Exception("Unexpected Encrypted Settings length: %d" % len(data))
6172 iv = data[0:16]
6173 encr = data[16:]
6174 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6175 decrypted = aes.decrypt(encr)
6176 pad_len, = struct.unpack('B', decrypted[-1])
6177 if pad_len > len(decrypted):
6178 raise Exception("Invalid padding in Encrypted Settings")
6179 for i in range(-pad_len, -1):
6180 if decrypted[i] != decrypted[-1]:
6181 raise Exception("Invalid PS value in Encrypted Settings")
6182
6183 decrypted = decrypted[0:len(decrypted) - pad_len]
6184 if len(decrypted) < 12:
6185 raise Exception("Truncated Encrypted Settings plaintext")
6186 kwa = decrypted[-12:]
6187 attr,length = struct.unpack(">HH", kwa[0:4])
6188 if attr != ATTR_KEY_WRAP_AUTH or length != 8:
6189 raise Exception("Invalid KWA header")
6190 kwa = kwa[4:]
6191 decrypted = decrypted[0:len(decrypted) - 12]
6192
6193 m = hmac.new(authkey, decrypted, hashlib.sha256)
6194 calc_kwa = m.digest()[0:8]
6195 if kwa != calc_kwa:
6196 raise Exception("KWA mismatch")
6197
6198 return decrypted
6199
6200def zeropad_str(val, pad_len):
6201 while len(val) < pad_len * 2:
6202 val = '0' + val
6203 return val
6204
6205def wsc_dh_init():
6206 # For now, use a hardcoded private key. In theory, this is supposed to be
6207 # randomly selected.
6208 own_private = 0x123456789
6209 own_public = pow(group_5_generator, own_private, group_5_prime)
6210 pk = binascii.unhexlify(zeropad_str(format(own_public, '02x'), 192))
6211 return own_private, pk
6212
6213def wsc_dh_kdf(peer_pk, own_private, mac_addr, e_nonce, r_nonce):
6214 peer_public = long(binascii.hexlify(peer_pk), 16)
6215 if peer_public < 2 or peer_public >= group_5_prime:
6216 raise Exception("Invalid peer public key")
6217 if pow(peer_public, (group_5_prime - 1) / 2, group_5_prime) != 1:
6218 raise Exception("Unexpected Legendre symbol for peer public key")
6219
6220 shared_secret = pow(peer_public, own_private, group_5_prime)
6221 ss = zeropad_str(format(shared_secret, "02x"), 192)
6222 logger.debug("DH shared secret: " + ss)
6223
6224 dhkey = hashlib.sha256(binascii.unhexlify(ss)).digest()
6225 logger.debug("DHKey: " + binascii.hexlify(dhkey))
6226
6227 m = hmac.new(dhkey, e_nonce + mac_addr + r_nonce, hashlib.sha256)
6228 kdk = m.digest()
6229 logger.debug("KDK: " + binascii.hexlify(kdk))
6230 authkey,keywrapkey,emsk = wsc_keys(kdk)
6231 logger.debug("AuthKey: " + binascii.hexlify(authkey))
6232 logger.debug("KeyWrapKey: " + binascii.hexlify(keywrapkey))
6233 logger.debug("EMSK: " + binascii.hexlify(emsk))
6234 return authkey,keywrapkey
6235
6236def wsc_dev_pw_hash(authkey, dev_pw, e_pk, r_pk):
6237 psk1,psk2 = wsc_dev_pw_psk(authkey, dev_pw)
6238 logger.debug("PSK1: " + binascii.hexlify(psk1))
6239 logger.debug("PSK2: " + binascii.hexlify(psk2))
6240
6241 # Note: Secret values are supposed to be random, but hardcoded values are
6242 # fine for testing.
6243 s1 = 16*'\x77'
6244 m = hmac.new(authkey, s1 + psk1 + e_pk + r_pk, hashlib.sha256)
6245 hash1 = m.digest()
6246 logger.debug("Hash1: " + binascii.hexlify(hash1))
6247
6248 s2 = 16*'\x88'
6249 m = hmac.new(authkey, s2 + psk2 + e_pk + r_pk, hashlib.sha256)
6250 hash2 = m.digest()
6251 logger.debug("Hash2: " + binascii.hexlify(hash2))
6252 return s1,s2,hash1,hash2
6253
6254def build_m1(eap_id, uuid_e, mac_addr, e_nonce, e_pk,
6255 manufacturer='', model_name='', config_methods='\x00\x00'):
6256 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6257 attrs += build_attr_msg_type(WPS_M1)
6258 attrs += build_wsc_attr(ATTR_UUID_E, uuid_e)
6259 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6260 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6261 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, e_pk)
6262 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6263 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6264 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6265 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, config_methods)
6266 attrs += build_wsc_attr(ATTR_WPS_STATE, '\x00')
6267 attrs += build_wsc_attr(ATTR_MANUFACTURER, manufacturer)
6268 attrs += build_wsc_attr(ATTR_MODEL_NAME, model_name)
6269 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6270 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6271 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6272 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6273 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6274 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6275 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, '\x00\x00')
6276 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6277 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6278 m1 = build_eap_wsc(2, eap_id, attrs)
6279 return m1, attrs
6280
6281def build_m2(authkey, m1, eap_id, e_nonce, r_nonce, uuid_r, r_pk,
6282 dev_pw_id='\x00\x00', eap_code=1):
6283 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6284 attrs += build_attr_msg_type(WPS_M2)
6285 if e_nonce:
6286 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6287 if r_nonce:
6288 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6289 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6290 if r_pk:
6291 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, r_pk)
6292 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6293 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6294 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6295 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6296 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6297 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6298 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6299 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6300 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6301 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6302 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6303 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6304 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6305 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6306 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6307 attrs += build_attr_authenticator(authkey, m1, attrs)
6308 m2 = build_eap_wsc(eap_code, eap_id, attrs)
6309 return m2, attrs
6310
6311def build_m2d(m1, eap_id, e_nonce, r_nonce, uuid_r, dev_pw_id=None, eap_code=1):
6312 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6313 attrs += build_attr_msg_type(WPS_M2D)
6314 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6315 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6316 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6317 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6318 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6319 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6320 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6321 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6322 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6323 #attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6324 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6325 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6326 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6327 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6328 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6329 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6330 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6331 if dev_pw_id:
6332 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6333 m2d = build_eap_wsc(eap_code, eap_id, attrs)
6334 return m2d, attrs
6335
6336def build_ack(eap_id, e_nonce, r_nonce, msg_type=WPS_WSC_ACK, eap_code=1):
6337 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6338 if msg_type is not None:
6339 attrs += build_attr_msg_type(msg_type)
6340 if e_nonce:
6341 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6342 if r_nonce:
6343 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6344 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_ACK)
6345 return msg, attrs
6346
6347def build_nack(eap_id, e_nonce, r_nonce, config_error='\x00\x00',
6348 msg_type=WPS_WSC_NACK, eap_code=1):
6349 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6350 if msg_type is not None:
6351 attrs += build_attr_msg_type(msg_type)
6352 if e_nonce:
6353 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6354 if r_nonce:
6355 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6356 if config_error:
6357 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, config_error)
6358 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_NACK)
6359 return msg, attrs
6360
6361def test_wps_ext(dev, apdev):
6362 """WPS against external implementation"""
6363 pin = "12345670"
6364 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6365 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6366 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6367
6368 logger.debug("Receive WSC/Start from AP")
6369 msg = get_wsc_msg(hapd)
6370 if msg['wsc_opcode'] != WSC_Start:
6371 raise Exception("Unexpected Op-Code for WSC/Start")
6372 wsc_start_id = msg['eap_identifier']
6373
6374 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6375 uuid_e = 16*'\x11'
6376 e_nonce = 16*'\x22'
6377 own_private, e_pk = wsc_dh_init()
6378
6379 logger.debug("Send M1 to AP")
6380 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
6381 e_nonce, e_pk)
6382 send_wsc_msg(hapd, addr, m1)
6383
6384 logger.debug("Receive M2 from AP")
6385 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
6386
6387 authkey,keywrapkey = wsc_dh_kdf(m2_attrs[ATTR_PUBLIC_KEY], own_private,
6388 mac_addr, e_nonce,
6389 m2_attrs[ATTR_REGISTRAR_NONCE])
6390 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk,
6391 m2_attrs[ATTR_PUBLIC_KEY])
6392
6393 logger.debug("Send M3 to AP")
6394 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6395 attrs += build_attr_msg_type(WPS_M3)
6396 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6397 m2_attrs[ATTR_REGISTRAR_NONCE])
6398 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
6399 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
6400 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
6401 raw_m3_attrs = attrs
6402 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6403 send_wsc_msg(hapd, addr, m3)
6404
6405 logger.debug("Receive M4 from AP")
6406 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
6407
6408 logger.debug("Send M5 to AP")
6409 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6410 attrs += build_attr_msg_type(WPS_M5)
6411 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6412 m2_attrs[ATTR_REGISTRAR_NONCE])
6413 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
6414 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6415 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
6416 raw_m5_attrs = attrs
6417 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6418 send_wsc_msg(hapd, addr, m5)
6419
6420 logger.debug("Receive M6 from AP")
6421 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
6422
6423 logger.debug("Send M7 to AP")
6424 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6425 attrs += build_attr_msg_type(WPS_M7)
6426 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6427 m2_attrs[ATTR_REGISTRAR_NONCE])
6428 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
6429 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6430 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
6431 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6432 raw_m7_attrs = attrs
6433 send_wsc_msg(hapd, addr, m7)
6434
6435 logger.debug("Receive M8 from AP")
6436 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
6437 m8_cred = decrypt_attr_encr_settings(authkey, keywrapkey,
6438 m8_attrs[ATTR_ENCR_SETTINGS])
6439 logger.debug("M8 Credential: " + binascii.hexlify(m8_cred))
6440
6441 logger.debug("Prepare WSC_Done")
6442 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6443 attrs += build_attr_msg_type(WPS_WSC_DONE)
6444 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6445 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6446 m2_attrs[ATTR_REGISTRAR_NONCE])
6447 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
6448 # Do not send WSC_Done yet to allow exchangw with STA complete before the
6449 # AP disconnects.
6450
6451 uuid_r = 16*'\x33'
6452 r_nonce = 16*'\x44'
6453
6454 eap_id = wsc_start_id
6455 logger.debug("Send WSC/Start to STA")
6456 wsc_start = build_eap_wsc(1, eap_id, "", opcode=WSC_Start)
6457 send_wsc_msg(dev[0], bssid, wsc_start)
6458 eap_id = (eap_id + 1) % 256
6459
6460 logger.debug("Receive M1 from STA")
6461 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6462
6463 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6464 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6465 r_nonce)
6466 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6467 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6468
6469 logger.debug("Send M2 to STA")
6470 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6471 m1_attrs[ATTR_ENROLLEE_NONCE],
6472 r_nonce, uuid_r, e_pk)
6473 send_wsc_msg(dev[0], bssid, m2)
6474 eap_id = (eap_id + 1) % 256
6475
6476 logger.debug("Receive M3 from STA")
6477 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6478
6479 logger.debug("Send M4 to STA")
6480 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6481 attrs += build_attr_msg_type(WPS_M4)
6482 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6483 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6484 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6485 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6486 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6487 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6488 raw_m4_attrs = attrs
6489 m4 = build_eap_wsc(1, eap_id, attrs)
6490 send_wsc_msg(dev[0], bssid, m4)
6491 eap_id = (eap_id + 1) % 256
6492
6493 logger.debug("Receive M5 from STA")
6494 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6495
6496 logger.debug("Send M6 to STA")
6497 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6498 attrs += build_attr_msg_type(WPS_M6)
6499 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6500 m1_attrs[ATTR_ENROLLEE_NONCE])
6501 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6502 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6503 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6504 raw_m6_attrs = attrs
6505 m6 = build_eap_wsc(1, eap_id, attrs)
6506 send_wsc_msg(dev[0], bssid, m6)
6507 eap_id = (eap_id + 1) % 256
6508
6509 logger.debug("Receive M7 from STA")
6510 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6511
6512 logger.debug("Send M8 to STA")
6513 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6514 attrs += build_attr_msg_type(WPS_M8)
6515 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6516 m1_attrs[ATTR_ENROLLEE_NONCE])
6517 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6518 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6519 raw_m8_attrs = attrs
6520 m8 = build_eap_wsc(1, eap_id, attrs)
6521 send_wsc_msg(dev[0], bssid, m8)
6522 eap_id = (eap_id + 1) % 256
6523
6524 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=5)
6525 if ev is None:
6526 raise Exception("wpa_supplicant did not report credential")
6527
6528 logger.debug("Receive WSC_Done from STA")
6529 msg = get_wsc_msg(dev[0])
6530 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6531 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6532
6533 logger.debug("Send WSC_Done to AP")
6534 hapd.request("SET ext_eapol_frame_io 0")
6535 dev[0].request("SET ext_eapol_frame_io 0")
6536 send_wsc_msg(hapd, addr, wsc_done)
6537
6538 ev = hapd.wait_event(["WPS-REG-SUCCESS"], timeout=5)
6539 if ev is None:
6540 raise Exception("hostapd did not report WPS success")
6541
6542 dev[0].wait_connected()
6543
6544def wps_start_kwa(dev, apdev):
6545 pin = "12345670"
6546 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6547 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6548 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6549 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6550
6551 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6552 uuid_r = 16*'\x33'
6553 r_nonce = 16*'\x44'
6554 own_private, e_pk = wsc_dh_init()
6555
6556 logger.debug("Receive M1 from STA")
6557 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6558 eap_id = (msg['eap_identifier'] + 1) % 256
6559
6560 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6561 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6562 r_nonce)
6563 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6564 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6565
6566 logger.debug("Send M2 to STA")
6567 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6568 m1_attrs[ATTR_ENROLLEE_NONCE],
6569 r_nonce, uuid_r, e_pk)
6570 send_wsc_msg(dev[0], bssid, m2)
6571 eap_id = (eap_id + 1) % 256
6572
6573 logger.debug("Receive M3 from STA")
6574 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6575
6576 logger.debug("Send M4 to STA")
6577 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6578 attrs += build_attr_msg_type(WPS_M4)
6579 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6580 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6581 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6582
6583 return r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs
6584
6585def wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id):
6586 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6587 m4 = build_eap_wsc(1, eap_id, attrs)
6588 send_wsc_msg(dev[0], bssid, m4)
6589 eap_id = (eap_id + 1) % 256
6590
6591 logger.debug("Receive M5 from STA")
6592 msg = get_wsc_msg(dev[0])
6593 if msg['wsc_opcode'] != WSC_NACK:
6594 raise Exception("Unexpected message - expected WSC_Nack")
6595
6596 dev[0].request("WPS_CANCEL")
6597 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6598 dev[0].wait_disconnected()
6599
6600def test_wps_ext_kwa_proto_no_kwa(dev, apdev):
6601 """WPS and KWA error: No KWA attribute"""
6602 r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6603 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6604 # Encrypted Settings without KWA
6605 iv = 16*'\x99'
6606 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6607 pad_len = 16 - len(data) % 16
6608 ps = pad_len * struct.pack('B', pad_len)
6609 data += ps
6610 wrapped = aes.encrypt(data)
6611 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6612 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6613
6614def test_wps_ext_kwa_proto_data_after_kwa(dev, apdev):
6615 """WPS and KWA error: Data after KWA"""
6616 r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6617 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6618 # Encrypted Settings and data after KWA
6619 m = hmac.new(authkey, data, hashlib.sha256)
6620 kwa = m.digest()[0:8]
6621 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6622 data += build_wsc_attr(ATTR_VENDOR_EXT, "1234567890")
6623 iv = 16*'\x99'
6624 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6625 pad_len = 16 - len(data) % 16
6626 ps = pad_len * struct.pack('B', pad_len)
6627 data += ps
6628 wrapped = aes.encrypt(data)
6629 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6630 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6631
6632def test_wps_ext_kwa_proto_kwa_mismatch(dev, apdev):
6633 """WPS and KWA error: KWA mismatch"""
6634 r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6635 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6636 # Encrypted Settings and KWA with incorrect value
6637 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, 8*'\x00')
6638 iv = 16*'\x99'
6639 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6640 pad_len = 16 - len(data) % 16
6641 ps = pad_len * struct.pack('B', pad_len)
6642 data += ps
6643 wrapped = aes.encrypt(data)
6644 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6645 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6646
6647def wps_run_cred_proto(dev, apdev, m8_cred, connect=False, no_connect=False):
6648 pin = "12345670"
6649 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6650 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6651 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6652 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6653
6654 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6655 uuid_r = 16*'\x33'
6656 r_nonce = 16*'\x44'
6657 own_private, e_pk = wsc_dh_init()
6658
6659 logger.debug("Receive M1 from STA")
6660 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6661 eap_id = (msg['eap_identifier'] + 1) % 256
6662
6663 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6664 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6665 r_nonce)
6666 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6667 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6668
6669 logger.debug("Send M2 to STA")
6670 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6671 m1_attrs[ATTR_ENROLLEE_NONCE],
6672 r_nonce, uuid_r, e_pk)
6673 send_wsc_msg(dev[0], bssid, m2)
6674 eap_id = (eap_id + 1) % 256
6675
6676 logger.debug("Receive M3 from STA")
6677 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6678
6679 logger.debug("Send M4 to STA")
6680 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6681 attrs += build_attr_msg_type(WPS_M4)
6682 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6683 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6684 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6685 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6686 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6687 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6688 raw_m4_attrs = attrs
6689 m4 = build_eap_wsc(1, eap_id, attrs)
6690 send_wsc_msg(dev[0], bssid, m4)
6691 eap_id = (eap_id + 1) % 256
6692
6693 logger.debug("Receive M5 from STA")
6694 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6695
6696 logger.debug("Send M6 to STA")
6697 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6698 attrs += build_attr_msg_type(WPS_M6)
6699 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6700 m1_attrs[ATTR_ENROLLEE_NONCE])
6701 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6702 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6703 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6704 raw_m6_attrs = attrs
6705 m6 = build_eap_wsc(1, eap_id, attrs)
6706 send_wsc_msg(dev[0], bssid, m6)
6707 eap_id = (eap_id + 1) % 256
6708
6709 logger.debug("Receive M7 from STA")
6710 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6711
6712 logger.debug("Send M8 to STA")
6713 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6714 attrs += build_attr_msg_type(WPS_M8)
6715 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6716 m1_attrs[ATTR_ENROLLEE_NONCE])
6717 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6718 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6719 raw_m8_attrs = attrs
6720 m8 = build_eap_wsc(1, eap_id, attrs)
6721 send_wsc_msg(dev[0], bssid, m8)
6722 eap_id = (eap_id + 1) % 256
6723
6724 if no_connect:
6725 logger.debug("Receive WSC_Done from STA")
6726 msg = get_wsc_msg(dev[0])
6727 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6728 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6729
6730 hapd.request("SET ext_eapol_frame_io 0")
6731 dev[0].request("SET ext_eapol_frame_io 0")
6732
6733 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6734
6735 dev[0].wait_disconnected()
6736 dev[0].request("REMOVE_NETWORK all")
6737 elif connect:
6738 logger.debug("Receive WSC_Done from STA")
6739 msg = get_wsc_msg(dev[0])
6740 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6741 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6742
6743 hapd.request("SET ext_eapol_frame_io 0")
6744 dev[0].request("SET ext_eapol_frame_io 0")
6745
6746 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6747
6748 dev[0].wait_connected()
6749 else:
6750 # Verify STA NACK's the credential
6751 msg = get_wsc_msg(dev[0])
6752 if msg['wsc_opcode'] != WSC_NACK:
6753 raise Exception("Unexpected message - expected WSC_Nack")
6754 dev[0].request("WPS_CANCEL")
6755 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6756 dev[0].wait_disconnected()
6757
6758def build_cred(nw_idx='\x01', ssid='test-wps-conf', auth_type='\x00\x20',
6759 encr_type='\x00\x08', nw_key="12345678",
6760 mac_addr='\x00\x00\x00\x00\x00\x00'):
6761 attrs = ''
6762 if nw_idx is not None:
6763 attrs += build_wsc_attr(ATTR_NETWORK_INDEX, nw_idx)
6764 if ssid is not None:
6765 attrs += build_wsc_attr(ATTR_SSID, ssid)
6766 if auth_type is not None:
6767 attrs += build_wsc_attr(ATTR_AUTH_TYPE, auth_type)
6768 if encr_type is not None:
6769 attrs += build_wsc_attr(ATTR_ENCR_TYPE, encr_type)
6770 if nw_key is not None:
6771 attrs += build_wsc_attr(ATTR_NETWORK_KEY, nw_key)
6772 if mac_addr is not None:
6773 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6774 return build_wsc_attr(ATTR_CRED, attrs)
6775
6776def test_wps_ext_cred_proto_success(dev, apdev):
6777 """WPS and Credential: success"""
6778 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6779 m8_cred = build_cred(mac_addr=mac_addr)
6780 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6781
6782def test_wps_ext_cred_proto_mac_addr_mismatch(dev, apdev):
6783 """WPS and Credential: MAC Address mismatch"""
6784 m8_cred = build_cred()
6785 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6786
6787def test_wps_ext_cred_proto_zero_padding(dev, apdev):
6788 """WPS and Credential: zeropadded attributes"""
6789 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6790 m8_cred = build_cred(mac_addr=mac_addr, ssid='test-wps-conf\x00',
6791 nw_key="12345678\x00")
6792 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6793
6794def test_wps_ext_cred_proto_ssid_missing(dev, apdev):
6795 """WPS and Credential: SSID missing"""
6796 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6797 m8_cred = build_cred(mac_addr=mac_addr, ssid=None)
6798 wps_run_cred_proto(dev, apdev, m8_cred)
6799
6800def test_wps_ext_cred_proto_ssid_zero_len(dev, apdev):
6801 """WPS and Credential: Zero-length SSID"""
6802 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6803 m8_cred = build_cred(mac_addr=mac_addr, ssid="")
6804 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6805
6806def test_wps_ext_cred_proto_auth_type_missing(dev, apdev):
6807 """WPS and Credential: Auth Type missing"""
6808 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6809 m8_cred = build_cred(mac_addr=mac_addr, auth_type=None)
6810 wps_run_cred_proto(dev, apdev, m8_cred)
6811
6812def test_wps_ext_cred_proto_encr_type_missing(dev, apdev):
6813 """WPS and Credential: Encr Type missing"""
6814 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6815 m8_cred = build_cred(mac_addr=mac_addr, encr_type=None)
6816 wps_run_cred_proto(dev, apdev, m8_cred)
6817
6818def test_wps_ext_cred_proto_network_key_missing(dev, apdev):
6819 """WPS and Credential: Network Key missing"""
6820 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6821 m8_cred = build_cred(mac_addr=mac_addr, nw_key=None)
6822 wps_run_cred_proto(dev, apdev, m8_cred)
6823
6824def test_wps_ext_cred_proto_network_key_missing_open(dev, apdev):
6825 """WPS and Credential: Network Key missing (open)"""
6826 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6827 m8_cred = build_cred(mac_addr=mac_addr, auth_type='\x00\x01',
6828 encr_type='\x00\x01', nw_key=None, ssid="foo")
6829 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6830
6831def test_wps_ext_cred_proto_mac_addr_missing(dev, apdev):
6832 """WPS and Credential: MAC Address missing"""
6833 m8_cred = build_cred(mac_addr=None)
6834 wps_run_cred_proto(dev, apdev, m8_cred)
6835
6836def test_wps_ext_cred_proto_invalid_encr_type(dev, apdev):
6837 """WPS and Credential: Invalid Encr Type"""
6838 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6839 m8_cred = build_cred(mac_addr=mac_addr, encr_type='\x00\x00')
6840 wps_run_cred_proto(dev, apdev, m8_cred)
6841
6842def test_wps_ext_cred_proto_missing_cred(dev, apdev):
6843 """WPS and Credential: Missing Credential"""
6844 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6845 m8_cred = ''
6846 wps_run_cred_proto(dev, apdev, m8_cred)
6847
6848def test_wps_ext_proto_m2_no_public_key(dev, apdev):
6849 """WPS and no Public Key in M2"""
6850 pin = "12345670"
6851 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6852 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6853 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6854 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6855
6856 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6857 uuid_r = 16*'\x33'
6858 r_nonce = 16*'\x44'
6859 own_private, e_pk = wsc_dh_init()
6860
6861 logger.debug("Receive M1 from STA")
6862 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6863 eap_id = (msg['eap_identifier'] + 1) % 256
6864
6865 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6866 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6867 r_nonce)
6868 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6869 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6870
6871 logger.debug("Send M2 to STA")
6872 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6873 m1_attrs[ATTR_ENROLLEE_NONCE],
6874 r_nonce, uuid_r, None)
6875 send_wsc_msg(dev[0], bssid, m2)
6876 eap_id = (eap_id + 1) % 256
6877
6878 # Verify STA NACK's the credential
6879 msg = get_wsc_msg(dev[0])
6880 if msg['wsc_opcode'] != WSC_NACK:
6881 raise Exception("Unexpected message - expected WSC_Nack")
6882 dev[0].request("WPS_CANCEL")
6883 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6884 dev[0].wait_disconnected()
6885
6886def test_wps_ext_proto_m2_invalid_public_key(dev, apdev):
6887 """WPS and invalid Public Key in M2"""
6888 pin = "12345670"
6889 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6890 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6891 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6892 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6893
6894 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6895 uuid_r = 16*'\x33'
6896 r_nonce = 16*'\x44'
6897 own_private, e_pk = wsc_dh_init()
6898
6899 logger.debug("Receive M1 from STA")
6900 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6901 eap_id = (msg['eap_identifier'] + 1) % 256
6902
6903 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6904 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6905 r_nonce)
6906 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6907 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6908
6909 logger.debug("Send M2 to STA")
6910 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6911 m1_attrs[ATTR_ENROLLEE_NONCE],
6912 r_nonce, uuid_r, 192*'\xff')
6913 send_wsc_msg(dev[0], bssid, m2)
6914 eap_id = (eap_id + 1) % 256
6915
6916 # Verify STA NACK's the credential
6917 msg = get_wsc_msg(dev[0])
6918 if msg['wsc_opcode'] != WSC_NACK:
6919 raise Exception("Unexpected message - expected WSC_Nack")
6920 dev[0].request("WPS_CANCEL")
6921 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6922 dev[0].wait_disconnected()
6923
6924def test_wps_ext_proto_m2_public_key_oom(dev, apdev):
6925 """WPS and Public Key OOM in M2"""
6926 pin = "12345670"
6927 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6928 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6929 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6930 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6931
6932 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6933 uuid_r = 16*'\x33'
6934 r_nonce = 16*'\x44'
6935 own_private, e_pk = wsc_dh_init()
6936
6937 logger.debug("Receive M1 from STA")
6938 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6939 eap_id = (msg['eap_identifier'] + 1) % 256
6940
6941 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6942 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6943 r_nonce)
6944 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6945 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6946
6947 logger.debug("Send M2 to STA")
6948 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6949 m1_attrs[ATTR_ENROLLEE_NONCE],
6950 r_nonce, uuid_r, e_pk)
6951 with alloc_fail(dev[0], 1, "wpabuf_alloc_copy;wps_process_pubkey"):
6952 send_wsc_msg(dev[0], bssid, m2)
6953 eap_id = (eap_id + 1) % 256
6954
6955 # Verify STA NACK's the credential
6956 msg = get_wsc_msg(dev[0])
6957 if msg['wsc_opcode'] != WSC_NACK:
6958 raise Exception("Unexpected message - expected WSC_Nack")
6959 dev[0].request("WPS_CANCEL")
6960 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6961 dev[0].wait_disconnected()
6962
6963def test_wps_ext_proto_nack_m3(dev, apdev):
6964 """WPS and NACK M3"""
6965 pin = "12345670"
6966 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6967 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6968 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6969 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6970
6971 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6972 uuid_r = 16*'\x33'
6973 r_nonce = 16*'\x44'
6974 own_private, e_pk = wsc_dh_init()
6975
6976 logger.debug("Receive M1 from STA")
6977 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6978 eap_id = (msg['eap_identifier'] + 1) % 256
6979
6980 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6981 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6982 r_nonce)
6983 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6984 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6985
6986 logger.debug("Send M2 to STA")
6987 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6988 m1_attrs[ATTR_ENROLLEE_NONCE],
6989 r_nonce, uuid_r, e_pk)
6990 send_wsc_msg(dev[0], bssid, m2)
6991 eap_id = (eap_id + 1) % 256
6992
6993 logger.debug("Receive M3 from STA")
6994 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6995
6996 logger.debug("Send NACK to STA")
6997 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
6998 r_nonce, config_error='\x01\x23')
6999 send_wsc_msg(dev[0], bssid, msg)
7000 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7001 if ev is None:
7002 raise Exception("Failure not reported")
7003 if "msg=7 config_error=291" not in ev:
7004 raise Exception("Unexpected failure reason: " + ev)
7005
7006def test_wps_ext_proto_nack_m5(dev, apdev):
7007 """WPS and NACK M5"""
7008 pin = "12345670"
7009 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7010 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7011 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7012 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7013
7014 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7015 uuid_r = 16*'\x33'
7016 r_nonce = 16*'\x44'
7017 own_private, e_pk = wsc_dh_init()
7018
7019 logger.debug("Receive M1 from STA")
7020 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7021 eap_id = (msg['eap_identifier'] + 1) % 256
7022
7023 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7024 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7025 r_nonce)
7026 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7027 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7028
7029 logger.debug("Send M2 to STA")
7030 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7031 m1_attrs[ATTR_ENROLLEE_NONCE],
7032 r_nonce, uuid_r, e_pk)
7033 send_wsc_msg(dev[0], bssid, m2)
7034 eap_id = (eap_id + 1) % 256
7035
7036 logger.debug("Receive M3 from STA")
7037 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7038
7039 logger.debug("Send M4 to STA")
7040 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7041 attrs += build_attr_msg_type(WPS_M4)
7042 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7043 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7044 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7045 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7046 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7047 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7048 raw_m4_attrs = attrs
7049 m4 = build_eap_wsc(1, eap_id, attrs)
7050 send_wsc_msg(dev[0], bssid, m4)
7051 eap_id = (eap_id + 1) % 256
7052
7053 logger.debug("Receive M5 from STA")
7054 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7055
7056 logger.debug("Send NACK to STA")
7057 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7058 r_nonce, config_error='\x01\x24')
7059 send_wsc_msg(dev[0], bssid, msg)
7060 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7061 if ev is None:
7062 raise Exception("Failure not reported")
7063 if "msg=9 config_error=292" not in ev:
7064 raise Exception("Unexpected failure reason: " + ev)
7065
7066def wps_nack_m3(dev, apdev):
7067 pin = "00000000"
7068 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
7069 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7070 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7071 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7072
7073 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7074 uuid_r = 16*'\x33'
7075 r_nonce = 16*'\x44'
7076 own_private, e_pk = wsc_dh_init()
7077
7078 logger.debug("Receive M1 from STA")
7079 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7080 eap_id = (msg['eap_identifier'] + 1) % 256
7081
7082 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7083 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7084 r_nonce)
7085 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7086 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7087
7088 logger.debug("Send M2 to STA")
7089 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7090 m1_attrs[ATTR_ENROLLEE_NONCE],
7091 r_nonce, uuid_r, e_pk, dev_pw_id='\x00\x04')
7092 send_wsc_msg(dev[0], bssid, m2)
7093 eap_id = (eap_id + 1) % 256
7094
7095 logger.debug("Receive M3 from STA")
7096 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7097 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid
7098
7099def test_wps_ext_proto_nack_m3_no_config_error(dev, apdev):
7100 """WPS and NACK M3 missing Config Error"""
7101 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7102 logger.debug("Send NACK to STA")
7103 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, config_error=None)
7104 send_wsc_msg(dev[0], bssid, msg)
7105 dev[0].request("WPS_CANCEL")
7106 dev[0].wait_disconnected()
7107 dev[0].flush_scan_cache()
7108
7109def test_wps_ext_proto_nack_m3_no_e_nonce(dev, apdev):
7110 """WPS and NACK M3 missing E-Nonce"""
7111 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7112 logger.debug("Send NACK to STA")
7113 msg, attrs = build_nack(eap_id, None, r_nonce)
7114 send_wsc_msg(dev[0], bssid, msg)
7115 dev[0].request("WPS_CANCEL")
7116 dev[0].wait_disconnected()
7117 dev[0].flush_scan_cache()
7118
7119def test_wps_ext_proto_nack_m3_e_nonce_mismatch(dev, apdev):
7120 """WPS and NACK M3 E-Nonce mismatch"""
7121 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7122 logger.debug("Send NACK to STA")
7123 msg, attrs = build_nack(eap_id, 16*'\x00', r_nonce)
7124 send_wsc_msg(dev[0], bssid, msg)
7125 dev[0].request("WPS_CANCEL")
7126 dev[0].wait_disconnected()
7127 dev[0].flush_scan_cache()
7128
7129def test_wps_ext_proto_nack_m3_no_r_nonce(dev, apdev):
7130 """WPS and NACK M3 missing R-Nonce"""
7131 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7132 logger.debug("Send NACK to STA")
7133 msg, attrs = build_nack(eap_id, e_nonce, None)
7134 send_wsc_msg(dev[0], bssid, msg)
7135 dev[0].request("WPS_CANCEL")
7136 dev[0].wait_disconnected()
7137 dev[0].flush_scan_cache()
7138
7139def test_wps_ext_proto_nack_m3_r_nonce_mismatch(dev, apdev):
7140 """WPS and NACK M3 R-Nonce mismatch"""
7141 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7142 logger.debug("Send NACK to STA")
7143 msg, attrs = build_nack(eap_id, e_nonce, 16*'\x00')
7144 send_wsc_msg(dev[0], bssid, msg)
7145 dev[0].request("WPS_CANCEL")
7146 dev[0].wait_disconnected()
7147 dev[0].flush_scan_cache()
7148
7149def test_wps_ext_proto_nack_m3_no_msg_type(dev, apdev):
7150 """WPS and NACK M3 no Message Type"""
7151 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7152 logger.debug("Send NACK to STA")
7153 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=None)
7154 send_wsc_msg(dev[0], bssid, msg)
7155 dev[0].request("WPS_CANCEL")
7156 dev[0].wait_disconnected()
7157 dev[0].flush_scan_cache()
7158
7159def test_wps_ext_proto_nack_m3_invalid_msg_type(dev, apdev):
7160 """WPS and NACK M3 invalid Message Type"""
7161 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7162 logger.debug("Send NACK to STA")
7163 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=123)
7164 send_wsc_msg(dev[0], bssid, msg)
7165 dev[0].request("WPS_CANCEL")
7166 dev[0].wait_disconnected()
7167 dev[0].flush_scan_cache()
7168
7169def test_wps_ext_proto_nack_m3_invalid_attr(dev, apdev):
7170 """WPS and NACK M3 invalid attribute"""
7171 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7172 logger.debug("Send NACK to STA")
7173 attrs = '\x10\x10\x00'
7174 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_NACK)
7175 send_wsc_msg(dev[0], bssid, msg)
7176 dev[0].request("WPS_CANCEL")
7177 dev[0].wait_disconnected()
7178 dev[0].flush_scan_cache()
7179
7180def test_wps_ext_proto_ack_m3_no_e_nonce(dev, apdev):
7181 """WPS and ACK M3 missing E-Nonce"""
7182 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7183 logger.debug("Send NACK to STA")
7184 msg, attrs = build_ack(eap_id, None, r_nonce)
7185 send_wsc_msg(dev[0], bssid, msg)
7186 dev[0].request("WPS_CANCEL")
7187 dev[0].wait_disconnected()
7188 dev[0].flush_scan_cache()
7189
7190def test_wps_ext_proto_ack_m3_e_nonce_mismatch(dev, apdev):
7191 """WPS and ACK M3 E-Nonce mismatch"""
7192 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7193 logger.debug("Send NACK to STA")
7194 msg, attrs = build_ack(eap_id, 16*'\x00', r_nonce)
7195 send_wsc_msg(dev[0], bssid, msg)
7196 dev[0].request("WPS_CANCEL")
7197 dev[0].wait_disconnected()
7198 dev[0].flush_scan_cache()
7199
7200def test_wps_ext_proto_ack_m3_no_r_nonce(dev, apdev):
7201 """WPS and ACK M3 missing R-Nonce"""
7202 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7203 logger.debug("Send NACK to STA")
7204 msg, attrs = build_ack(eap_id, e_nonce, None)
7205 send_wsc_msg(dev[0], bssid, msg)
7206 dev[0].request("WPS_CANCEL")
7207 dev[0].wait_disconnected()
7208 dev[0].flush_scan_cache()
7209
7210def test_wps_ext_proto_ack_m3_r_nonce_mismatch(dev, apdev):
7211 """WPS and ACK M3 R-Nonce mismatch"""
7212 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7213 logger.debug("Send NACK to STA")
7214 msg, attrs = build_ack(eap_id, e_nonce, 16*'\x00')
7215 send_wsc_msg(dev[0], bssid, msg)
7216 dev[0].request("WPS_CANCEL")
7217 dev[0].wait_disconnected()
7218 dev[0].flush_scan_cache()
7219
7220def test_wps_ext_proto_ack_m3_no_msg_type(dev, apdev):
7221 """WPS and ACK M3 no Message Type"""
7222 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7223 logger.debug("Send NACK to STA")
7224 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=None)
7225 send_wsc_msg(dev[0], bssid, msg)
7226 dev[0].request("WPS_CANCEL")
7227 dev[0].wait_disconnected()
7228 dev[0].flush_scan_cache()
7229
7230def test_wps_ext_proto_ack_m3_invalid_msg_type(dev, apdev):
7231 """WPS and ACK M3 invalid Message Type"""
7232 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7233 logger.debug("Send NACK to STA")
7234 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=123)
7235 send_wsc_msg(dev[0], bssid, msg)
7236 dev[0].request("WPS_CANCEL")
7237 dev[0].wait_disconnected()
7238 dev[0].flush_scan_cache()
7239
7240def test_wps_ext_proto_ack_m3_invalid_attr(dev, apdev):
7241 """WPS and ACK M3 invalid attribute"""
7242 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7243 logger.debug("Send ACK to STA")
7244 attrs = '\x10\x10\x00'
7245 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_ACK)
7246 send_wsc_msg(dev[0], bssid, msg)
7247 dev[0].request("WPS_CANCEL")
7248 dev[0].wait_disconnected()
7249 dev[0].flush_scan_cache()
7250
7251def test_wps_ext_proto_ack_m3(dev, apdev):
7252 """WPS and ACK M3"""
7253 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7254 logger.debug("Send ACK to STA")
7255 msg, attrs = build_ack(eap_id, e_nonce, r_nonce)
7256 send_wsc_msg(dev[0], bssid, msg)
7257 dev[0].request("WPS_CANCEL")
7258 dev[0].wait_disconnected()
7259 dev[0].flush_scan_cache()
7260
7261def wps_to_m3_helper(dev, apdev):
7262 pin = "12345670"
7263 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7264 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7265 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7266 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7267
7268 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7269 uuid_r = 16*'\x33'
7270 r_nonce = 16*'\x44'
7271 own_private, e_pk = wsc_dh_init()
7272
7273 logger.debug("Receive M1 from STA")
7274 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7275 eap_id = (msg['eap_identifier'] + 1) % 256
7276
7277 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7278 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7279 r_nonce)
7280 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7281 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7282
7283 logger.debug("Send M2 to STA")
7284 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7285 m1_attrs[ATTR_ENROLLEE_NONCE],
7286 r_nonce, uuid_r, e_pk)
7287 send_wsc_msg(dev[0], bssid, m2)
7288 eap_id = (eap_id + 1) % 256
7289
7290 logger.debug("Receive M3 from STA")
7291 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7292 return eap_id, m1_attrs, r_nonce, bssid, r_hash1, r_hash2, r_s1, r_s2, raw_m3_attrs, authkey, keywrapkey
7293
7294def wps_to_m3(dev, apdev):
7295 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)
7296 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s1, raw_m3_attrs, authkey, keywrapkey
7297
7298def wps_to_m5(dev, apdev):
7299 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)
7300
7301 logger.debug("Send M4 to STA")
7302 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7303 attrs += build_attr_msg_type(WPS_M4)
7304 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7305 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7306 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7307 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7308 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7309 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7310 raw_m4_attrs = attrs
7311 m4 = build_eap_wsc(1, eap_id, attrs)
7312 send_wsc_msg(dev[0], bssid, m4)
7313 eap_id = (eap_id + 1) % 256
7314
7315 logger.debug("Receive M5 from STA")
7316 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7317
7318 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s2, raw_m5_attrs, authkey, keywrapkey
7319
7320def test_wps_ext_proto_m4_missing_r_hash1(dev, apdev):
7321 """WPS and no R-Hash1 in M4"""
7322 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7323
7324 logger.debug("Send M4 to STA")
7325 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7326 attrs += build_attr_msg_type(WPS_M4)
7327 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7328 #attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7329 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7330 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7331 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7332 attrs += build_attr_authenticator(authkey, m3, attrs)
7333 m4 = build_eap_wsc(1, eap_id, attrs)
7334 send_wsc_msg(dev[0], bssid, m4)
7335 eap_id = (eap_id + 1) % 256
7336
7337 logger.debug("Receive M5 (NACK) from STA")
7338 msg = get_wsc_msg(dev[0])
7339 if msg['wsc_opcode'] != WSC_NACK:
7340 raise Exception("Unexpected message - expected WSC_Nack")
7341
7342 dev[0].request("WPS_CANCEL")
7343 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7344 dev[0].wait_disconnected()
7345
7346def test_wps_ext_proto_m4_missing_r_hash2(dev, apdev):
7347 """WPS and no R-Hash2 in M4"""
7348 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7349
7350 logger.debug("Send M4 to STA")
7351 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7352 attrs += build_attr_msg_type(WPS_M4)
7353 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7354 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7355 #attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7356 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7357 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7358 attrs += build_attr_authenticator(authkey, m3, attrs)
7359 m4 = build_eap_wsc(1, eap_id, attrs)
7360 send_wsc_msg(dev[0], bssid, m4)
7361 eap_id = (eap_id + 1) % 256
7362
7363 logger.debug("Receive M5 (NACK) from STA")
7364 msg = get_wsc_msg(dev[0])
7365 if msg['wsc_opcode'] != WSC_NACK:
7366 raise Exception("Unexpected message - expected WSC_Nack")
7367
7368 dev[0].request("WPS_CANCEL")
7369 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7370 dev[0].wait_disconnected()
7371
7372def test_wps_ext_proto_m4_missing_r_snonce1(dev, apdev):
7373 """WPS and no R-SNonce1 in M4"""
7374 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7375
7376 logger.debug("Send M4 to STA")
7377 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7378 attrs += build_attr_msg_type(WPS_M4)
7379 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7380 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7381 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7382 #data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7383 data = ''
7384 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7385 attrs += build_attr_authenticator(authkey, m3, attrs)
7386 m4 = build_eap_wsc(1, eap_id, attrs)
7387 send_wsc_msg(dev[0], bssid, m4)
7388 eap_id = (eap_id + 1) % 256
7389
7390 logger.debug("Receive M5 (NACK) from STA")
7391 msg = get_wsc_msg(dev[0])
7392 if msg['wsc_opcode'] != WSC_NACK:
7393 raise Exception("Unexpected message - expected WSC_Nack")
7394
7395 dev[0].request("WPS_CANCEL")
7396 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7397 dev[0].wait_disconnected()
7398
7399def test_wps_ext_proto_m4_invalid_pad_string(dev, apdev):
7400 """WPS and invalid pad string in M4"""
7401 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7402
7403 logger.debug("Send M4 to STA")
7404 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7405 attrs += build_attr_msg_type(WPS_M4)
7406 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7407 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7408 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7409 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7410
7411 m = hmac.new(authkey, data, hashlib.sha256)
7412 kwa = m.digest()[0:8]
7413 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7414 iv = 16*'\x99'
7415 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7416 pad_len = 16 - len(data) % 16
7417 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', pad_len - 1)
7418 data += ps
7419 wrapped = aes.encrypt(data)
7420 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7421
7422 attrs += build_attr_authenticator(authkey, m3, attrs)
7423 m4 = build_eap_wsc(1, eap_id, attrs)
7424 send_wsc_msg(dev[0], bssid, m4)
7425 eap_id = (eap_id + 1) % 256
7426
7427 logger.debug("Receive M5 (NACK) from STA")
7428 msg = get_wsc_msg(dev[0])
7429 if msg['wsc_opcode'] != WSC_NACK:
7430 raise Exception("Unexpected message - expected WSC_Nack")
7431
7432 dev[0].request("WPS_CANCEL")
7433 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7434 dev[0].wait_disconnected()
7435
7436def test_wps_ext_proto_m4_invalid_pad_value(dev, apdev):
7437 """WPS and invalid pad value in M4"""
7438 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7439
7440 logger.debug("Send M4 to STA")
7441 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7442 attrs += build_attr_msg_type(WPS_M4)
7443 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7444 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7445 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7446 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7447
7448 m = hmac.new(authkey, data, hashlib.sha256)
7449 kwa = m.digest()[0:8]
7450 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7451 iv = 16*'\x99'
7452 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7453 pad_len = 16 - len(data) % 16
7454 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', 255)
7455 data += ps
7456 wrapped = aes.encrypt(data)
7457 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7458
7459 attrs += build_attr_authenticator(authkey, m3, attrs)
7460 m4 = build_eap_wsc(1, eap_id, attrs)
7461 send_wsc_msg(dev[0], bssid, m4)
7462 eap_id = (eap_id + 1) % 256
7463
7464 logger.debug("Receive M5 (NACK) from STA")
7465 msg = get_wsc_msg(dev[0])
7466 if msg['wsc_opcode'] != WSC_NACK:
7467 raise Exception("Unexpected message - expected WSC_Nack")
7468
7469 dev[0].request("WPS_CANCEL")
7470 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7471 dev[0].wait_disconnected()
7472
7473def test_wps_ext_proto_m4_no_encr_settings(dev, apdev):
7474 """WPS and no Encr Settings in M4"""
7475 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7476
7477 logger.debug("Send M4 to STA")
7478 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7479 attrs += build_attr_msg_type(WPS_M4)
7480 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7481 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7482 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7483 attrs += build_attr_authenticator(authkey, m3, attrs)
7484 m4 = build_eap_wsc(1, eap_id, attrs)
7485 send_wsc_msg(dev[0], bssid, m4)
7486 eap_id = (eap_id + 1) % 256
7487
7488 logger.debug("Receive M5 (NACK) from STA")
7489 msg = get_wsc_msg(dev[0])
7490 if msg['wsc_opcode'] != WSC_NACK:
7491 raise Exception("Unexpected message - expected WSC_Nack")
7492
7493 dev[0].request("WPS_CANCEL")
7494 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7495 dev[0].wait_disconnected()
7496
7497def test_wps_ext_proto_m6_missing_r_snonce2(dev, apdev):
7498 """WPS and no R-SNonce2 in M6"""
7499 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7500
7501 logger.debug("Send M6 to STA")
7502 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7503 attrs += build_attr_msg_type(WPS_M6)
7504 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7505 #data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7506 data = ''
7507 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7508 attrs += build_attr_authenticator(authkey, m5, attrs)
7509 m6 = build_eap_wsc(1, eap_id, attrs)
7510 send_wsc_msg(dev[0], bssid, m6)
7511 eap_id = (eap_id + 1) % 256
7512
7513 logger.debug("Receive M7 (NACK) from STA")
7514 msg = get_wsc_msg(dev[0])
7515 if msg['wsc_opcode'] != WSC_NACK:
7516 raise Exception("Unexpected message - expected WSC_Nack")
7517
7518 dev[0].request("WPS_CANCEL")
7519 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7520 dev[0].wait_disconnected()
7521
7522def test_wps_ext_proto_m6_no_encr_settings(dev, apdev):
7523 """WPS and no Encr Settings in M6"""
7524 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7525
7526 logger.debug("Send M6 to STA")
7527 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7528 attrs += build_attr_msg_type(WPS_M6)
7529 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7530 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7531 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7532 attrs += build_attr_authenticator(authkey, m5, attrs)
7533 m6 = build_eap_wsc(1, eap_id, attrs)
7534 send_wsc_msg(dev[0], bssid, m6)
7535 eap_id = (eap_id + 1) % 256
7536
7537 logger.debug("Receive M7 (NACK) from STA")
7538 msg = get_wsc_msg(dev[0])
7539 if msg['wsc_opcode'] != WSC_NACK:
7540 raise Exception("Unexpected message - expected WSC_Nack")
7541
7542 dev[0].request("WPS_CANCEL")
7543 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7544 dev[0].wait_disconnected()
7545
7546def test_wps_ext_proto_m8_no_encr_settings(dev, apdev):
7547 """WPS and no Encr Settings in M6"""
7548 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7549
7550 logger.debug("Send M6 to STA")
7551 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7552 attrs += build_attr_msg_type(WPS_M6)
7553 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7554 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7555 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7556 attrs += build_attr_authenticator(authkey, m5, attrs)
7557 raw_m6_attrs = attrs
7558 m6 = build_eap_wsc(1, eap_id, attrs)
7559 send_wsc_msg(dev[0], bssid, m6)
7560 eap_id = (eap_id + 1) % 256
7561
7562 logger.debug("Receive M7 from STA")
7563 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
7564
7565 logger.debug("Send M8 to STA")
7566 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7567 attrs += build_attr_msg_type(WPS_M8)
7568 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7569 #attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
7570 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7571 raw_m8_attrs = attrs
7572 m8 = build_eap_wsc(1, eap_id, attrs)
7573 send_wsc_msg(dev[0], bssid, m8)
7574
7575 logger.debug("Receive WSC_Done (NACK) from STA")
7576 msg = get_wsc_msg(dev[0])
7577 if msg['wsc_opcode'] != WSC_NACK:
7578 raise Exception("Unexpected message - expected WSC_Nack")
7579
7580 dev[0].request("WPS_CANCEL")
7581 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7582 dev[0].wait_disconnected()
7583
7584def wps_start_ext_reg(apdev, dev):
7585 addr = dev.own_addr()
7586 bssid = apdev['bssid']
7587 ssid = "test-wps-conf"
7588 appin = "12345670"
7589 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
7590 "wpa_passphrase": "12345678", "wpa": "2",
7591 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
7592 "ap_pin": appin }
7593 hapd = hostapd.add_ap(apdev['ifname'], params)
7594
7595 dev.scan_for_bss(bssid, freq="2412")
7596 hapd.request("SET ext_eapol_frame_io 1")
7597 dev.request("SET ext_eapol_frame_io 1")
7598
7599 dev.request("WPS_REG " + bssid + " " + appin)
7600
7601 return addr,bssid,hapd
7602
7603def wps_run_ap_settings_proto(dev, apdev, ap_settings, success):
7604 addr,bssid,hapd = wps_start_ext_reg(apdev[0], dev[0])
7605 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7606 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7607
7608 logger.debug("Receive M1 from AP")
7609 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7610 mac_addr = m1_attrs[ATTR_MAC_ADDR]
7611 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7612 e_pk = m1_attrs[ATTR_PUBLIC_KEY]
7613
7614 appin = '12345670'
7615 uuid_r = 16*'\x33'
7616 r_nonce = 16*'\x44'
7617 own_private, r_pk = wsc_dh_init()
7618 authkey,keywrapkey = wsc_dh_kdf(e_pk, own_private, mac_addr, e_nonce,
7619 r_nonce)
7620 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, appin, e_pk, r_pk)
7621
7622 logger.debug("Send M2 to AP")
7623 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, msg['eap_identifier'],
7624 e_nonce, r_nonce, uuid_r, r_pk, eap_code=2)
7625 send_wsc_msg(hapd, addr, m2)
7626
7627 logger.debug("Receive M3 from AP")
7628 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M3)
7629
7630 logger.debug("Send M4 to AP")
7631 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7632 attrs += build_attr_msg_type(WPS_M4)
7633 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7634 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7635 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7636 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7637 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7638 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7639 raw_m4_attrs = attrs
7640 m4 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7641 send_wsc_msg(hapd, addr, m4)
7642
7643 logger.debug("Receive M5 from AP")
7644 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M5)
7645
7646 logger.debug("Send M6 to STA")
7647 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7648 attrs += build_attr_msg_type(WPS_M6)
7649 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7650 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7651 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7652 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
7653 raw_m6_attrs = attrs
7654 m6 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7655 send_wsc_msg(hapd, addr, m6)
7656
7657 logger.debug("Receive M7 from AP")
7658 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M7)
7659
7660 logger.debug("Send M8 to STA")
7661 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7662 attrs += build_attr_msg_type(WPS_M8)
7663 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7664 if ap_settings:
7665 attrs += build_attr_encr_settings(authkey, keywrapkey, ap_settings)
7666 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7667 raw_m8_attrs = attrs
7668 m8 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7669 send_wsc_msg(hapd, addr, m8)
7670
7671 if success:
7672 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
7673 if ev is None:
7674 raise Exception("New AP settings not reported")
7675 logger.debug("Receive WSC_Done from AP")
7676 msg = get_wsc_msg(hapd)
7677 if msg['wsc_opcode'] != WSC_Done:
7678 raise Exception("Unexpected message - expected WSC_Done")
7679
7680 logger.debug("Send WSC_ACK to AP")
7681 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
7682 eap_code=2)
7683 send_wsc_msg(hapd, addr, ack)
7684 dev[0].wait_disconnected()
7685 else:
7686 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
7687 if ev is None:
7688 raise Exception("WPS failure not reported")
7689 logger.debug("Receive WSC_NACK from AP")
7690 msg = get_wsc_msg(hapd)
7691 if msg['wsc_opcode'] != WSC_NACK:
7692 raise Exception("Unexpected message - expected WSC_NACK")
7693
7694 logger.debug("Send WSC_NACK to AP")
7695 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7696 eap_code=2)
7697 send_wsc_msg(hapd, addr, nack)
7698 dev[0].wait_disconnected()
7699
7700def test_wps_ext_ap_settings_success(dev, apdev):
7701 """WPS and AP Settings: success"""
7702 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7703 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7704 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7705 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7706 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7707 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7708 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7709
7710def test_wps_ext_ap_settings_missing(dev, apdev):
7711 """WPS and AP Settings: missing"""
7712 wps_run_ap_settings_proto(dev, apdev, None, False)
7713
7714def test_wps_ext_ap_settings_mac_addr_mismatch(dev, apdev):
7715 """WPS and AP Settings: MAC Address mismatch"""
7716 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7717 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7718 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7719 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7720 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7721 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, '\x00\x00\x00\x00\x00\x00')
7722 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7723
7724def test_wps_ext_ap_settings_mac_addr_missing(dev, apdev):
7725 """WPS and AP Settings: missing MAC Address"""
7726 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7727 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7728 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7729 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7730 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7731 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7732
7733def test_wps_ext_ap_settings_reject_encr_type(dev, apdev):
7734 """WPS and AP Settings: reject Encr Type"""
7735 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7736 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7737 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7738 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x00')
7739 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7740 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7741 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7742
7743def test_wps_ext_ap_settings_m2d(dev, apdev):
7744 """WPS and AP Settings: M2D"""
7745 addr,bssid,hapd = wps_start_ext_reg(apdev[0], dev[0])
7746 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7747 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7748
7749 logger.debug("Receive M1 from AP")
7750 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7751 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7752
7753 r_nonce = 16*'\x44'
7754 uuid_r = 16*'\x33'
7755
7756 logger.debug("Send M2D to AP")
7757 m2d, raw_m2d_attrs = build_m2d(raw_m1_attrs, msg['eap_identifier'],
7758 e_nonce, r_nonce, uuid_r,
7759 dev_pw_id='\x00\x00', eap_code=2)
7760 send_wsc_msg(hapd, addr, m2d)
7761
7762 ev = hapd.wait_event(["WPS-M2D"], timeout=5)
7763 if ev is None:
7764 raise Exception("M2D not reported")
7765
7766 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7767
7768def wps_wait_ap_nack(hapd, dev, e_nonce, r_nonce):
7769 logger.debug("Receive WSC_NACK from AP")
7770 msg = get_wsc_msg(hapd)
7771 if msg['wsc_opcode'] != WSC_NACK:
7772 raise Exception("Unexpected message - expected WSC_NACK")
7773
7774 logger.debug("Send WSC_NACK to AP")
7775 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7776 eap_code=2)
7777 send_wsc_msg(hapd, dev.own_addr(), nack)
7778 dev.wait_disconnected()
7779
7780def test_wps_ext_m3_missing_e_hash1(dev, apdev):
7781 """WPS proto: M3 missing E-Hash1"""
7782 pin = "12345670"
7783 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7784 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7785 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7786
7787 logger.debug("Receive WSC/Start from AP")
7788 msg = get_wsc_msg(hapd)
7789 if msg['wsc_opcode'] != WSC_Start:
7790 raise Exception("Unexpected Op-Code for WSC/Start")
7791
7792 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7793 uuid_e = 16*'\x11'
7794 e_nonce = 16*'\x22'
7795 own_private, e_pk = wsc_dh_init()
7796
7797 logger.debug("Send M1 to AP")
7798 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7799 e_nonce, e_pk)
7800 send_wsc_msg(hapd, addr, m1)
7801
7802 logger.debug("Receive M2 from AP")
7803 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7804 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7805 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7806
7807 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7808 r_nonce)
7809 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7810
7811 logger.debug("Send M3 to AP")
7812 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7813 attrs += build_attr_msg_type(WPS_M3)
7814 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7815 #attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7816 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7817 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7818 raw_m3_attrs = attrs
7819 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7820 send_wsc_msg(hapd, addr, m3)
7821
7822 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7823
7824def test_wps_ext_m3_missing_e_hash2(dev, apdev):
7825 """WPS proto: M3 missing E-Hash2"""
7826 pin = "12345670"
7827 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7828 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7829 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7830
7831 logger.debug("Receive WSC/Start from AP")
7832 msg = get_wsc_msg(hapd)
7833 if msg['wsc_opcode'] != WSC_Start:
7834 raise Exception("Unexpected Op-Code for WSC/Start")
7835
7836 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7837 uuid_e = 16*'\x11'
7838 e_nonce = 16*'\x22'
7839 own_private, e_pk = wsc_dh_init()
7840
7841 logger.debug("Send M1 to AP")
7842 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7843 e_nonce, e_pk)
7844 send_wsc_msg(hapd, addr, m1)
7845
7846 logger.debug("Receive M2 from AP")
7847 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7848 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7849 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7850
7851 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7852 r_nonce)
7853 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7854
7855 logger.debug("Send M3 to AP")
7856 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7857 attrs += build_attr_msg_type(WPS_M3)
7858 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7859 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7860 #attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7861 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7862 raw_m3_attrs = attrs
7863 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7864 send_wsc_msg(hapd, addr, m3)
7865
7866 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7867
7868def test_wps_ext_m5_missing_e_snonce1(dev, apdev):
7869 """WPS proto: M5 missing E-SNonce1"""
7870 pin = "12345670"
7871 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7872 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7873 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7874
7875 logger.debug("Receive WSC/Start from AP")
7876 msg = get_wsc_msg(hapd)
7877 if msg['wsc_opcode'] != WSC_Start:
7878 raise Exception("Unexpected Op-Code for WSC/Start")
7879
7880 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7881 uuid_e = 16*'\x11'
7882 e_nonce = 16*'\x22'
7883 own_private, e_pk = wsc_dh_init()
7884
7885 logger.debug("Send M1 to AP")
7886 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7887 e_nonce, e_pk)
7888 send_wsc_msg(hapd, addr, m1)
7889
7890 logger.debug("Receive M2 from AP")
7891 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7892 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7893 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7894
7895 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7896 r_nonce)
7897 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7898
7899 logger.debug("Send M3 to AP")
7900 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7901 attrs += build_attr_msg_type(WPS_M3)
7902 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7903 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7904 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7905 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7906 raw_m3_attrs = attrs
7907 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7908 send_wsc_msg(hapd, addr, m3)
7909
7910 logger.debug("Receive M4 from AP")
7911 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
7912
7913 logger.debug("Send M5 to AP")
7914 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7915 attrs += build_attr_msg_type(WPS_M5)
7916 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7917 #data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
7918 data = ''
7919 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7920 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
7921 raw_m5_attrs = attrs
7922 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7923 send_wsc_msg(hapd, addr, m5)
7924
7925 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7926
7927def test_wps_ext_m5_e_snonce1_mismatch(dev, apdev):
7928 """WPS proto: M5 E-SNonce1 mismatch"""
7929 pin = "12345670"
7930 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7931 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7932 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7933
7934 logger.debug("Receive WSC/Start from AP")
7935 msg = get_wsc_msg(hapd)
7936 if msg['wsc_opcode'] != WSC_Start:
7937 raise Exception("Unexpected Op-Code for WSC/Start")
7938
7939 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7940 uuid_e = 16*'\x11'
7941 e_nonce = 16*'\x22'
7942 own_private, e_pk = wsc_dh_init()
7943
7944 logger.debug("Send M1 to AP")
7945 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7946 e_nonce, e_pk)
7947 send_wsc_msg(hapd, addr, m1)
7948
7949 logger.debug("Receive M2 from AP")
7950 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7951 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7952 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7953
7954 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7955 r_nonce)
7956 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7957
7958 logger.debug("Send M3 to AP")
7959 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7960 attrs += build_attr_msg_type(WPS_M3)
7961 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7962 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7963 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7964 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7965 raw_m3_attrs = attrs
7966 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7967 send_wsc_msg(hapd, addr, m3)
7968
7969 logger.debug("Receive M4 from AP")
7970 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
7971
7972 logger.debug("Send M5 to AP")
7973 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7974 attrs += build_attr_msg_type(WPS_M5)
7975 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7976 data = build_wsc_attr(ATTR_E_SNONCE1, 16*'\x00')
7977 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7978 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
7979 raw_m5_attrs = attrs
7980 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7981 send_wsc_msg(hapd, addr, m5)
7982
7983 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7984
7985def test_wps_ext_m7_missing_e_snonce2(dev, apdev):
7986 """WPS proto: M7 missing E-SNonce2"""
7987 pin = "12345670"
7988 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7989 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7990 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7991
7992 logger.debug("Receive WSC/Start from AP")
7993 msg = get_wsc_msg(hapd)
7994 if msg['wsc_opcode'] != WSC_Start:
7995 raise Exception("Unexpected Op-Code for WSC/Start")
7996
7997 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7998 uuid_e = 16*'\x11'
7999 e_nonce = 16*'\x22'
8000 own_private, e_pk = wsc_dh_init()
8001
8002 logger.debug("Send M1 to AP")
8003 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8004 e_nonce, e_pk)
8005 send_wsc_msg(hapd, addr, m1)
8006
8007 logger.debug("Receive M2 from AP")
8008 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8009 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8010 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8011
8012 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8013 r_nonce)
8014 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8015
8016 logger.debug("Send M3 to AP")
8017 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8018 attrs += build_attr_msg_type(WPS_M3)
8019 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8020 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8021 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8022 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8023 raw_m3_attrs = attrs
8024 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8025 send_wsc_msg(hapd, addr, m3)
8026
8027 logger.debug("Receive M4 from AP")
8028 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8029
8030 logger.debug("Send M5 to AP")
8031 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8032 attrs += build_attr_msg_type(WPS_M5)
8033 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8034 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8035 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8036 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8037 raw_m5_attrs = attrs
8038 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8039 send_wsc_msg(hapd, addr, m5)
8040
8041 logger.debug("Receive M6 from AP")
8042 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8043
8044 logger.debug("Send M7 to AP")
8045 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8046 attrs += build_attr_msg_type(WPS_M7)
8047 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8048 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
8049 data = ''
8050 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8051 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8052 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8053 raw_m7_attrs = attrs
8054 send_wsc_msg(hapd, addr, m7)
8055
8056 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8057
8058def test_wps_ext_m7_e_snonce2_mismatch(dev, apdev):
8059 """WPS proto: M7 E-SNonce2 mismatch"""
8060 pin = "12345670"
8061 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8062 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8063 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8064
8065 logger.debug("Receive WSC/Start from AP")
8066 msg = get_wsc_msg(hapd)
8067 if msg['wsc_opcode'] != WSC_Start:
8068 raise Exception("Unexpected Op-Code for WSC/Start")
8069
8070 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8071 uuid_e = 16*'\x11'
8072 e_nonce = 16*'\x22'
8073 own_private, e_pk = wsc_dh_init()
8074
8075 logger.debug("Send M1 to AP")
8076 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8077 e_nonce, e_pk)
8078 send_wsc_msg(hapd, addr, m1)
8079
8080 logger.debug("Receive M2 from AP")
8081 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8082 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8083 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8084
8085 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8086 r_nonce)
8087 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8088
8089 logger.debug("Send M3 to AP")
8090 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8091 attrs += build_attr_msg_type(WPS_M3)
8092 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8093 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8094 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8095 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8096 raw_m3_attrs = attrs
8097 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8098 send_wsc_msg(hapd, addr, m3)
8099
8100 logger.debug("Receive M4 from AP")
8101 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8102
8103 logger.debug("Send M5 to AP")
8104 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8105 attrs += build_attr_msg_type(WPS_M5)
8106 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8107 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8108 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8109 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8110 raw_m5_attrs = attrs
8111 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8112 send_wsc_msg(hapd, addr, m5)
8113
8114 logger.debug("Receive M6 from AP")
8115 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8116
8117 logger.debug("Send M7 to AP")
8118 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8119 attrs += build_attr_msg_type(WPS_M7)
8120 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8121 data = build_wsc_attr(ATTR_E_SNONCE2, 16*'\x00')
8122 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8123 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8124 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8125 raw_m7_attrs = attrs
8126 send_wsc_msg(hapd, addr, m7)
8127
8128 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8129
8130def test_wps_ext_m1_pubkey_oom(dev, apdev):
8131 """WPS proto: M1 PubKey OOM"""
8132 pin = "12345670"
8133 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8134 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8135 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8136
8137 logger.debug("Receive WSC/Start from AP")
8138 msg = get_wsc_msg(hapd)
8139 if msg['wsc_opcode'] != WSC_Start:
8140 raise Exception("Unexpected Op-Code for WSC/Start")
8141
8142 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8143 uuid_e = 16*'\x11'
8144 e_nonce = 16*'\x22'
8145 own_private, e_pk = wsc_dh_init()
8146
8147 logger.debug("Send M1 to AP")
8148 with alloc_fail(hapd, 1, "wpabuf_alloc_copy;wps_process_pubkey"):
8149 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8150 e_nonce, e_pk)
8151 send_wsc_msg(hapd, addr, m1)
8152 wps_wait_eap_failure(hapd, dev[0])
8153
8154def wps_wait_eap_failure(hapd, dev):
8155 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
8156 if ev is None:
8157 raise Exception("EAP-Failure not reported")
8158 dev.wait_disconnected()
8159
8160def test_wps_ext_m3_m1(dev, apdev):
8161 """WPS proto: M3 replaced with M1"""
8162 pin = "12345670"
8163 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8164 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8165 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8166
8167 logger.debug("Receive WSC/Start from AP")
8168 msg = get_wsc_msg(hapd)
8169 if msg['wsc_opcode'] != WSC_Start:
8170 raise Exception("Unexpected Op-Code for WSC/Start")
8171
8172 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8173 uuid_e = 16*'\x11'
8174 e_nonce = 16*'\x22'
8175 own_private, e_pk = wsc_dh_init()
8176
8177 logger.debug("Send M1 to AP")
8178 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8179 e_nonce, e_pk)
8180 send_wsc_msg(hapd, addr, m1)
8181
8182 logger.debug("Receive M2 from AP")
8183 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8184 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8185 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8186
8187 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8188 r_nonce)
8189 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8190
8191 logger.debug("Send M3(M1) to AP")
8192 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8193 attrs += build_attr_msg_type(WPS_M1)
8194 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8195 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8196 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8197 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8198 raw_m3_attrs = attrs
8199 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8200 send_wsc_msg(hapd, addr, m3)
8201
8202 wps_wait_eap_failure(hapd, dev[0])
8203
8204def test_wps_ext_m5_m3(dev, apdev):
8205 """WPS proto: M5 replaced with M3"""
8206 pin = "12345670"
8207 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8208 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8209 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8210
8211 logger.debug("Receive WSC/Start from AP")
8212 msg = get_wsc_msg(hapd)
8213 if msg['wsc_opcode'] != WSC_Start:
8214 raise Exception("Unexpected Op-Code for WSC/Start")
8215
8216 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8217 uuid_e = 16*'\x11'
8218 e_nonce = 16*'\x22'
8219 own_private, e_pk = wsc_dh_init()
8220
8221 logger.debug("Send M1 to AP")
8222 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8223 e_nonce, e_pk)
8224 send_wsc_msg(hapd, addr, m1)
8225
8226 logger.debug("Receive M2 from AP")
8227 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8228 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8229 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8230
8231 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8232 r_nonce)
8233 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8234
8235 logger.debug("Send M3 to AP")
8236 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8237 attrs += build_attr_msg_type(WPS_M3)
8238 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8239 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8240 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8241 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8242 raw_m3_attrs = attrs
8243 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8244 send_wsc_msg(hapd, addr, m3)
8245
8246 logger.debug("Receive M4 from AP")
8247 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8248
8249 logger.debug("Send M5(M3) to AP")
8250 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8251 attrs += build_attr_msg_type(WPS_M3)
8252 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8253 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8254 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8255 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8256 raw_m5_attrs = attrs
8257 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8258 send_wsc_msg(hapd, addr, m5)
8259
8260 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8261
8262def test_wps_ext_m3_m2(dev, apdev):
8263 """WPS proto: M3 replaced with M2"""
8264 pin = "12345670"
8265 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8266 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8267 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8268
8269 logger.debug("Receive WSC/Start from AP")
8270 msg = get_wsc_msg(hapd)
8271 if msg['wsc_opcode'] != WSC_Start:
8272 raise Exception("Unexpected Op-Code for WSC/Start")
8273
8274 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8275 uuid_e = 16*'\x11'
8276 e_nonce = 16*'\x22'
8277 own_private, e_pk = wsc_dh_init()
8278
8279 logger.debug("Send M1 to AP")
8280 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8281 e_nonce, e_pk)
8282 send_wsc_msg(hapd, addr, m1)
8283
8284 logger.debug("Receive M2 from AP")
8285 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8286 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8287 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8288
8289 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8290 r_nonce)
8291 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8292
8293 logger.debug("Send M3(M2) to AP")
8294 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8295 attrs += build_attr_msg_type(WPS_M2)
8296 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8297 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8298 raw_m3_attrs = attrs
8299 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8300 send_wsc_msg(hapd, addr, m3)
8301
8302 wps_wait_eap_failure(hapd, dev[0])
8303
8304def test_wps_ext_m3_m5(dev, apdev):
8305 """WPS proto: M3 replaced with M5"""
8306 pin = "12345670"
8307 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8308 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8309 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8310
8311 logger.debug("Receive WSC/Start from AP")
8312 msg = get_wsc_msg(hapd)
8313 if msg['wsc_opcode'] != WSC_Start:
8314 raise Exception("Unexpected Op-Code for WSC/Start")
8315
8316 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8317 uuid_e = 16*'\x11'
8318 e_nonce = 16*'\x22'
8319 own_private, e_pk = wsc_dh_init()
8320
8321 logger.debug("Send M1 to AP")
8322 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8323 e_nonce, e_pk)
8324 send_wsc_msg(hapd, addr, m1)
8325
8326 logger.debug("Receive M2 from AP")
8327 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8328 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8329 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8330
8331 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8332 r_nonce)
8333 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8334
8335 logger.debug("Send M3(M5) to AP")
8336 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8337 attrs += build_attr_msg_type(WPS_M5)
8338 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8339 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8340 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8341 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8342 raw_m3_attrs = attrs
8343 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8344 send_wsc_msg(hapd, addr, m3)
8345
8346 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8347
8348def test_wps_ext_m3_m7(dev, apdev):
8349 """WPS proto: M3 replaced with M7"""
8350 pin = "12345670"
8351 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8352 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8353 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8354
8355 logger.debug("Receive WSC/Start from AP")
8356 msg = get_wsc_msg(hapd)
8357 if msg['wsc_opcode'] != WSC_Start:
8358 raise Exception("Unexpected Op-Code for WSC/Start")
8359
8360 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8361 uuid_e = 16*'\x11'
8362 e_nonce = 16*'\x22'
8363 own_private, e_pk = wsc_dh_init()
8364
8365 logger.debug("Send M1 to AP")
8366 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8367 e_nonce, e_pk)
8368 send_wsc_msg(hapd, addr, m1)
8369
8370 logger.debug("Receive M2 from AP")
8371 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8372 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8373 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8374
8375 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8376 r_nonce)
8377 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8378
8379 logger.debug("Send M3(M7) to AP")
8380 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8381 attrs += build_attr_msg_type(WPS_M7)
8382 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8383 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8384 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8385 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8386 raw_m3_attrs = attrs
8387 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8388 send_wsc_msg(hapd, addr, m3)
8389
8390 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8391
8392def test_wps_ext_m3_done(dev, apdev):
8393 """WPS proto: M3 replaced with WSC_Done"""
8394 pin = "12345670"
8395 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8396 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8397 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8398
8399 logger.debug("Receive WSC/Start from AP")
8400 msg = get_wsc_msg(hapd)
8401 if msg['wsc_opcode'] != WSC_Start:
8402 raise Exception("Unexpected Op-Code for WSC/Start")
8403
8404 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8405 uuid_e = 16*'\x11'
8406 e_nonce = 16*'\x22'
8407 own_private, e_pk = wsc_dh_init()
8408
8409 logger.debug("Send M1 to AP")
8410 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8411 e_nonce, e_pk)
8412 send_wsc_msg(hapd, addr, m1)
8413
8414 logger.debug("Receive M2 from AP")
8415 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8416 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8417 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8418
8419 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8420 r_nonce)
8421 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8422
8423 logger.debug("Send M3(WSC_Done) to AP")
8424 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8425 attrs += build_attr_msg_type(WPS_WSC_DONE)
8426 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8427 raw_m3_attrs = attrs
8428 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8429 send_wsc_msg(hapd, addr, m3)
8430
8431 wps_wait_eap_failure(hapd, dev[0])
8432
8433def test_wps_ext_m2_nack_invalid(dev, apdev):
8434 """WPS proto: M2 followed by invalid NACK"""
8435 pin = "12345670"
8436 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8437 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8438 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8439
8440 logger.debug("Receive WSC/Start from AP")
8441 msg = get_wsc_msg(hapd)
8442 if msg['wsc_opcode'] != WSC_Start:
8443 raise Exception("Unexpected Op-Code for WSC/Start")
8444
8445 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8446 uuid_e = 16*'\x11'
8447 e_nonce = 16*'\x22'
8448 own_private, e_pk = wsc_dh_init()
8449
8450 logger.debug("Send M1 to AP")
8451 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8452 e_nonce, e_pk)
8453 send_wsc_msg(hapd, addr, m1)
8454
8455 logger.debug("Receive M2 from AP")
8456 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8457 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8458 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8459
8460 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8461 r_nonce)
8462 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8463
8464 logger.debug("Send WSC_NACK to AP")
8465 attrs = '\x10\x00\x00'
8466 nack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_NACK)
8467 send_wsc_msg(hapd, addr, nack)
8468
8469 wps_wait_eap_failure(hapd, dev[0])
8470
8471def test_wps_ext_m2_nack_no_msg_type(dev, apdev):
8472 """WPS proto: M2 followed by NACK without Msg Type"""
8473 pin = "12345670"
8474 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8475 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8476 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8477
8478 logger.debug("Receive WSC/Start from AP")
8479 msg = get_wsc_msg(hapd)
8480 if msg['wsc_opcode'] != WSC_Start:
8481 raise Exception("Unexpected Op-Code for WSC/Start")
8482
8483 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8484 uuid_e = 16*'\x11'
8485 e_nonce = 16*'\x22'
8486 own_private, e_pk = wsc_dh_init()
8487
8488 logger.debug("Send M1 to AP")
8489 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8490 e_nonce, e_pk)
8491 send_wsc_msg(hapd, addr, m1)
8492
8493 logger.debug("Receive M2 from AP")
8494 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8495 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8496 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8497
8498 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8499 r_nonce)
8500 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8501
8502 logger.debug("Send WSC_NACK to AP")
8503 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8504 msg_type=None, eap_code=2)
8505 send_wsc_msg(hapd, addr, nack)
8506
8507 wps_wait_eap_failure(hapd, dev[0])
8508
8509def test_wps_ext_m2_nack_invalid_msg_type(dev, apdev):
8510 """WPS proto: M2 followed by NACK with invalid Msg Type"""
8511 pin = "12345670"
8512 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8513 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8514 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8515
8516 logger.debug("Receive WSC/Start from AP")
8517 msg = get_wsc_msg(hapd)
8518 if msg['wsc_opcode'] != WSC_Start:
8519 raise Exception("Unexpected Op-Code for WSC/Start")
8520
8521 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8522 uuid_e = 16*'\x11'
8523 e_nonce = 16*'\x22'
8524 own_private, e_pk = wsc_dh_init()
8525
8526 logger.debug("Send M1 to AP")
8527 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8528 e_nonce, e_pk)
8529 send_wsc_msg(hapd, addr, m1)
8530
8531 logger.debug("Receive M2 from AP")
8532 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8533 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8534 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8535
8536 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8537 r_nonce)
8538 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8539
8540 logger.debug("Send WSC_NACK to AP")
8541 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8542 msg_type=WPS_WSC_ACK, eap_code=2)
8543 send_wsc_msg(hapd, addr, nack)
8544
8545 wps_wait_eap_failure(hapd, dev[0])
8546
8547def test_wps_ext_m2_nack_e_nonce_mismatch(dev, apdev):
8548 """WPS proto: M2 followed by NACK with e-nonce mismatch"""
8549 pin = "12345670"
8550 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8551 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8552 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8553
8554 logger.debug("Receive WSC/Start from AP")
8555 msg = get_wsc_msg(hapd)
8556 if msg['wsc_opcode'] != WSC_Start:
8557 raise Exception("Unexpected Op-Code for WSC/Start")
8558
8559 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8560 uuid_e = 16*'\x11'
8561 e_nonce = 16*'\x22'
8562 own_private, e_pk = wsc_dh_init()
8563
8564 logger.debug("Send M1 to AP")
8565 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8566 e_nonce, e_pk)
8567 send_wsc_msg(hapd, addr, m1)
8568
8569 logger.debug("Receive M2 from AP")
8570 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8571 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8572 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8573
8574 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8575 r_nonce)
8576 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8577
8578 logger.debug("Send WSC_NACK to AP")
8579 nack,attrs = build_nack(msg['eap_identifier'], 16*'\x00', r_nonce,
8580 eap_code=2)
8581 send_wsc_msg(hapd, addr, nack)
8582
8583 wps_wait_eap_failure(hapd, dev[0])
8584
8585def test_wps_ext_m2_nack_no_config_error(dev, apdev):
8586 """WPS proto: M2 followed by NACK without Config Error"""
8587 pin = "12345670"
8588 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8589 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8590 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8591
8592 logger.debug("Receive WSC/Start from AP")
8593 msg = get_wsc_msg(hapd)
8594 if msg['wsc_opcode'] != WSC_Start:
8595 raise Exception("Unexpected Op-Code for WSC/Start")
8596
8597 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8598 uuid_e = 16*'\x11'
8599 e_nonce = 16*'\x22'
8600 own_private, e_pk = wsc_dh_init()
8601
8602 logger.debug("Send M1 to AP")
8603 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8604 e_nonce, e_pk)
8605 send_wsc_msg(hapd, addr, m1)
8606
8607 logger.debug("Receive M2 from AP")
8608 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8609 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8610 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8611
8612 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8613 r_nonce)
8614 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8615
8616 logger.debug("Send WSC_NACK to AP")
8617 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8618 config_error=None, eap_code=2)
8619 send_wsc_msg(hapd, addr, nack)
8620
8621 wps_wait_eap_failure(hapd, dev[0])
8622
8623def test_wps_ext_m2_ack_invalid(dev, apdev):
8624 """WPS proto: M2 followed by invalid ACK"""
8625 pin = "12345670"
8626 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8627 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8628 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8629
8630 logger.debug("Receive WSC/Start from AP")
8631 msg = get_wsc_msg(hapd)
8632 if msg['wsc_opcode'] != WSC_Start:
8633 raise Exception("Unexpected Op-Code for WSC/Start")
8634
8635 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8636 uuid_e = 16*'\x11'
8637 e_nonce = 16*'\x22'
8638 own_private, e_pk = wsc_dh_init()
8639
8640 logger.debug("Send M1 to AP")
8641 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8642 e_nonce, e_pk)
8643 send_wsc_msg(hapd, addr, m1)
8644
8645 logger.debug("Receive M2 from AP")
8646 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8647 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8648 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8649
8650 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8651 r_nonce)
8652 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8653
8654 logger.debug("Send WSC_ACK to AP")
8655 attrs = '\x10\x00\x00'
8656 ack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_ACK)
8657 send_wsc_msg(hapd, addr, ack)
8658
8659 wps_wait_eap_failure(hapd, dev[0])
8660
8661def test_wps_ext_m2_ack(dev, apdev):
8662 """WPS proto: M2 followed by ACK"""
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*'\x11'
8675 e_nonce = 16*'\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_ACK to AP")
8693 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce, eap_code=2)
8694 send_wsc_msg(hapd, addr, ack)
8695
8696 wps_wait_eap_failure(hapd, dev[0])
8697
8698def test_wps_ext_m2_ack_no_msg_type(dev, apdev):
8699 """WPS proto: M2 followed by ACK missing Msg Type"""
8700 pin = "12345670"
8701 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8702 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8703 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8704
8705 logger.debug("Receive WSC/Start from AP")
8706 msg = get_wsc_msg(hapd)
8707 if msg['wsc_opcode'] != WSC_Start:
8708 raise Exception("Unexpected Op-Code for WSC/Start")
8709
8710 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8711 uuid_e = 16*'\x11'
8712 e_nonce = 16*'\x22'
8713 own_private, e_pk = wsc_dh_init()
8714
8715 logger.debug("Send M1 to AP")
8716 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8717 e_nonce, e_pk)
8718 send_wsc_msg(hapd, addr, m1)
8719
8720 logger.debug("Receive M2 from AP")
8721 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8722 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8723 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8724
8725 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8726 r_nonce)
8727 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8728
8729 logger.debug("Send WSC_ACK to AP")
8730 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8731 msg_type=None, eap_code=2)
8732 send_wsc_msg(hapd, addr, ack)
8733
8734 wps_wait_eap_failure(hapd, dev[0])
8735
8736def test_wps_ext_m2_ack_invalid_msg_type(dev, apdev):
8737 """WPS proto: M2 followed by ACK with invalid Msg Type"""
8738 pin = "12345670"
8739 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8740 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8741 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8742
8743 logger.debug("Receive WSC/Start from AP")
8744 msg = get_wsc_msg(hapd)
8745 if msg['wsc_opcode'] != WSC_Start:
8746 raise Exception("Unexpected Op-Code for WSC/Start")
8747
8748 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8749 uuid_e = 16*'\x11'
8750 e_nonce = 16*'\x22'
8751 own_private, e_pk = wsc_dh_init()
8752
8753 logger.debug("Send M1 to AP")
8754 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8755 e_nonce, e_pk)
8756 send_wsc_msg(hapd, addr, m1)
8757
8758 logger.debug("Receive M2 from AP")
8759 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8760 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8761 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8762
8763 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8764 r_nonce)
8765 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8766
8767 logger.debug("Send WSC_ACK to AP")
8768 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8769 msg_type=WPS_WSC_NACK, eap_code=2)
8770 send_wsc_msg(hapd, addr, ack)
8771
8772 wps_wait_eap_failure(hapd, dev[0])
8773
8774def test_wps_ext_m2_ack_e_nonce_mismatch(dev, apdev):
8775 """WPS proto: M2 followed by ACK with e-nonce mismatch"""
8776 pin = "12345670"
8777 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8778 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8779 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8780
8781 logger.debug("Receive WSC/Start from AP")
8782 msg = get_wsc_msg(hapd)
8783 if msg['wsc_opcode'] != WSC_Start:
8784 raise Exception("Unexpected Op-Code for WSC/Start")
8785
8786 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8787 uuid_e = 16*'\x11'
8788 e_nonce = 16*'\x22'
8789 own_private, e_pk = wsc_dh_init()
8790
8791 logger.debug("Send M1 to AP")
8792 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8793 e_nonce, e_pk)
8794 send_wsc_msg(hapd, addr, m1)
8795
8796 logger.debug("Receive M2 from AP")
8797 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8798 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8799 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8800
8801 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8802 r_nonce)
8803 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8804
8805 logger.debug("Send WSC_ACK to AP")
8806 ack,attrs = build_ack(msg['eap_identifier'], 16*'\x00', r_nonce,
8807 eap_code=2)
8808 send_wsc_msg(hapd, addr, ack)
8809
8810 wps_wait_eap_failure(hapd, dev[0])
8811
8812def test_wps_ext_m1_invalid(dev, apdev):
8813 """WPS proto: M1 failing parsing"""
8814 pin = "12345670"
8815 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8816 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8817 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8818
8819 logger.debug("Receive WSC/Start from AP")
8820 msg = get_wsc_msg(hapd)
8821 if msg['wsc_opcode'] != WSC_Start:
8822 raise Exception("Unexpected Op-Code for WSC/Start")
8823
8824 logger.debug("Send M1 to AP")
8825 attrs = '\x10\x00\x00'
8826 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8827 send_wsc_msg(hapd, addr, m1)
8828
8829 wps_wait_eap_failure(hapd, dev[0])
8830
8831def test_wps_ext_m1_missing_msg_type(dev, apdev):
8832 """WPS proto: M1 missing Msg Type"""
8833 pin = "12345670"
8834 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8835 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8836 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8837
8838 logger.debug("Receive WSC/Start from AP")
8839 msg = get_wsc_msg(hapd)
8840 if msg['wsc_opcode'] != WSC_Start:
8841 raise Exception("Unexpected Op-Code for WSC/Start")
8842
8843 logger.debug("Send M1 to AP")
8844 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8845 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8846 send_wsc_msg(hapd, addr, m1)
8847
8848 wps_wait_ap_nack(hapd, dev[0], 16*'\x00', 16*'\x00')
8849
8850def wps_ext_wsc_done(dev, apdev):
8851 pin = "12345670"
8852 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8853 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8854 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8855
8856 logger.debug("Receive WSC/Start from AP")
8857 msg = get_wsc_msg(hapd)
8858 if msg['wsc_opcode'] != WSC_Start:
8859 raise Exception("Unexpected Op-Code for WSC/Start")
8860
8861 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8862 uuid_e = 16*'\x11'
8863 e_nonce = 16*'\x22'
8864 own_private, e_pk = wsc_dh_init()
8865
8866 logger.debug("Send M1 to AP")
8867 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8868 e_nonce, e_pk)
8869 send_wsc_msg(hapd, addr, m1)
8870
8871 logger.debug("Receive M2 from AP")
8872 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8873 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8874 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8875
8876 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8877 r_nonce)
8878 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8879
8880 logger.debug("Send M3 to AP")
8881 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8882 attrs += build_attr_msg_type(WPS_M3)
8883 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8884 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8885 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8886 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8887 raw_m3_attrs = attrs
8888 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8889 send_wsc_msg(hapd, addr, m3)
8890
8891 logger.debug("Receive M4 from AP")
8892 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8893
8894 logger.debug("Send M5 to AP")
8895 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8896 attrs += build_attr_msg_type(WPS_M5)
8897 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8898 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8899 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8900 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8901 raw_m5_attrs = attrs
8902 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8903 send_wsc_msg(hapd, addr, m5)
8904
8905 logger.debug("Receive M6 from AP")
8906 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8907
8908 logger.debug("Send M7 to AP")
8909 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8910 attrs += build_attr_msg_type(WPS_M7)
8911 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8912 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
8913 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8914 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8915 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8916 raw_m7_attrs = attrs
8917 send_wsc_msg(hapd, addr, m7)
8918
8919 logger.debug("Receive M8 from AP")
8920 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
8921 return hapd, msg, e_nonce, r_nonce
8922
8923def test_wps_ext_wsc_done_invalid(dev, apdev):
8924 """WPS proto: invalid WSC_Done"""
8925 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
8926
8927 logger.debug("Send WSC_Done to AP")
8928 attrs = '\x10\x00\x00'
8929 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8930 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
8931
8932 wps_wait_eap_failure(hapd, dev[0])
8933
8934def test_wps_ext_wsc_done_no_msg_type(dev, apdev):
8935 """WPS proto: invalid WSC_Done"""
8936 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
8937
8938 logger.debug("Send WSC_Done to AP")
8939 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8940 #attrs += build_attr_msg_type(WPS_WSC_DONE)
8941 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
8942 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8943 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8944 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
8945
8946 wps_wait_eap_failure(hapd, dev[0])
8947
8948def test_wps_ext_wsc_done_wrong_msg_type(dev, apdev):
8949 """WPS proto: WSC_Done with wrong Msg Type"""
8950 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
8951
8952 logger.debug("Send WSC_Done to AP")
8953 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8954 attrs += build_attr_msg_type(WPS_WSC_ACK)
8955 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
8956 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8957 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8958 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
8959
8960 wps_wait_eap_failure(hapd, dev[0])
8961
8962def test_wps_ext_wsc_done_no_e_nonce(dev, apdev):
8963 """WPS proto: WSC_Done without e_nonce"""
8964 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
8965
8966 logger.debug("Send WSC_Done to AP")
8967 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8968 attrs += build_attr_msg_type(WPS_WSC_DONE)
8969 #attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
8970 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8971 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8972 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
8973
8974 wps_wait_eap_failure(hapd, dev[0])
8975
8976def test_wps_ext_wsc_done_no_r_nonce(dev, apdev):
8977 """WPS proto: WSC_Done without r_nonce"""
8978 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
8979
8980 logger.debug("Send WSC_Done to AP")
8981 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8982 attrs += build_attr_msg_type(WPS_WSC_DONE)
8983 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
8984 #attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8985 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8986 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
8987
8988 wps_wait_eap_failure(hapd, dev[0])
8989
8990def test_wps_ext_m7_no_encr_settings(dev, apdev):
8991 """WPS proto: M7 without Encr Settings"""
8992 pin = "12345670"
8993 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8994 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8995 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8996
8997 logger.debug("Receive WSC/Start from AP")
8998 msg = get_wsc_msg(hapd)
8999 if msg['wsc_opcode'] != WSC_Start:
9000 raise Exception("Unexpected Op-Code for WSC/Start")
9001
9002 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9003 uuid_e = 16*'\x11'
9004 e_nonce = 16*'\x22'
9005 own_private, e_pk = wsc_dh_init()
9006
9007 logger.debug("Send M1 to AP")
9008 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9009 e_nonce, e_pk)
9010 send_wsc_msg(hapd, addr, m1)
9011
9012 logger.debug("Receive M2 from AP")
9013 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9014 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9015 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9016
9017 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9018 r_nonce)
9019 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9020
9021 logger.debug("Send M3 to AP")
9022 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9023 attrs += build_attr_msg_type(WPS_M3)
9024 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9025 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9026 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9027 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9028 raw_m3_attrs = attrs
9029 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9030 send_wsc_msg(hapd, addr, m3)
9031
9032 logger.debug("Receive M4 from AP")
9033 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9034
9035 logger.debug("Send M5 to AP")
9036 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9037 attrs += build_attr_msg_type(WPS_M5)
9038 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9039 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9040 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9041 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9042 raw_m5_attrs = attrs
9043 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9044 send_wsc_msg(hapd, addr, m5)
9045
9046 logger.debug("Receive M6 from AP")
9047 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9048
9049 logger.debug("Send M7 to AP")
9050 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9051 attrs += build_attr_msg_type(WPS_M7)
9052 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9053 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9054 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9055 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9056 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9057 raw_m7_attrs = attrs
9058 send_wsc_msg(hapd, addr, m7)
9059
9060 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
9061
9062def test_wps_ext_m1_workaround(dev, apdev):
9063 """WPS proto: M1 Manufacturer/Model workaround"""
9064 pin = "12345670"
9065 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9066 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9067 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9068
9069 logger.debug("Receive WSC/Start from AP")
9070 msg = get_wsc_msg(hapd)
9071 if msg['wsc_opcode'] != WSC_Start:
9072 raise Exception("Unexpected Op-Code for WSC/Start")
9073
9074 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9075 uuid_e = 16*'\x11'
9076 e_nonce = 16*'\x22'
9077 own_private, e_pk = wsc_dh_init()
9078
9079 logger.debug("Send M1 to AP")
9080 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9081 e_nonce, e_pk, manufacturer='Apple TEST',
9082 model_name='AirPort', config_methods='\xff\xff')
9083 send_wsc_msg(hapd, addr, m1)
9084
9085 logger.debug("Receive M2 from AP")
9086 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
53bd8653
JM
9087
9088def test_ap_wps_disable_enable(dev, apdev):
9089 """WPS and DISABLE/ENABLE AP"""
9090 hapd = wps_start_ap(apdev[0])
9091 hapd.disable()
9092 hapd.enable()
9093 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
dd124ee8
JM
9094
9095def test_ap_wps_upnp_web_oom(dev, apdev, params):
9096 """hostapd WPS UPnP web OOM"""
9097 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9098 hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
9099
9100 location = ssdp_get_location(ap_uuid)
9101 url = urlparse.urlparse(location)
9102 urls = upnp_get_urls(location)
9103 eventurl = urlparse.urlparse(urls['event_sub_url'])
9104 ctrlurl = urlparse.urlparse(urls['control_url'])
9105
9106 conn = httplib.HTTPConnection(url.netloc)
9107 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9108 conn.request("GET", "/wps_device.xml")
9109 try:
9110 resp = conn.getresponse()
9111 except:
9112 pass
9113
9114 conn = httplib.HTTPConnection(url.netloc)
9115 conn.request("GET", "/unknown")
9116 resp = conn.getresponse()
9117 if resp.status != 404:
9118 raise Exception("Unexpected HTTP result for unknown URL: %d" + resp.status)
9119
9120 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9121 conn.request("GET", "/unknown")
9122 try:
9123 resp = conn.getresponse()
9124 print resp.status
9125 except:
9126 pass
9127
9128 conn = httplib.HTTPConnection(url.netloc)
9129 conn.request("GET", "/wps_device.xml")
9130 resp = conn.getresponse()
9131 if resp.status != 200:
9132 raise Exception("GET /wps_device.xml failed")
9133
9134 conn = httplib.HTTPConnection(url.netloc)
9135 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9136 if resp.status != 200:
9137 raise Exception("GetDeviceInfo failed")
9138
9139 with alloc_fail(hapd, 1, "web_process_get_device_info"):
9140 conn = httplib.HTTPConnection(url.netloc)
9141 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9142 if resp.status != 500:
9143 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9144
9145 with alloc_fail(hapd, 1, "wps_build_m1;web_process_get_device_info"):
9146 conn = httplib.HTTPConnection(url.netloc)
9147 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9148 if resp.status != 500:
9149 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9150
9151 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_send_reply"):
9152 conn = httplib.HTTPConnection(url.netloc)
9153 try:
9154 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9155 except:
9156 pass
9157
9158 conn = httplib.HTTPConnection(url.netloc)
9159 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9160 if resp.status != 200:
9161 raise Exception("GetDeviceInfo failed")
9162
9163 # No NewWLANEventType in PutWLANResponse NewMessage
9164 conn = httplib.HTTPConnection(url.netloc)
9165 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse", newmsg="foo")
9166 if resp.status != 600:
9167 raise Exception("Unexpected HTTP response: %d" % resp.status)
9168
9169 # No NewWLANEventMAC in PutWLANResponse NewMessage
9170 conn = httplib.HTTPConnection(url.netloc)
9171 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9172 newmsg="foo", neweventtype="1")
9173 if resp.status != 600:
9174 raise Exception("Unexpected HTTP response: %d" % resp.status)
9175
9176 # Invalid NewWLANEventMAC in PutWLANResponse NewMessage
9177 conn = httplib.HTTPConnection(url.netloc)
9178 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9179 newmsg="foo", neweventtype="1",
9180 neweventmac="foo")
9181 if resp.status != 600:
9182 raise Exception("Unexpected HTTP response: %d" % resp.status)
9183
9184 # Workaround for NewWLANEventMAC in PutWLANResponse NewMessage
9185 # Ignored unexpected PutWLANResponse WLANEventType 1
9186 conn = httplib.HTTPConnection(url.netloc)
9187 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9188 newmsg="foo", neweventtype="1",
9189 neweventmac="00.11.22.33.44.55")
9190 if resp.status != 500:
9191 raise Exception("Unexpected HTTP response: %d" % resp.status)
9192
9193 # PutWLANResponse NewMessage with invalid EAP message
9194 conn = httplib.HTTPConnection(url.netloc)
9195 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9196 newmsg="foo", neweventtype="2",
9197 neweventmac="00:11:22:33:44:55")
9198 if resp.status != 200:
9199 raise Exception("Unexpected HTTP response: %d" % resp.status)
9200
9201 with alloc_fail(hapd, 1, "web_connection_parse_subscribe"):
9202 conn = httplib.HTTPConnection(url.netloc)
9203 headers = { "callback": '<http://127.0.0.1:12345/event>',
9204 "NT": "upnp:event",
9205 "timeout": "Second-1234" }
9206 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9207 try:
9208 resp = conn.getresponse()
9209 except:
9210 pass
9211
9212 with alloc_fail(hapd, 1, "dup_binstr;web_connection_parse_subscribe"):
9213 conn = httplib.HTTPConnection(url.netloc)
9214 headers = { "callback": '<http://127.0.0.1:12345/event>',
9215 "NT": "upnp:event",
9216 "timeout": "Second-1234" }
9217 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9218 resp = conn.getresponse()
9219 if resp.status != 500:
9220 raise Exception("Unexpected HTTP response: %d" % resp.status)
9221
9222 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_parse_unsubscribe"):
9223 conn = httplib.HTTPConnection(url.netloc)
9224 headers = { "callback": '<http://127.0.0.1:12345/event>',
9225 "NT": "upnp:event",
9226 "timeout": "Second-1234" }
9227 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9228 try:
9229 resp = conn.getresponse()
9230 except:
9231 pass
9232
9233 with alloc_fail(hapd, 1, "web_connection_unimplemented"):
9234 conn = httplib.HTTPConnection(url.netloc)
9235 conn.request("HEAD", "/wps_device.xml")
9236 try:
9237 resp = conn.getresponse()
9238 except:
9239 pass