]> git.ipfire.org Git - thirdparty/hostap.git/blame - tests/hwsim/test_ap_wps.py
WPS: Fix memory leak with wps_ie in wpa_bss_is_wps_candidate()
[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
1e35aa15 32from utils import wait_fail_trigger
d8e5a55f 33from test_ap_eap import int_eap_server_params
302b7a1b 34
24b7f282
JM
35def wps_start_ap(apdev, ssid="test-wps-conf"):
36 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
37 "wpa_passphrase": "12345678", "wpa": "2",
38 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
afc26df2 39 return hostapd.add_ap(apdev, params)
24b7f282 40
ae3ad328 41def test_ap_wps_init(dev, apdev):
302b7a1b
JM
42 """Initial AP configuration with first WPS Enrollee"""
43 ssid = "test-wps"
6f334bf7
JD
44 hapd = hostapd.add_ap(apdev[0],
45 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
302b7a1b
JM
46 logger.info("WPS provisioning step")
47 hapd.request("WPS_PBC")
d671a420
JM
48 if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
49 raise Exception("PBC status not shown correctly")
b9018833
JM
50
51 id = dev[0].add_network()
52 dev[0].set_network_quoted(id, "ssid", "home")
53 dev[0].set_network_quoted(id, "psk", "12345678")
54 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
55
56 id = dev[0].add_network()
57 dev[0].set_network_quoted(id, "ssid", "home2")
58 dev[0].set_network(id, "bssid", "00:11:22:33:44:55")
59 dev[0].set_network(id, "key_mgmt", "NONE")
60 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
61
302b7a1b 62 dev[0].request("WPS_PBC")
5f35a5e2 63 dev[0].wait_connected(timeout=30)
302b7a1b 64 status = dev[0].get_status()
ae3ad328 65 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
66 raise Exception("Not fully connected")
67 if status['ssid'] != ssid:
68 raise Exception("Unexpected SSID")
69 if status['pairwise_cipher'] != 'CCMP':
70 raise Exception("Unexpected encryption configuration")
71 if status['key_mgmt'] != 'WPA2-PSK':
72 raise Exception("Unexpected key_mgmt")
73
d671a420
JM
74 status = hapd.request("WPS_GET_STATUS")
75 if "PBC Status: Disabled" not in status:
76 raise Exception("PBC status not shown correctly")
77 if "Last WPS result: Success" not in status:
78 raise Exception("Last WPS result not shown correctly")
79 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
80 raise Exception("Peer address not shown correctly")
75b25ece
JM
81 conf = hapd.request("GET_CONFIG")
82 if "wps_state=configured" not in conf:
83 raise Exception("AP not in WPS configured state")
742408af
JM
84 if "wpa=3" not in conf:
85 raise Exception("AP not in WPA+WPA2 configuration")
75b25ece
JM
86 if "rsn_pairwise_cipher=CCMP TKIP" not in conf:
87 raise Exception("Unexpected rsn_pairwise_cipher")
88 if "wpa_pairwise_cipher=CCMP TKIP" not in conf:
89 raise Exception("Unexpected wpa_pairwise_cipher")
90 if "group_cipher=TKIP" not in conf:
91 raise Exception("Unexpected group_cipher")
d671a420 92
b9018833
JM
93 if len(dev[0].list_networks()) != 3:
94 raise Exception("Unexpected number of network blocks")
95
18030dc0
JM
96def test_ap_wps_init_2ap_pbc(dev, apdev):
97 """Initial two-radio AP configuration with first WPS PBC Enrollee"""
98 ssid = "test-wps"
99 params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
6f334bf7 100 hapd = hostapd.add_ap(apdev[0], params)
8b8a1864 101 hostapd.add_ap(apdev[1], params)
18030dc0
JM
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" }
6f334bf7 136 hapd = hostapd.add_ap(apdev[0], params)
8b8a1864 137 hostapd.add_ap(apdev[1], params)
18030dc0
JM
138 logger.info("WPS provisioning step")
139 pin = dev[0].wps_read_pin()
140 hapd.request("WPS_PIN any " + pin)
84a40841
JM
141 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
142 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
143 bss = dev[0].get_bss(apdev[0]['bssid'])
144 if "[WPS-AUTH]" not in bss['flags']:
145 raise Exception("WPS-AUTH flag missing from AP1")
146 bss = dev[0].get_bss(apdev[1]['bssid'])
147 if "[WPS-AUTH]" not in bss['flags']:
148 raise Exception("WPS-AUTH flag missing from AP2")
149 dev[0].dump_monitor()
150 dev[0].request("WPS_PIN any " + pin)
5f35a5e2 151 dev[0].wait_connected(timeout=30)
18030dc0 152
84a40841
JM
153 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
154 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
155 bss = dev[1].get_bss(apdev[0]['bssid'])
156 if "[WPS-AUTH]" in bss['flags']:
157 raise Exception("WPS-AUTH flag not cleared from AP1")
158 bss = dev[1].get_bss(apdev[1]['bssid'])
159 if "[WPS-AUTH]" in bss['flags']:
0bde923c 160 raise Exception("WPS-AUTH flag not cleared from AP2")
18030dc0 161
35831e94
JM
162def test_ap_wps_init_through_wps_config(dev, apdev):
163 """Initial AP configuration using wps_config command"""
164 ssid = "test-wps-init-config"
6f334bf7
JD
165 hapd = hostapd.add_ap(apdev[0],
166 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
35831e94
JM
167 if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
168 raise Exception("WPS_CONFIG command failed")
180cd73d
JM
169 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
170 if ev is None:
171 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
172 # It takes some time for the AP to update Beacon and Probe Response frames,
173 # so wait here before requesting the scan to be started to avoid adding
174 # extra five second wait to the test due to fetching obsolete scan results.
175 hapd.ping()
176 time.sleep(0.2)
35831e94
JM
177 dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
178 pairwise="CCMP", group="CCMP")
179
fbf6b717
JM
180def test_ap_wps_init_through_wps_config_2(dev, apdev):
181 """AP configuration using wps_config and wps_cred_processing=2"""
182 ssid = "test-wps-init-config"
6f334bf7
JD
183 hapd = hostapd.add_ap(apdev[0],
184 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
185 "wps_cred_processing": "2" })
fbf6b717
JM
186 if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
187 raise Exception("WPS_CONFIG command failed")
188 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
189 if ev is None:
190 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
191 if "100e" not in ev:
192 raise Exception("WPS-NEW-AP-SETTINGS did not include Credential")
193
e1eb0e9e
JM
194def test_ap_wps_invalid_wps_config_passphrase(dev, apdev):
195 """AP configuration using wps_config command with invalid passphrase"""
196 ssid = "test-wps-init-config"
6f334bf7
JD
197 hapd = hostapd.add_ap(apdev[0],
198 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
e1eb0e9e
JM
199 if "FAIL" not in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "1234567".encode("hex")):
200 raise Exception("Invalid WPS_CONFIG command accepted")
201
ae3ad328 202def test_ap_wps_conf(dev, apdev):
302b7a1b
JM
203 """WPS PBC provisioning with configured AP"""
204 ssid = "test-wps-conf"
6f334bf7
JD
205 hapd = hostapd.add_ap(apdev[0],
206 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
207 "wpa_passphrase": "12345678", "wpa": "2",
208 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
302b7a1b
JM
209 logger.info("WPS provisioning step")
210 hapd.request("WPS_PBC")
33d0b157 211 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 212 dev[0].dump_monitor()
33d0b157 213 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 214 dev[0].wait_connected(timeout=30)
302b7a1b 215 status = dev[0].get_status()
ae3ad328 216 if status['wpa_state'] != 'COMPLETED':
302b7a1b 217 raise Exception("Not fully connected")
ae3ad328
JM
218 if status['bssid'] != apdev[0]['bssid']:
219 raise Exception("Unexpected BSSID")
302b7a1b
JM
220 if status['ssid'] != ssid:
221 raise Exception("Unexpected SSID")
222 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
223 raise Exception("Unexpected encryption configuration")
224 if status['key_mgmt'] != 'WPA2-PSK':
225 raise Exception("Unexpected key_mgmt")
226
097cd9cd
JM
227 sta = hapd.get_sta(dev[0].p2p_interface_addr())
228 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
229 raise Exception("Device name not available in STA command")
230
daad14cc
JM
231def test_ap_wps_conf_5ghz(dev, apdev):
232 """WPS PBC provisioning with configured AP on 5 GHz band"""
233 try:
9d7fdac5 234 hapd = None
daad14cc
JM
235 ssid = "test-wps-conf"
236 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
237 "wpa_passphrase": "12345678", "wpa": "2",
238 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
239 "country_code": "FI", "hw_mode": "a", "channel": "36" }
8b8a1864 240 hapd = hostapd.add_ap(apdev[0], params)
daad14cc
JM
241 logger.info("WPS provisioning step")
242 hapd.request("WPS_PBC")
33d0b157
JM
243 dev[0].scan_for_bss(apdev[0]['bssid'], freq="5180")
244 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 245 dev[0].wait_connected(timeout=30)
daad14cc
JM
246
247 sta = hapd.get_sta(dev[0].p2p_interface_addr())
248 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
249 raise Exception("Device name not available in STA command")
250 finally:
9d7fdac5
JM
251 dev[0].request("DISCONNECT")
252 if hapd:
253 hapd.request("DISABLE")
c4668009 254 subprocess.call(['iw', 'reg', 'set', '00'])
9d7fdac5 255 dev[0].flush_scan_cache()
daad14cc
JM
256
257def test_ap_wps_conf_chan14(dev, apdev):
258 """WPS PBC provisioning with configured AP on channel 14"""
259 try:
9d7fdac5 260 hapd = None
daad14cc
JM
261 ssid = "test-wps-conf"
262 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
263 "wpa_passphrase": "12345678", "wpa": "2",
264 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
265 "country_code": "JP", "hw_mode": "b", "channel": "14" }
8b8a1864 266 hapd = hostapd.add_ap(apdev[0], params)
daad14cc
JM
267 logger.info("WPS provisioning step")
268 hapd.request("WPS_PBC")
269 dev[0].request("WPS_PBC")
5f35a5e2 270 dev[0].wait_connected(timeout=30)
daad14cc
JM
271
272 sta = hapd.get_sta(dev[0].p2p_interface_addr())
273 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
274 raise Exception("Device name not available in STA command")
275 finally:
9d7fdac5
JM
276 dev[0].request("DISCONNECT")
277 if hapd:
278 hapd.request("DISABLE")
c4668009 279 subprocess.call(['iw', 'reg', 'set', '00'])
9d7fdac5 280 dev[0].flush_scan_cache()
daad14cc 281
04e62788
JM
282def test_ap_wps_twice(dev, apdev):
283 """WPS provisioning with twice to change passphrase"""
284 ssid = "test-wps-twice"
285 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
286 "wpa_passphrase": "12345678", "wpa": "2",
287 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
01703a9f 288 hapd = hostapd.add_ap(apdev[0], params)
04e62788
JM
289 logger.info("WPS provisioning step")
290 hapd.request("WPS_PBC")
33d0b157 291 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
04e62788 292 dev[0].dump_monitor()
33d0b157 293 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 294 dev[0].wait_connected(timeout=30)
04e62788
JM
295 dev[0].request("DISCONNECT")
296
297 logger.info("Restart AP with different passphrase and re-run WPS")
01703a9f 298 hostapd.remove_bss(apdev[0])
04e62788 299 params['wpa_passphrase'] = 'another passphrase'
01703a9f 300 hapd = hostapd.add_ap(apdev[0], params)
04e62788
JM
301 logger.info("WPS provisioning step")
302 hapd.request("WPS_PBC")
303 dev[0].dump_monitor()
33d0b157 304 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 305 dev[0].wait_connected(timeout=30)
04e62788
JM
306 networks = dev[0].list_networks()
307 if len(networks) > 1:
308 raise Exception("Unexpected duplicated network block present")
309
d658205a
JM
310def test_ap_wps_incorrect_pin(dev, apdev):
311 """WPS PIN provisioning with incorrect PIN"""
312 ssid = "test-wps-incorrect-pin"
6f334bf7
JD
313 hapd = hostapd.add_ap(apdev[0],
314 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
315 "wpa_passphrase": "12345678", "wpa": "2",
316 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
d658205a
JM
317
318 logger.info("WPS provisioning attempt 1")
319 hapd.request("WPS_PIN any 12345670")
33d0b157 320 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
d658205a 321 dev[0].dump_monitor()
33d0b157 322 dev[0].request("WPS_PIN %s 55554444" % apdev[0]['bssid'])
d658205a
JM
323 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
324 if ev is None:
325 raise Exception("WPS operation timed out")
326 if "config_error=18" not in ev:
327 raise Exception("Incorrect config_error reported")
328 if "msg=8" not in ev:
329 raise Exception("PIN error detected on incorrect message")
5f35a5e2 330 dev[0].wait_disconnected(timeout=10)
d658205a
JM
331 dev[0].request("WPS_CANCEL")
332 # if a scan was in progress, wait for it to complete before trying WPS again
333 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
334
d671a420
JM
335 status = hapd.request("WPS_GET_STATUS")
336 if "Last WPS result: Failed" not in status:
337 raise Exception("WPS failure result not shown correctly")
338
d658205a
JM
339 logger.info("WPS provisioning attempt 2")
340 hapd.request("WPS_PIN any 12345670")
341 dev[0].dump_monitor()
33d0b157 342 dev[0].request("WPS_PIN %s 12344444" % apdev[0]['bssid'])
d658205a
JM
343 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
344 if ev is None:
345 raise Exception("WPS operation timed out")
346 if "config_error=18" not in ev:
347 raise Exception("Incorrect config_error reported")
348 if "msg=10" not in ev:
349 raise Exception("PIN error detected on incorrect message")
5f35a5e2 350 dev[0].wait_disconnected(timeout=10)
d658205a 351
ae3ad328 352def test_ap_wps_conf_pin(dev, apdev):
302b7a1b
JM
353 """WPS PIN provisioning with configured AP"""
354 ssid = "test-wps-conf-pin"
6f334bf7
JD
355 hapd = hostapd.add_ap(apdev[0],
356 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
357 "wpa_passphrase": "12345678", "wpa": "2",
358 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
302b7a1b
JM
359 logger.info("WPS provisioning step")
360 pin = dev[0].wps_read_pin()
361 hapd.request("WPS_PIN any " + pin)
33d0b157 362 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 363 dev[0].dump_monitor()
33d0b157 364 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 365 dev[0].wait_connected(timeout=30)
302b7a1b 366 status = dev[0].get_status()
ae3ad328 367 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
368 raise Exception("Not fully connected")
369 if status['ssid'] != ssid:
370 raise Exception("Unexpected SSID")
371 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
372 raise Exception("Unexpected encryption configuration")
373 if status['key_mgmt'] != 'WPA2-PSK':
374 raise Exception("Unexpected key_mgmt")
375
84a40841 376 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
362ba6de
JM
377 bss = dev[1].get_bss(apdev[0]['bssid'])
378 if "[WPS-AUTH]" in bss['flags']:
379 raise Exception("WPS-AUTH flag not cleared")
a60a6d6b 380 logger.info("Try to connect from another station using the same PIN")
33d0b157 381 pin = dev[1].request("WPS_PIN " + apdev[0]['bssid'])
a60a6d6b
JM
382 ev = dev[1].wait_event(["WPS-M2D","CTRL-EVENT-CONNECTED"], timeout=30)
383 if ev is None:
384 raise Exception("Operation timed out")
385 if "WPS-M2D" not in ev:
386 raise Exception("Unexpected WPS operation started")
6e12eaa4 387 hapd.request("WPS_PIN any " + pin)
5f35a5e2 388 dev[1].wait_connected(timeout=30)
362ba6de 389
ff518fbd
JM
390def test_ap_wps_conf_pin_mixed_mode(dev, apdev):
391 """WPS PIN provisioning with configured AP (WPA+WPA2)"""
392 ssid = "test-wps-conf-pin-mixed"
6f334bf7
JD
393 hapd = hostapd.add_ap(apdev[0],
394 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
395 "wpa_passphrase": "12345678", "wpa": "3",
396 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
397 "wpa_pairwise": "TKIP" })
ff518fbd
JM
398
399 logger.info("WPS provisioning step")
400 pin = dev[0].wps_read_pin()
401 hapd.request("WPS_PIN any " + pin)
402 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
403 dev[0].dump_monitor()
404 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
405 dev[0].wait_connected(timeout=30)
406 status = dev[0].get_status()
407 dev[0].request("REMOVE_NETWORK all")
408 dev[0].wait_disconnected()
409 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
410 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
411
412 logger.info("WPS provisioning step (auth_types=0x1b)")
413 if "OK" not in dev[0].request("SET wps_force_auth_types 0x1b"):
414 raise Exception("Failed to set wps_force_auth_types 0x1b")
415 pin = dev[0].wps_read_pin()
416 hapd.request("WPS_PIN any " + pin)
417 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
418 dev[0].dump_monitor()
419 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
420 dev[0].wait_connected(timeout=30)
421 status = dev[0].get_status()
422 dev[0].request("REMOVE_NETWORK all")
423 dev[0].wait_disconnected()
424 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
425 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
426
427 logger.info("WPS provisioning step (auth_types=0 encr_types=0)")
428 if "OK" not in dev[0].request("SET wps_force_auth_types 0"):
429 raise Exception("Failed to set wps_force_auth_types 0")
430 if "OK" not in dev[0].request("SET wps_force_encr_types 0"):
431 raise Exception("Failed to set wps_force_encr_types 0")
432 pin = dev[0].wps_read_pin()
433 hapd.request("WPS_PIN any " + pin)
434 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
435 dev[0].dump_monitor()
436 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
437 dev[0].wait_connected(timeout=30)
438 status = dev[0].get_status()
439 dev[0].request("REMOVE_NETWORK all")
440 dev[0].wait_disconnected()
441 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
442 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
443
444 dev[0].request("SET wps_force_auth_types ")
445 dev[0].request("SET wps_force_encr_types ")
446
6257f9c0
JM
447def test_ap_wps_conf_pin_v1(dev, apdev):
448 """WPS PIN provisioning with configured WPS v1.0 AP"""
449 ssid = "test-wps-conf-pin-v1"
6f334bf7
JD
450 hapd = hostapd.add_ap(apdev[0],
451 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
452 "wpa_passphrase": "12345678", "wpa": "2",
453 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
6257f9c0
JM
454 logger.info("WPS provisioning step")
455 pin = dev[0].wps_read_pin()
456 hapd.request("SET wps_version_number 0x10")
457 hapd.request("WPS_PIN any " + pin)
458 found = False
459 for i in range(0, 10):
460 dev[0].scan(freq="2412")
461 if "[WPS-PIN]" in dev[0].request("SCAN_RESULTS"):
462 found = True
463 break
464 if not found:
465 hapd.request("SET wps_version_number 0x20")
466 raise Exception("WPS-PIN flag not seen in scan results")
467 dev[0].dump_monitor()
33d0b157 468 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 469 dev[0].wait_connected(timeout=30)
6257f9c0 470 hapd.request("SET wps_version_number 0x20")
6257f9c0 471
e9129860
JM
472def test_ap_wps_conf_pin_2sta(dev, apdev):
473 """Two stations trying to use WPS PIN at the same time"""
474 ssid = "test-wps-conf-pin2"
6f334bf7
JD
475 hapd = hostapd.add_ap(apdev[0],
476 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
477 "wpa_passphrase": "12345678", "wpa": "2",
478 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e9129860
JM
479 logger.info("WPS provisioning step")
480 pin = "12345670"
481 pin2 = "55554444"
482 hapd.request("WPS_PIN " + dev[0].get_status_field("uuid") + " " + pin)
483 hapd.request("WPS_PIN " + dev[1].get_status_field("uuid") + " " + pin)
e9129860 484 dev[0].dump_monitor()
e9129860 485 dev[1].dump_monitor()
33d0b157
JM
486 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
487 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
488 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
489 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2
JM
490 dev[0].wait_connected(timeout=30)
491 dev[1].wait_connected(timeout=30)
0489e880
JM
492
493def test_ap_wps_conf_pin_timeout(dev, apdev):
494 """WPS PIN provisioning with configured AP timing out PIN"""
495 ssid = "test-wps-conf-pin"
6f334bf7
JD
496 hapd = hostapd.add_ap(apdev[0],
497 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
498 "wpa_passphrase": "12345678", "wpa": "2",
499 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
0489e880
JM
500 addr = dev[0].p2p_interface_addr()
501 pin = dev[0].wps_read_pin()
502 if "FAIL" not in hapd.request("WPS_PIN "):
503 raise Exception("Unexpected success on invalid WPS_PIN")
504 hapd.request("WPS_PIN any " + pin + " 1")
33d0b157 505 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
0489e880 506 time.sleep(1.1)
33d0b157 507 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
0489e880
JM
508 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=20)
509 if ev is None:
510 raise Exception("WPS-PIN-NEEDED event timed out")
511 ev = dev[0].wait_event(["WPS-M2D"])
512 if ev is None:
513 raise Exception("M2D not reported")
514 dev[0].request("WPS_CANCEL")
515
516 hapd.request("WPS_PIN any " + pin + " 20 " + addr)
33d0b157 517 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 518 dev[0].wait_connected(timeout=30)
e9129860 519
ae3ad328 520def test_ap_wps_reg_connect(dev, apdev):
302b7a1b 521 """WPS registrar using AP PIN to connect"""
803edd1c 522 ssid = "test-wps-reg-ap-pin"
302b7a1b 523 appin = "12345670"
8b8a1864 524 hostapd.add_ap(apdev[0],
302b7a1b
JM
525 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
526 "wpa_passphrase": "12345678", "wpa": "2",
527 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
528 "ap_pin": appin})
529 logger.info("WPS provisioning step")
302b7a1b 530 dev[0].dump_monitor()
33d0b157 531 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 532 dev[0].wps_reg(apdev[0]['bssid'], appin)
302b7a1b 533 status = dev[0].get_status()
ae3ad328 534 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
535 raise Exception("Not fully connected")
536 if status['ssid'] != ssid:
537 raise Exception("Unexpected SSID")
538 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
539 raise Exception("Unexpected encryption configuration")
540 if status['key_mgmt'] != 'WPA2-PSK':
541 raise Exception("Unexpected key_mgmt")
542
e60be3b3
JM
543def test_ap_wps_reg_connect_mixed_mode(dev, apdev):
544 """WPS registrar using AP PIN to connect (WPA+WPA2)"""
545 ssid = "test-wps-reg-ap-pin"
546 appin = "12345670"
8b8a1864 547 hostapd.add_ap(apdev[0],
e60be3b3
JM
548 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
549 "wpa_passphrase": "12345678", "wpa": "3",
550 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
551 "wpa_pairwise": "TKIP", "ap_pin": appin})
552 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
553 dev[0].wps_reg(apdev[0]['bssid'], appin)
554 status = dev[0].get_status()
555 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
556 raise Exception("Not fully connected")
557 if status['ssid'] != ssid:
558 raise Exception("Unexpected SSID")
559 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
560 raise Exception("Unexpected encryption configuration")
561 if status['key_mgmt'] != 'WPA2-PSK':
562 raise Exception("Unexpected key_mgmt")
563
7511ead0
JM
564def test_ap_wps_reg_override_ap_settings(dev, apdev):
565 """WPS registrar and ap_settings override"""
566 ap_settings = "/tmp/ap_wps_reg_override_ap_settings"
567 try:
568 os.remove(ap_settings)
569 except:
570 pass
571 # Override AP Settings with values that point to another AP
572 data = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
573 data += build_wsc_attr(ATTR_SSID, "test")
574 data += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
575 data += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
576 data += build_wsc_attr(ATTR_NETWORK_KEY, '')
577 data += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[1]['bssid'].replace(':', '')))
578 with open(ap_settings, "w") as f:
579 f.write(data)
580 ssid = "test-wps-reg-ap-pin"
581 appin = "12345670"
8b8a1864 582 hostapd.add_ap(apdev[0],
7511ead0
JM
583 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
584 "wpa_passphrase": "12345678", "wpa": "2",
585 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
586 "ap_pin": appin, "ap_settings": ap_settings })
8b8a1864 587 hapd2 = hostapd.add_ap(apdev[1], { "ssid": "test" })
7511ead0
JM
588 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
589 dev[0].scan_for_bss(apdev[1]['bssid'], freq=2412)
590 dev[0].wps_reg(apdev[0]['bssid'], appin)
591 ev = hapd2.wait_event(['AP-STA-CONNECTED'], timeout=10)
592 os.remove(ap_settings)
593 if ev is None:
594 raise Exception("No connection with the other AP")
595
9488858f
JM
596def check_wps_reg_failure(dev, ap, appin):
597 dev.request("WPS_REG " + ap['bssid'] + " " + appin)
598 ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
599 if ev is None:
600 raise Exception("WPS operation timed out")
601 if "WPS-SUCCESS" in ev:
602 raise Exception("WPS operation succeeded unexpectedly")
603 if "config_error=15" not in ev:
604 raise Exception("WPS setup locked state was not reported correctly")
605
e4357b19
JM
606def test_ap_wps_random_ap_pin(dev, apdev):
607 """WPS registrar using random AP PIN"""
608 ssid = "test-wps-reg-random-ap-pin"
609 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
6f334bf7
JD
610 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
611 "wpa_passphrase": "12345678", "wpa": "2",
612 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
613 "device_name": "Wireless AP", "manufacturer": "Company",
614 "model_name": "WAP", "model_number": "123",
615 "serial_number": "12345", "device_type": "6-0050F204-1",
616 "os_version": "01020300",
617 "config_methods": "label push_button",
618 "uuid": ap_uuid, "upnp_iface": "lo" }
619 hapd = hostapd.add_ap(apdev[0], params)
e4357b19
JM
620 appin = hapd.request("WPS_AP_PIN random")
621 if "FAIL" in appin:
622 raise Exception("Could not generate random AP PIN")
623 if appin not in hapd.request("WPS_AP_PIN get"):
624 raise Exception("Could not fetch current AP PIN")
625 logger.info("WPS provisioning step")
33d0b157 626 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
e4357b19
JM
627 dev[0].wps_reg(apdev[0]['bssid'], appin)
628
629 hapd.request("WPS_AP_PIN disable")
630 logger.info("WPS provisioning step with AP PIN disabled")
33d0b157 631 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
9488858f
JM
632 check_wps_reg_failure(dev[1], apdev[0], appin)
633
634 logger.info("WPS provisioning step with AP PIN reset")
635 appin = "12345670"
636 hapd.request("WPS_AP_PIN set " + appin)
637 dev[1].wps_reg(apdev[0]['bssid'], appin)
638 dev[0].request("REMOVE_NETWORK all")
639 dev[1].request("REMOVE_NETWORK all")
5f35a5e2
JM
640 dev[0].wait_disconnected(timeout=10)
641 dev[1].wait_disconnected(timeout=10)
9488858f
JM
642
643 logger.info("WPS provisioning step after AP PIN timeout")
644 hapd.request("WPS_AP_PIN disable")
645 appin = hapd.request("WPS_AP_PIN random 1")
646 time.sleep(1.1)
647 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
648 raise Exception("AP PIN unexpectedly still enabled")
649 check_wps_reg_failure(dev[0], apdev[0], appin)
650
651 logger.info("WPS provisioning step after AP PIN timeout(2)")
652 hapd.request("WPS_AP_PIN disable")
653 appin = "12345670"
654 hapd.request("WPS_AP_PIN set " + appin + " 1")
655 time.sleep(1.1)
656 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
657 raise Exception("AP PIN unexpectedly still enabled")
658 check_wps_reg_failure(dev[1], apdev[0], appin)
e4357b19 659
24b7f282 660 with fail_test(hapd, 1, "os_get_random;wps_generate_pin"):
20c48fd9 661 hapd.request("WPS_AP_PIN random 1")
24b7f282
JM
662 hapd.request("WPS_AP_PIN disable")
663
664 with alloc_fail(hapd, 1, "upnp_wps_set_ap_pin"):
665 hapd.request("WPS_AP_PIN set 12345670")
666 hapd.request("WPS_AP_PIN disable")
667
ae3ad328 668def test_ap_wps_reg_config(dev, apdev):
4b727c5c 669 """WPS registrar configuring an AP using AP PIN"""
302b7a1b
JM
670 ssid = "test-wps-init-ap-pin"
671 appin = "12345670"
8b8a1864 672 hostapd.add_ap(apdev[0],
302b7a1b
JM
673 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
674 "ap_pin": appin})
675 logger.info("WPS configuration step")
33d0b157 676 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
302b7a1b
JM
677 dev[0].dump_monitor()
678 new_ssid = "wps-new-ssid"
679 new_passphrase = "1234567890"
6edaee9c
JM
680 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
681 new_passphrase)
302b7a1b 682 status = dev[0].get_status()
ae3ad328 683 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
684 raise Exception("Not fully connected")
685 if status['ssid'] != new_ssid:
686 raise Exception("Unexpected SSID")
687 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
688 raise Exception("Unexpected encryption configuration")
689 if status['key_mgmt'] != 'WPA2-PSK':
690 raise Exception("Unexpected key_mgmt")
691
375afd7c
JM
692 logger.info("Re-configure back to open")
693 dev[0].request("REMOVE_NETWORK all")
243dcc4a 694 dev[0].flush_scan_cache()
375afd7c
JM
695 dev[0].dump_monitor()
696 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-open", "OPEN", "NONE", "")
697 status = dev[0].get_status()
698 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
699 raise Exception("Not fully connected")
700 if status['ssid'] != "wps-open":
701 raise Exception("Unexpected SSID")
702 if status['key_mgmt'] != 'NONE':
703 raise Exception("Unexpected key_mgmt")
704
4b727c5c
JM
705def test_ap_wps_reg_config_ext_processing(dev, apdev):
706 """WPS registrar configuring an AP with external config processing"""
707 ssid = "test-wps-init-ap-pin"
708 appin = "12345670"
709 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
710 "wps_cred_processing": "1", "ap_pin": appin}
8b8a1864 711 hapd = hostapd.add_ap(apdev[0], params)
33d0b157 712 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
4b727c5c
JM
713 new_ssid = "wps-new-ssid"
714 new_passphrase = "1234567890"
715 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
716 new_passphrase, no_wait=True)
717 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
718 if ev is None:
719 raise Exception("WPS registrar operation timed out")
720 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=15)
721 if ev is None:
722 raise Exception("WPS configuration timed out")
723 if "1026" not in ev:
724 raise Exception("AP Settings missing from event")
725 hapd.request("SET wps_cred_processing 0")
726 if "FAIL" in hapd.request("WPS_CONFIG " + new_ssid.encode("hex") + " WPA2PSK CCMP " + new_passphrase.encode("hex")):
727 raise Exception("WPS_CONFIG command failed")
5f35a5e2 728 dev[0].wait_connected(timeout=15)
4b727c5c 729
eeefe187
JM
730def test_ap_wps_reg_config_tkip(dev, apdev):
731 """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
a1eabc74 732 skip_with_fips(dev[0])
eeefe187
JM
733 ssid = "test-wps-init-ap"
734 appin = "12345670"
8b8a1864 735 hostapd.add_ap(apdev[0],
eeefe187
JM
736 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
737 "ap_pin": appin})
738 logger.info("WPS configuration step")
eeefe187 739 dev[0].request("SET wps_version_number 0x10")
33d0b157 740 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
eeefe187
JM
741 dev[0].dump_monitor()
742 new_ssid = "wps-new-ssid-with-tkip"
743 new_passphrase = "1234567890"
744 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
745 new_passphrase)
746 logger.info("Re-connect to verify WPA2 mixed mode")
747 dev[0].request("DISCONNECT")
748 id = 0
749 dev[0].set_network(id, "pairwise", "CCMP")
750 dev[0].set_network(id, "proto", "RSN")
751 dev[0].connect_network(id)
752 status = dev[0].get_status()
753 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
3c086180 754 raise Exception("Not fully connected: wpa_state={} bssid={}".format(status['wpa_state'], status['bssid']))
eeefe187
JM
755 if status['ssid'] != new_ssid:
756 raise Exception("Unexpected SSID")
757 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
758 raise Exception("Unexpected encryption configuration")
759 if status['key_mgmt'] != 'WPA2-PSK':
760 raise Exception("Unexpected key_mgmt")
761
6645ff50
JM
762def test_ap_wps_setup_locked(dev, apdev):
763 """WPS registrar locking up AP setup on AP PIN failures"""
764 ssid = "test-wps-incorrect-ap-pin"
765 appin = "12345670"
6f334bf7
JD
766 hapd = hostapd.add_ap(apdev[0],
767 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
768 "wpa_passphrase": "12345678", "wpa": "2",
769 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
770 "ap_pin": appin})
6645ff50
JM
771 new_ssid = "wps-new-ssid-test"
772 new_passphrase = "1234567890"
773
33d0b157 774 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6645ff50
JM
775 ap_setup_locked=False
776 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
777 dev[0].dump_monitor()
778 logger.info("Try incorrect AP PIN - attempt " + pin)
779 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
780 "CCMP", new_passphrase, no_wait=True)
781 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
782 if ev is None:
783 raise Exception("Timeout on receiving WPS operation failure event")
784 if "CTRL-EVENT-CONNECTED" in ev:
785 raise Exception("Unexpected connection")
786 if "config_error=15" in ev:
787 logger.info("AP Setup Locked")
788 ap_setup_locked=True
789 elif "config_error=18" not in ev:
790 raise Exception("config_error=18 not reported")
5f35a5e2 791 dev[0].wait_disconnected(timeout=10)
6645ff50
JM
792 time.sleep(0.1)
793 if not ap_setup_locked:
794 raise Exception("AP setup was not locked")
24b7f282
JM
795 dev[0].request("WPS_CANCEL")
796 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True,
797 only_new=True)
798 bss = dev[0].get_bss(apdev[0]['bssid'])
799 if 'wps_ap_setup_locked' not in bss or bss['wps_ap_setup_locked'] != '1':
800 logger.info("BSS: " + str(bss))
801 raise Exception("AP Setup Locked not indicated in scan results")
6645ff50 802
d671a420
JM
803 status = hapd.request("WPS_GET_STATUS")
804 if "Last WPS result: Failed" not in status:
805 raise Exception("WPS failure result not shown correctly")
806 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
807 raise Exception("Peer address not shown correctly")
808
6645ff50
JM
809 time.sleep(0.5)
810 dev[0].dump_monitor()
811 logger.info("WPS provisioning step")
812 pin = dev[0].wps_read_pin()
6645ff50 813 hapd.request("WPS_PIN any " + pin)
33d0b157 814 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
6645ff50
JM
815 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
816 if ev is None:
817 raise Exception("WPS success was not reported")
5f35a5e2 818 dev[0].wait_connected(timeout=30)
6645ff50 819
c1cec68b
JM
820 appin = hapd.request("WPS_AP_PIN random")
821 if "FAIL" in appin:
822 raise Exception("Could not generate random AP PIN")
823 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=10)
824 if ev is None:
825 raise Exception("Failed to unlock AP PIN")
826
33c9b8d8
JM
827def test_ap_wps_setup_locked_timeout(dev, apdev):
828 """WPS re-enabling AP PIN after timeout"""
829 ssid = "test-wps-incorrect-ap-pin"
830 appin = "12345670"
6f334bf7
JD
831 hapd = hostapd.add_ap(apdev[0],
832 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
833 "wpa_passphrase": "12345678", "wpa": "2",
834 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
835 "ap_pin": appin})
33c9b8d8
JM
836 new_ssid = "wps-new-ssid-test"
837 new_passphrase = "1234567890"
838
33d0b157 839 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
33c9b8d8
JM
840 ap_setup_locked=False
841 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
842 dev[0].dump_monitor()
843 logger.info("Try incorrect AP PIN - attempt " + pin)
844 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
845 "CCMP", new_passphrase, no_wait=True)
9ed53f5e 846 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"], timeout=15)
33c9b8d8
JM
847 if ev is None:
848 raise Exception("Timeout on receiving WPS operation failure event")
849 if "CTRL-EVENT-CONNECTED" in ev:
850 raise Exception("Unexpected connection")
851 if "config_error=15" in ev:
852 logger.info("AP Setup Locked")
853 ap_setup_locked=True
854 break
855 elif "config_error=18" not in ev:
856 raise Exception("config_error=18 not reported")
5f35a5e2 857 dev[0].wait_disconnected(timeout=10)
33c9b8d8
JM
858 time.sleep(0.1)
859 if not ap_setup_locked:
860 raise Exception("AP setup was not locked")
33c9b8d8
JM
861 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=80)
862 if ev is None:
863 raise Exception("AP PIN did not get unlocked on 60 second timeout")
864
4c355e3e
JM
865def test_ap_wps_setup_locked_2(dev, apdev):
866 """WPS AP configured for special ap_setup_locked=2 mode"""
867 ssid = "test-wps-ap-pin"
868 appin = "12345670"
869 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
870 "wpa_passphrase": "12345678", "wpa": "2",
871 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
872 "ap_pin": appin, "ap_setup_locked": "2" }
8b8a1864 873 hapd = hostapd.add_ap(apdev[0], params)
4c355e3e
JM
874 new_ssid = "wps-new-ssid-test"
875 new_passphrase = "1234567890"
876
877 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
878 dev[0].wps_reg(apdev[0]['bssid'], appin)
879 dev[0].request("REMOVE_NETWORK all")
880 dev[0].wait_disconnected()
881
882 hapd.dump_monitor()
883 dev[0].dump_monitor()
884 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK",
885 "CCMP", new_passphrase, no_wait=True)
886
887 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
888 if ev is None:
889 raise Exception("hostapd did not report WPS failure")
890 if "msg=12 config_error=15" not in ev:
891 raise Exception("Unexpected failure reason (AP): " + ev)
892
893 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
894 if ev is None:
895 raise Exception("Timeout on receiving WPS operation failure event")
896 if "CTRL-EVENT-CONNECTED" in ev:
897 raise Exception("Unexpected connection")
898 if "config_error=15" not in ev:
899 raise Exception("Unexpected failure reason (STA): " + ev)
900 dev[0].request("WPS_CANCEL")
901 dev[0].wait_disconnected()
902
ae3ad328 903def test_ap_wps_pbc_overlap_2ap(dev, apdev):
302b7a1b 904 """WPS PBC session overlap with two active APs"""
6f334bf7
JD
905 params = { "ssid": "wps1", "eap_server": "1", "wps_state": "2",
906 "wpa_passphrase": "12345678", "wpa": "2",
907 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
908 "wps_independent": "1"}
909 hapd = hostapd.add_ap(apdev[0], params)
910 params = { "ssid": "wps2", "eap_server": "1", "wps_state": "2",
911 "wpa_passphrase": "123456789", "wpa": "2",
912 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
913 "wps_independent": "1"}
914 hapd2 = hostapd.add_ap(apdev[1], params)
302b7a1b 915 hapd.request("WPS_PBC")
302b7a1b
JM
916 hapd2.request("WPS_PBC")
917 logger.info("WPS provisioning step")
84a40841
JM
918 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
919 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
302b7a1b
JM
920 dev[0].request("WPS_PBC")
921 ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
922 if ev is None:
923 raise Exception("PBC session overlap not detected")
492c3a91
JM
924 hapd.request("DISABLE")
925 hapd2.request("DISABLE")
926 dev[0].flush_scan_cache()
302b7a1b 927
ae3ad328 928def test_ap_wps_pbc_overlap_2sta(dev, apdev):
302b7a1b
JM
929 """WPS PBC session overlap with two active STAs"""
930 ssid = "test-wps-pbc-overlap"
6f334bf7
JD
931 hapd = hostapd.add_ap(apdev[0],
932 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
933 "wpa_passphrase": "12345678", "wpa": "2",
934 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
302b7a1b
JM
935 logger.info("WPS provisioning step")
936 hapd.request("WPS_PBC")
33d0b157 937 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 938 dev[0].dump_monitor()
33d0b157 939 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 940 dev[1].dump_monitor()
33d0b157
JM
941 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
942 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
302b7a1b
JM
943 ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
944 if ev is None:
945 raise Exception("PBC session overlap not detected (dev0)")
946 if "config_error=12" not in ev:
947 raise Exception("PBC session overlap not correctly reported (dev0)")
492c3a91
JM
948 dev[0].request("WPS_CANCEL")
949 dev[0].request("DISCONNECT")
302b7a1b
JM
950 ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
951 if ev is None:
952 raise Exception("PBC session overlap not detected (dev1)")
953 if "config_error=12" not in ev:
954 raise Exception("PBC session overlap not correctly reported (dev1)")
492c3a91
JM
955 dev[1].request("WPS_CANCEL")
956 dev[1].request("DISCONNECT")
11e7eeba
JM
957 hapd.request("WPS_CANCEL")
958 ret = hapd.request("WPS_PBC")
959 if "FAIL" not in ret:
960 raise Exception("PBC mode allowed to be started while PBC overlap still active")
492c3a91
JM
961 hapd.request("DISABLE")
962 dev[0].flush_scan_cache()
963 dev[1].flush_scan_cache()
6edaee9c 964
71afe834
JM
965def test_ap_wps_cancel(dev, apdev):
966 """WPS AP cancelling enabled config method"""
967 ssid = "test-wps-ap-cancel"
6f334bf7
JD
968 hapd = hostapd.add_ap(apdev[0],
969 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
970 "wpa_passphrase": "12345678", "wpa": "2",
971 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
71afe834 972 bssid = apdev[0]['bssid']
71afe834
JM
973
974 logger.info("Verify PBC enable/cancel")
975 hapd.request("WPS_PBC")
71afe834 976 dev[0].scan(freq="2412")
84a40841 977 dev[0].scan(freq="2412")
71afe834
JM
978 bss = dev[0].get_bss(apdev[0]['bssid'])
979 if "[WPS-PBC]" not in bss['flags']:
980 raise Exception("WPS-PBC flag missing")
981 if "FAIL" in hapd.request("WPS_CANCEL"):
982 raise Exception("WPS_CANCEL failed")
983 dev[0].scan(freq="2412")
84a40841 984 dev[0].scan(freq="2412")
71afe834
JM
985 bss = dev[0].get_bss(apdev[0]['bssid'])
986 if "[WPS-PBC]" in bss['flags']:
987 raise Exception("WPS-PBC flag not cleared")
988
989 logger.info("Verify PIN enable/cancel")
990 hapd.request("WPS_PIN any 12345670")
991 dev[0].scan(freq="2412")
84a40841 992 dev[0].scan(freq="2412")
71afe834
JM
993 bss = dev[0].get_bss(apdev[0]['bssid'])
994 if "[WPS-AUTH]" not in bss['flags']:
995 raise Exception("WPS-AUTH flag missing")
996 if "FAIL" in hapd.request("WPS_CANCEL"):
997 raise Exception("WPS_CANCEL failed")
998 dev[0].scan(freq="2412")
84a40841 999 dev[0].scan(freq="2412")
71afe834
JM
1000 bss = dev[0].get_bss(apdev[0]['bssid'])
1001 if "[WPS-AUTH]" in bss['flags']:
1002 raise Exception("WPS-AUTH flag not cleared")
1003
6edaee9c
JM
1004def test_ap_wps_er_add_enrollee(dev, apdev):
1005 """WPS ER configuring AP and adding a new enrollee using PIN"""
be9f1562
JM
1006 try:
1007 _test_ap_wps_er_add_enrollee(dev, apdev)
1008 finally:
1009 dev[0].request("WPS_ER_STOP")
1010
1011def _test_ap_wps_er_add_enrollee(dev, apdev):
6edaee9c
JM
1012 ssid = "wps-er-add-enrollee"
1013 ap_pin = "12345670"
1014 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1015 hostapd.add_ap(apdev[0],
6edaee9c
JM
1016 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
1017 "device_name": "Wireless AP", "manufacturer": "Company",
1018 "model_name": "WAP", "model_number": "123",
1019 "serial_number": "12345", "device_type": "6-0050F204-1",
1020 "os_version": "01020300",
24b7f282 1021 'friendly_name': "WPS AP - <>&'\" - TEST",
6edaee9c
JM
1022 "config_methods": "label push_button",
1023 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1024 logger.info("WPS configuration step")
1025 new_passphrase = "1234567890"
1026 dev[0].dump_monitor()
33d0b157 1027 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c
JM
1028 dev[0].wps_reg(apdev[0]['bssid'], ap_pin, ssid, "WPA2PSK", "CCMP",
1029 new_passphrase)
1030 status = dev[0].get_status()
1031 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1032 raise Exception("Not fully connected")
1033 if status['ssid'] != ssid:
1034 raise Exception("Unexpected SSID")
1035 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
1036 raise Exception("Unexpected encryption configuration")
1037 if status['key_mgmt'] != 'WPA2-PSK':
1038 raise Exception("Unexpected key_mgmt")
1039
1040 logger.info("Start ER")
1041 dev[0].request("WPS_ER_START ifname=lo")
1042 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1043 if ev is None:
1044 raise Exception("AP discovery timed out")
1045 if ap_uuid not in ev:
1046 raise Exception("Expected AP UUID not found")
24b7f282
JM
1047 if "|WPS AP - &lt;&gt;&amp;&apos;&quot; - TEST|Company|" not in ev:
1048 raise Exception("Expected friendly name not found")
6edaee9c
JM
1049
1050 logger.info("Learn AP configuration through UPnP")
1051 dev[0].dump_monitor()
1052 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1053 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1054 if ev is None:
1055 raise Exception("AP learn timed out")
1056 if ap_uuid not in ev:
1057 raise Exception("Expected AP UUID not in settings")
1058 if "ssid=" + ssid not in ev:
1059 raise Exception("Expected SSID not in settings")
1060 if "key=" + new_passphrase not in ev:
1061 raise Exception("Expected passphrase not in settings")
33d0b157
JM
1062 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1063 if ev is None:
1064 raise Exception("WPS-FAIL after AP learn timed out")
1065 time.sleep(0.1)
6edaee9c
JM
1066
1067 logger.info("Add Enrollee using ER")
1068 pin = dev[1].wps_read_pin()
1069 dev[0].dump_monitor()
1070 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
33d0b157 1071 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 1072 dev[1].dump_monitor()
33d0b157 1073 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
846be889 1074 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
6edaee9c
JM
1075 if ev is None:
1076 raise Exception("Enrollee did not report success")
5f35a5e2 1077 dev[1].wait_connected(timeout=15)
6edaee9c
JM
1078 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1079 if ev is None:
1080 raise Exception("WPS ER did not report success")
1081 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1082
11c26f1b
JM
1083 logger.info("Add a specific Enrollee using ER")
1084 pin = dev[2].wps_read_pin()
1085 addr2 = dev[2].p2p_interface_addr()
1086 dev[0].dump_monitor()
33d0b157 1087 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
11c26f1b 1088 dev[2].dump_monitor()
33d0b157 1089 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
11c26f1b
JM
1090 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1091 if ev is None:
1092 raise Exception("Enrollee not seen")
1093 if addr2 not in ev:
1094 raise Exception("Unexpected Enrollee MAC address")
1095 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
5f35a5e2 1096 dev[2].wait_connected(timeout=30)
11c26f1b
JM
1097 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1098 if ev is None:
1099 raise Exception("WPS ER did not report success")
1100
38ae43de
JM
1101 logger.info("Verify registrar selection behavior")
1102 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1103 dev[1].request("DISCONNECT")
5f35a5e2 1104 dev[1].wait_disconnected(timeout=10)
84a40841 1105 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
38ae43de
JM
1106 dev[1].scan(freq="2412")
1107 bss = dev[1].get_bss(apdev[0]['bssid'])
1108 if "[WPS-AUTH]" not in bss['flags']:
321c7f60
JM
1109 # It is possible for scan to miss an update especially when running
1110 # tests under load with multiple VMs, so allow another attempt.
1111 dev[1].scan(freq="2412")
1112 bss = dev[1].get_bss(apdev[0]['bssid'])
1113 if "[WPS-AUTH]" not in bss['flags']:
1114 raise Exception("WPS-AUTH flag missing")
38ae43de
JM
1115
1116 logger.info("Stop ER")
1117 dev[0].dump_monitor()
1118 dev[0].request("WPS_ER_STOP")
1119 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
1120 if ev is None:
1121 raise Exception("WPS ER unsubscription timed out")
8697cbc0 1122 # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
befd671c 1123 # a bit before verifying that the scan results have changed.
8697cbc0 1124 time.sleep(0.2)
38ae43de 1125
befd671c
JM
1126 for i in range(0, 10):
1127 dev[1].request("BSS_FLUSH 0")
1128 dev[1].scan(freq="2412", only_new=True)
1129 bss = dev[1].get_bss(apdev[0]['bssid'])
1130 if bss and 'flags' in bss and "[WPS-AUTH]" not in bss['flags']:
1131 break
1132 logger.debug("WPS-AUTH flag was still in place - wait a bit longer")
1133 time.sleep(0.1)
38ae43de
JM
1134 if "[WPS-AUTH]" in bss['flags']:
1135 raise Exception("WPS-AUTH flag not removed")
1136
c965ae03
JM
1137def test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1138 """WPS ER adding a new enrollee identified by UUID"""
1139 try:
1140 _test_ap_wps_er_add_enrollee_uuid(dev, apdev)
1141 finally:
1142 dev[0].request("WPS_ER_STOP")
1143
1144def _test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1145 ssid = "wps-er-add-enrollee"
1146 ap_pin = "12345670"
1147 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1148 hostapd.add_ap(apdev[0],
c965ae03
JM
1149 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1150 "wpa_passphrase": "12345678", "wpa": "2",
1151 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1152 "device_name": "Wireless AP", "manufacturer": "Company",
1153 "model_name": "WAP", "model_number": "123",
1154 "serial_number": "12345", "device_type": "6-0050F204-1",
1155 "os_version": "01020300",
1156 "config_methods": "label push_button",
1157 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1158 logger.info("WPS configuration step")
1159 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1160 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1161
1162 logger.info("Start ER")
1163 dev[0].request("WPS_ER_START ifname=lo")
1164 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1165 if ev is None:
1166 raise Exception("AP discovery timed out")
1167 if ap_uuid not in ev:
1168 raise Exception("Expected AP UUID not found")
1169
1170 logger.info("Learn AP configuration through UPnP")
1171 dev[0].dump_monitor()
1172 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1173 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1174 if ev is None:
1175 raise Exception("AP learn timed out")
1176 if ap_uuid not in ev:
1177 raise Exception("Expected AP UUID not in settings")
1178 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1179 if ev is None:
1180 raise Exception("WPS-FAIL after AP learn timed out")
1181 time.sleep(0.1)
1182
1183 logger.info("Add a specific Enrollee using ER (PBC/UUID)")
1184 addr1 = dev[1].p2p_interface_addr()
1185 dev[0].dump_monitor()
1186 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1187 dev[1].dump_monitor()
1188 dev[1].request("WPS_PBC %s" % apdev[0]['bssid'])
1189 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1190 if ev is None:
1191 raise Exception("Enrollee not seen")
1192 if addr1 not in ev:
1193 raise Exception("Unexpected Enrollee MAC address")
1194 uuid = ev.split(' ')[1]
1195 dev[0].request("WPS_ER_PBC " + uuid)
1196 dev[1].wait_connected(timeout=30)
1197 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1198 if ev is None:
1199 raise Exception("WPS ER did not report success")
1200
1201 logger.info("Add a specific Enrollee using ER (PIN/UUID)")
1202 pin = dev[2].wps_read_pin()
1203 addr2 = dev[2].p2p_interface_addr()
1204 dev[0].dump_monitor()
1205 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1206 dev[2].dump_monitor()
1207 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1208 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1209 if ev is None:
1210 raise Exception("Enrollee not seen")
1211 if addr2 not in ev:
1212 raise Exception("Unexpected Enrollee MAC address")
1213 uuid = ev.split(' ')[1]
1214 dev[0].request("WPS_ER_PIN " + uuid + " " + pin)
1215 dev[2].wait_connected(timeout=30)
1216 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1217 if ev is None:
1218 raise Exception("WPS ER did not report success")
1219
ea982de1
JM
1220 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-REMOVE"], timeout=15)
1221 if ev is None:
1222 raise Exception("No Enrollee STA entry timeout seen")
1223
c965ae03
JM
1224 logger.info("Stop ER")
1225 dev[0].dump_monitor()
1226 dev[0].request("WPS_ER_STOP")
1227
61c3d464
JM
1228def test_ap_wps_er_multi_add_enrollee(dev, apdev):
1229 """Multiple WPS ERs adding a new enrollee using PIN"""
1230 try:
1231 _test_ap_wps_er_multi_add_enrollee(dev, apdev)
1232 finally:
d887ed3f
JM
1233 for i in range(2):
1234 dev[i].request("WPS_ER_STOP")
61c3d464
JM
1235
1236def _test_ap_wps_er_multi_add_enrollee(dev, apdev):
1237 ssid = "wps-er-add-enrollee"
1238 ap_pin = "12345670"
1239 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1240 hostapd.add_ap(apdev[0],
61c3d464
JM
1241 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1242 "wpa_passphrase": "12345678", "wpa": "2",
1243 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1244 "device_name": "Wireless AP", "manufacturer": "Company",
1245 "model_name": "WAP", "model_number": "123",
1246 "serial_number": "12345", "device_type": "6-0050F204-1",
1247 "os_version": "01020300",
1248 'friendly_name': "WPS AP",
1249 "config_methods": "label push_button",
1250 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1251
1252 for i in range(2):
1253 dev[i].scan_for_bss(apdev[0]['bssid'], freq=2412)
1254 dev[i].wps_reg(apdev[0]['bssid'], ap_pin)
6a5f578c 1255 for i in range(2):
61c3d464
JM
1256 dev[i].request("WPS_ER_START ifname=lo")
1257 for i in range(2):
1258 ev = dev[i].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1259 if ev is None:
1260 raise Exception("AP discovery timed out")
1261 dev[i].dump_monitor()
6a5f578c 1262 for i in range(2):
61c3d464 1263 dev[i].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
6a5f578c 1264 for i in range(2):
61c3d464
JM
1265 ev = dev[i].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1266 if ev is None:
1267 raise Exception("AP learn timed out")
1268 ev = dev[i].wait_event(["WPS-FAIL"], timeout=15)
1269 if ev is None:
1270 raise Exception("WPS-FAIL after AP learn timed out")
1271
1272 time.sleep(0.1)
1273
1274 pin = dev[2].wps_read_pin()
1275 addr = dev[2].own_addr()
1276 dev[0].dump_monitor()
1277 dev[0].request("WPS_ER_PIN any " + pin + " " + addr)
1278 dev[1].dump_monitor()
1279 dev[1].request("WPS_ER_PIN any " + pin + " " + addr)
1280
1281 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1282 dev[2].dump_monitor()
1283 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1284 ev = dev[2].wait_event(["WPS-SUCCESS"], timeout=30)
1285 if ev is None:
1286 raise Exception("Enrollee did not report success")
1287 dev[2].wait_connected(timeout=15)
1288
6edaee9c
JM
1289def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1290 """WPS ER connected to AP and adding a new enrollee using PBC"""
be9f1562
JM
1291 try:
1292 _test_ap_wps_er_add_enrollee_pbc(dev, apdev)
1293 finally:
1294 dev[0].request("WPS_ER_STOP")
1295
1296def _test_ap_wps_er_add_enrollee_pbc(dev, apdev):
6edaee9c
JM
1297 ssid = "wps-er-add-enrollee-pbc"
1298 ap_pin = "12345670"
1299 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1300 hostapd.add_ap(apdev[0],
6edaee9c
JM
1301 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1302 "wpa_passphrase": "12345678", "wpa": "2",
1303 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1304 "device_name": "Wireless AP", "manufacturer": "Company",
1305 "model_name": "WAP", "model_number": "123",
1306 "serial_number": "12345", "device_type": "6-0050F204-1",
1307 "os_version": "01020300",
1308 "config_methods": "label push_button",
1309 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1310 logger.info("Learn AP configuration")
33d0b157 1311 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 1312 dev[0].dump_monitor()
6edaee9c
JM
1313 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1314 status = dev[0].get_status()
1315 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1316 raise Exception("Not fully connected")
1317
1318 logger.info("Start ER")
1319 dev[0].request("WPS_ER_START ifname=lo")
1320 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1321 if ev is None:
1322 raise Exception("AP discovery timed out")
1323 if ap_uuid not in ev:
1324 raise Exception("Expected AP UUID not found")
1325
d6b916c9
JM
1326 enrollee = dev[1].p2p_interface_addr()
1327
1328 if "FAIL-UNKNOWN-UUID" not in dev[0].request("WPS_ER_PBC " + enrollee):
1329 raise Exception("Unknown UUID not reported")
6edaee9c
JM
1330
1331 logger.info("Add Enrollee using ER and PBC")
1332 dev[0].dump_monitor()
6edaee9c
JM
1333 dev[1].dump_monitor()
1334 dev[1].request("WPS_PBC")
1335
8674c022
JM
1336 for i in range(0, 2):
1337 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1338 if ev is None:
1339 raise Exception("Enrollee discovery timed out")
1340 if enrollee in ev:
1341 break
1342 if i == 1:
1343 raise Exception("Expected Enrollee not found")
d6b916c9
JM
1344 if "FAIL-NO-AP-SETTINGS" not in dev[0].request("WPS_ER_PBC " + enrollee):
1345 raise Exception("Unknown UUID not reported")
1346 logger.info("Use learned network configuration on ER")
1347 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1348 if "OK" not in dev[0].request("WPS_ER_PBC " + enrollee):
1349 raise Exception("WPS_ER_PBC failed")
6edaee9c
JM
1350
1351 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
1352 if ev is None:
1353 raise Exception("Enrollee did not report success")
5f35a5e2 1354 dev[1].wait_connected(timeout=15)
6edaee9c
JM
1355 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1356 if ev is None:
1357 raise Exception("WPS ER did not report success")
1358 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
bff3ac5b 1359
d6b916c9
JM
1360def test_ap_wps_er_pbc_overlap(dev, apdev):
1361 """WPS ER connected to AP and PBC session overlap"""
be9f1562
JM
1362 try:
1363 _test_ap_wps_er_pbc_overlap(dev, apdev)
1364 finally:
1365 dev[0].request("WPS_ER_STOP")
1366
1367def _test_ap_wps_er_pbc_overlap(dev, apdev):
d6b916c9
JM
1368 ssid = "wps-er-add-enrollee-pbc"
1369 ap_pin = "12345670"
1370 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1371 hostapd.add_ap(apdev[0],
d6b916c9
JM
1372 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1373 "wpa_passphrase": "12345678", "wpa": "2",
1374 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1375 "device_name": "Wireless AP", "manufacturer": "Company",
1376 "model_name": "WAP", "model_number": "123",
1377 "serial_number": "12345", "device_type": "6-0050F204-1",
1378 "os_version": "01020300",
1379 "config_methods": "label push_button",
1380 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1381 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1382 dev[0].dump_monitor()
1383 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1384
fba25c99
JM
1385 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1386 dev[2].scan_for_bss(apdev[0]['bssid'], freq="2412")
1387 # avoid leaving dev 1 or 2 as the last Probe Request to the AP
1388 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True)
1389
d6b916c9
JM
1390 dev[0].dump_monitor()
1391 dev[0].request("WPS_ER_START ifname=lo")
1392
1393 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1394 if ev is None:
1395 raise Exception("AP discovery timed out")
1396 if ap_uuid not in ev:
1397 raise Exception("Expected AP UUID not found")
1398
800bcf4e
JM
1399 # verify BSSID selection of the AP instead of UUID
1400 if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
1401 raise Exception("Could not select AP based on BSSID")
1402
fba25c99 1403 dev[0].dump_monitor()
d6b916c9
JM
1404 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1405 dev[2].request("WPS_PBC " + apdev[0]['bssid'])
1406 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1407 if ev is None:
1408 raise Exception("PBC scan failed")
1409 ev = dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1410 if ev is None:
1411 raise Exception("PBC scan failed")
fba25c99
JM
1412 found1 = False
1413 found2 = False
1414 addr1 = dev[1].own_addr()
1415 addr2 = dev[2].own_addr()
1416 for i in range(3):
d6b916c9
JM
1417 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1418 if ev is None:
1419 raise Exception("Enrollee discovery timed out")
fba25c99
JM
1420 if addr1 in ev:
1421 found1 = True
1422 if found2:
1423 break
1424 if addr2 in ev:
1425 found2 = True
1426 if found1:
1427 break
d6b916c9
JM
1428 if dev[0].request("WPS_ER_PBC " + ap_uuid) != "FAIL-PBC-OVERLAP\n":
1429 raise Exception("PBC overlap not reported")
1430 dev[1].request("WPS_CANCEL")
1431 dev[2].request("WPS_CANCEL")
1432 if dev[0].request("WPS_ER_PBC foo") != "FAIL\n":
1433 raise Exception("Invalid WPS_ER_PBC accepted")
1434
1f020f5e
JM
1435def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1436 """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
be9f1562
JM
1437 try:
1438 _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev)
1439 finally:
1440 dev[0].request("WPS_ER_STOP")
1441
1442def _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1f020f5e
JM
1443 ssid = "wps-er-add-enrollee-pbc"
1444 ap_pin = "12345670"
1445 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1446 hostapd.add_ap(apdev[0],
1f020f5e
JM
1447 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1448 "wpa_passphrase": "12345678", "wpa": "2",
1449 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1450 "device_name": "Wireless AP", "manufacturer": "Company",
1451 "model_name": "WAP", "model_number": "123",
1452 "serial_number": "12345", "device_type": "6-0050F204-1",
1453 "os_version": "01020300",
1454 "config_methods": "label push_button",
1455 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1456 logger.info("Learn AP configuration")
1457 dev[0].request("SET wps_version_number 0x10")
33d0b157 1458 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1f020f5e
JM
1459 dev[0].dump_monitor()
1460 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1461 status = dev[0].get_status()
1462 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1463 raise Exception("Not fully connected")
1464
1465 logger.info("Start ER")
1466 dev[0].request("WPS_ER_START ifname=lo")
1467 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1468 if ev is None:
1469 raise Exception("AP discovery timed out")
1470 if ap_uuid not in ev:
1471 raise Exception("Expected AP UUID not found")
1472
1473 logger.info("Use learned network configuration on ER")
1474 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1475
1476 logger.info("Add Enrollee using ER and PIN")
1477 enrollee = dev[1].p2p_interface_addr()
1478 pin = dev[1].wps_read_pin()
1479 dev[0].dump_monitor()
1480 dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
33d0b157 1481 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1f020f5e 1482 dev[1].dump_monitor()
33d0b157 1483 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 1484 dev[1].wait_connected(timeout=30)
1f020f5e
JM
1485 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1486 if ev is None:
1487 raise Exception("WPS ER did not report success")
1488
be923570
JM
1489def test_ap_wps_er_config_ap(dev, apdev):
1490 """WPS ER configuring AP over UPnP"""
be9f1562
JM
1491 try:
1492 _test_ap_wps_er_config_ap(dev, apdev)
1493 finally:
1494 dev[0].request("WPS_ER_STOP")
1495
1496def _test_ap_wps_er_config_ap(dev, apdev):
be923570
JM
1497 ssid = "wps-er-ap-config"
1498 ap_pin = "12345670"
1499 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1500 hostapd.add_ap(apdev[0],
be923570
JM
1501 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1502 "wpa_passphrase": "12345678", "wpa": "2",
1503 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1504 "device_name": "Wireless AP", "manufacturer": "Company",
1505 "model_name": "WAP", "model_number": "123",
1506 "serial_number": "12345", "device_type": "6-0050F204-1",
1507 "os_version": "01020300",
1508 "config_methods": "label push_button",
1509 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1510
1511 logger.info("Connect ER to the AP")
1512 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
1513
1514 logger.info("WPS configuration step")
1515 dev[0].request("WPS_ER_START ifname=lo")
1516 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1517 if ev is None:
1518 raise Exception("AP discovery timed out")
1519 if ap_uuid not in ev:
1520 raise Exception("Expected AP UUID not found")
1521 new_passphrase = "1234567890"
1522 dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
1523 ssid.encode("hex") + " WPA2PSK CCMP " +
1524 new_passphrase.encode("hex"))
1525 ev = dev[0].wait_event(["WPS-SUCCESS"])
1526 if ev is None:
1527 raise Exception("WPS ER configuration operation timed out")
5f35a5e2 1528 dev[0].wait_disconnected(timeout=10)
be923570
JM
1529 dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
1530
8f8c2fe8
JM
1531 logger.info("WPS ER restart")
1532 dev[0].request("WPS_ER_START")
1533 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1534 if ev is None:
1535 raise Exception("AP discovery timed out on ER restart")
1536 if ap_uuid not in ev:
1537 raise Exception("Expected AP UUID not found on ER restart")
1538 if "OK" not in dev[0].request("WPS_ER_STOP"):
1539 raise Exception("WPS_ER_STOP failed")
1540 if "OK" not in dev[0].request("WPS_ER_STOP"):
1541 raise Exception("WPS_ER_STOP failed")
1542
6aaa661a
JM
1543def test_ap_wps_er_cache_ap_settings(dev, apdev):
1544 """WPS ER caching AP settings"""
1545 try:
1546 _test_ap_wps_er_cache_ap_settings(dev, apdev)
1547 finally:
1548 dev[0].request("WPS_ER_STOP")
1549
1550def _test_ap_wps_er_cache_ap_settings(dev, apdev):
1551 ssid = "wps-er-add-enrollee"
1552 ap_pin = "12345670"
1553 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1554 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1555 "wpa_passphrase": "12345678", "wpa": "2",
1556 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1557 "device_name": "Wireless AP", "manufacturer": "Company",
1558 "model_name": "WAP", "model_number": "123",
1559 "serial_number": "12345", "device_type": "6-0050F204-1",
1560 "os_version": "01020300",
1561 "config_methods": "label push_button",
1562 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
8b8a1864 1563 hapd = hostapd.add_ap(apdev[0], params)
6aaa661a
JM
1564 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1565 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1566 id = int(dev[0].list_networks()[0]['id'])
1567 dev[0].set_network(id, "scan_freq", "2412")
1568
1569 dev[0].request("WPS_ER_START ifname=lo")
1570 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1571 if ev is None:
1572 raise Exception("AP discovery timed out")
1573 if ap_uuid not in ev:
1574 raise Exception("Expected AP UUID not found")
1575
1576 dev[0].dump_monitor()
1577 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1578 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1579 if ev is None:
1580 raise Exception("AP learn timed out")
1581 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1582 if ev is None:
1583 raise Exception("WPS-FAIL after AP learn timed out")
1584 time.sleep(0.1)
1585
1586 hapd.disable()
1587
1588 for i in range(2):
1589 ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1590 "CTRL-EVENT-DISCONNECTED" ],
1591 timeout=15)
1592 if ev is None:
1593 raise Exception("AP removal or disconnection timed out")
1594
8b8a1864 1595 hapd = hostapd.add_ap(apdev[0], params)
6aaa661a
JM
1596 for i in range(2):
1597 ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1598 timeout=15)
1599 if ev is None:
1600 raise Exception("AP discovery or connection timed out")
1601
1602 pin = dev[1].wps_read_pin()
1603 dev[0].dump_monitor()
1604 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1605
1606 time.sleep(0.2)
1607
1608 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1609 dev[1].dump_monitor()
1610 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1611 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
1612 if ev is None:
1613 raise Exception("Enrollee did not report success")
1614 dev[1].wait_connected(timeout=15)
1615 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1616 if ev is None:
1617 raise Exception("WPS ER did not report success")
1618
1619 dev[0].dump_monitor()
1620 dev[0].request("WPS_ER_STOP")
1621
d840350a
JM
1622def test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1623 """WPS ER caching AP settings (OOM)"""
1624 try:
1625 _test_ap_wps_er_cache_ap_settings_oom(dev, apdev)
1626 finally:
1627 dev[0].request("WPS_ER_STOP")
1628
1629def _test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1630 ssid = "wps-er-add-enrollee"
1631 ap_pin = "12345670"
1632 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1633 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1634 "wpa_passphrase": "12345678", "wpa": "2",
1635 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1636 "device_name": "Wireless AP", "manufacturer": "Company",
1637 "model_name": "WAP", "model_number": "123",
1638 "serial_number": "12345", "device_type": "6-0050F204-1",
1639 "os_version": "01020300",
1640 "config_methods": "label push_button",
1641 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
8b8a1864 1642 hapd = hostapd.add_ap(apdev[0], params)
d840350a
JM
1643 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1644 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1645 id = int(dev[0].list_networks()[0]['id'])
1646 dev[0].set_network(id, "scan_freq", "2412")
1647
1648 dev[0].request("WPS_ER_START ifname=lo")
1649 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1650 if ev is None:
1651 raise Exception("AP discovery timed out")
1652 if ap_uuid not in ev:
1653 raise Exception("Expected AP UUID not found")
1654
1655 dev[0].dump_monitor()
1656 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1657 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1658 if ev is None:
1659 raise Exception("AP learn timed out")
1660 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1661 if ev is None:
1662 raise Exception("WPS-FAIL after AP learn timed out")
1663 time.sleep(0.1)
1664
1665 with alloc_fail(dev[0], 1, "=wps_er_ap_use_cached_settings"):
1666 hapd.disable()
1667
1668 for i in range(2):
1669 ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1670 "CTRL-EVENT-DISCONNECTED" ],
1671 timeout=15)
1672 if ev is None:
1673 raise Exception("AP removal or disconnection timed out")
1674
8b8a1864 1675 hapd = hostapd.add_ap(apdev[0], params)
d840350a
JM
1676 for i in range(2):
1677 ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1678 timeout=15)
1679 if ev is None:
1680 raise Exception("AP discovery or connection timed out")
1681
1682 dev[0].request("WPS_ER_STOP")
1683
1684def test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1685 """WPS ER caching AP settings (OOM 2)"""
1686 try:
1687 _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev)
1688 finally:
1689 dev[0].request("WPS_ER_STOP")
1690
1691def _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1692 ssid = "wps-er-add-enrollee"
1693 ap_pin = "12345670"
1694 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1695 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1696 "wpa_passphrase": "12345678", "wpa": "2",
1697 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1698 "device_name": "Wireless AP", "manufacturer": "Company",
1699 "model_name": "WAP", "model_number": "123",
1700 "serial_number": "12345", "device_type": "6-0050F204-1",
1701 "os_version": "01020300",
1702 "config_methods": "label push_button",
1703 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
8b8a1864 1704 hapd = hostapd.add_ap(apdev[0], params)
d840350a
JM
1705 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1706 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1707 id = int(dev[0].list_networks()[0]['id'])
1708 dev[0].set_network(id, "scan_freq", "2412")
1709
1710 dev[0].request("WPS_ER_START ifname=lo")
1711 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1712 if ev is None:
1713 raise Exception("AP discovery timed out")
1714 if ap_uuid not in ev:
1715 raise Exception("Expected AP UUID not found")
1716
1717 dev[0].dump_monitor()
1718 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1719 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1720 if ev is None:
1721 raise Exception("AP learn timed out")
1722 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1723 if ev is None:
1724 raise Exception("WPS-FAIL after AP learn timed out")
1725 time.sleep(0.1)
1726
1727 with alloc_fail(dev[0], 1, "=wps_er_ap_cache_settings"):
1728 hapd.disable()
1729
1730 for i in range(2):
1731 ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1732 "CTRL-EVENT-DISCONNECTED" ],
1733 timeout=15)
1734 if ev is None:
1735 raise Exception("AP removal or disconnection timed out")
1736
8b8a1864 1737 hapd = hostapd.add_ap(apdev[0], params)
d840350a
JM
1738 for i in range(2):
1739 ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1740 timeout=15)
1741 if ev is None:
1742 raise Exception("AP discovery or connection timed out")
1743
1744 dev[0].request("WPS_ER_STOP")
1745
eb95ced2
JM
1746def test_ap_wps_er_subscribe_oom(dev, apdev):
1747 """WPS ER subscribe OOM"""
1748 try:
1749 _test_ap_wps_er_subscribe_oom(dev, apdev)
1750 finally:
1751 dev[0].request("WPS_ER_STOP")
1752
1753def _test_ap_wps_er_subscribe_oom(dev, apdev):
1754 ssid = "wps-er-add-enrollee"
1755 ap_pin = "12345670"
1756 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1757 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1758 "wpa_passphrase": "12345678", "wpa": "2",
1759 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1760 "device_name": "Wireless AP", "manufacturer": "Company",
1761 "model_name": "WAP", "model_number": "123",
1762 "serial_number": "12345", "device_type": "6-0050F204-1",
1763 "os_version": "01020300",
1764 "config_methods": "label push_button",
1765 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
8b8a1864 1766 hapd = hostapd.add_ap(apdev[0], params)
eb95ced2
JM
1767 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1768 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1769 id = int(dev[0].list_networks()[0]['id'])
1770 dev[0].set_network(id, "scan_freq", "2412")
1771
1772 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_subscribe"):
1773 dev[0].request("WPS_ER_START ifname=lo")
1774 for i in range(50):
1775 res = dev[0].request("GET_ALLOC_FAIL")
1776 if res.startswith("0:"):
1777 break
1778 time.sleep(0.1)
1779 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=0)
1780 if ev:
1781 raise Exception("Unexpected AP discovery during OOM")
1782
1783 dev[0].request("WPS_ER_STOP")
1784
db9c88eb
JM
1785def test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1786 """WPS ER SetSelectedRegistrar OOM"""
1787 try:
1788 _test_ap_wps_er_set_sel_reg_oom(dev, apdev)
1789 finally:
1790 dev[0].request("WPS_ER_STOP")
1791
1792def _test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1793 ssid = "wps-er-add-enrollee"
1794 ap_pin = "12345670"
1795 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1796 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1797 "wpa_passphrase": "12345678", "wpa": "2",
1798 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1799 "device_name": "Wireless AP", "manufacturer": "Company",
1800 "model_name": "WAP", "model_number": "123",
1801 "serial_number": "12345", "device_type": "6-0050F204-1",
1802 "os_version": "01020300",
1803 "config_methods": "label push_button",
1804 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
8b8a1864 1805 hapd = hostapd.add_ap(apdev[0], params)
db9c88eb
JM
1806 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1807 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1808
1809 dev[0].request("WPS_ER_START ifname=lo")
1810 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1811 if ev is None:
1812 raise Exception("AP not discovered")
1813
1814 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1815 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1816 if ev is None:
1817 raise Exception("AP learn timed out")
1818 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1819 if ev is None:
1820 raise Exception("WPS-FAIL timed out")
1821 time.sleep(0.1)
1822
1823 for func in [ "http_client_url_parse;wps_er_send_set_sel_reg",
1824 "wps_er_soap_hdr;wps_er_send_set_sel_reg",
1825 "http_client_addr;wps_er_send_set_sel_reg",
1826 "wpabuf_alloc;wps_er_set_sel_reg" ]:
1827 with alloc_fail(dev[0], 1, func):
1828 if "OK" not in dev[0].request("WPS_ER_PBC " + ap_uuid):
1829 raise Exception("WPS_ER_PBC failed")
1830 ev = dev[0].wait_event(["WPS-PBC-ACTIVE"], timeout=3)
1831 if ev is None:
1832 raise Exception("WPS-PBC-ACTIVE not seen")
1833
1834 dev[0].request("WPS_ER_STOP")
1835
ae3eacf7
JM
1836def test_ap_wps_er_learn_oom(dev, apdev):
1837 """WPS ER learn OOM"""
1838 try:
1839 _test_ap_wps_er_learn_oom(dev, apdev)
1840 finally:
1841 dev[0].request("WPS_ER_STOP")
1842
1843def _test_ap_wps_er_learn_oom(dev, apdev):
1844 ssid = "wps-er-add-enrollee"
1845 ap_pin = "12345670"
1846 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1847 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1848 "wpa_passphrase": "12345678", "wpa": "2",
1849 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1850 "device_name": "Wireless AP", "manufacturer": "Company",
1851 "model_name": "WAP", "model_number": "123",
1852 "serial_number": "12345", "device_type": "6-0050F204-1",
1853 "os_version": "01020300",
1854 "config_methods": "label push_button",
1855 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
8b8a1864 1856 hapd = hostapd.add_ap(apdev[0], params)
ae3eacf7
JM
1857 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1858 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1859
1860 dev[0].request("WPS_ER_START ifname=lo")
1861 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1862 if ev is None:
1863 raise Exception("AP not discovered")
1864
1865 for func in [ "wps_er_http_put_message_cb",
1866 "xml_get_base64_item;wps_er_http_put_message_cb",
1867 "http_client_url_parse;wps_er_ap_put_message",
1868 "wps_er_soap_hdr;wps_er_ap_put_message",
1869 "http_client_addr;wps_er_ap_put_message" ]:
1870 with alloc_fail(dev[0], 1, func):
1871 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1872 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=1)
1873 if ev is not None:
1874 raise Exception("AP learn succeeded during OOM")
1875
1876 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1877 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=10)
1878 if ev is None:
1879 raise Exception("AP learn did not succeed")
1880
1881 if "FAIL" not in dev[0].request("WPS_ER_LEARN 00000000-9e5c-4e73-bd82-f89cbcd10d7e " + ap_pin):
1882 raise Exception("WPS_ER_LEARN for unknown AP accepted")
1883
1884 dev[0].request("WPS_ER_STOP")
1885
bff3ac5b
JM
1886def test_ap_wps_fragmentation(dev, apdev):
1887 """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
1888 ssid = "test-wps-fragmentation"
9602b355 1889 appin = "12345670"
6f334bf7
JD
1890 hapd = hostapd.add_ap(apdev[0],
1891 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1892 "wpa_passphrase": "12345678", "wpa": "3",
1893 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1894 "wpa_pairwise": "TKIP", "ap_pin": appin,
1895 "fragment_size": "50" })
9602b355 1896 logger.info("WPS provisioning step (PBC)")
bff3ac5b 1897 hapd.request("WPS_PBC")
33d0b157 1898 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
bff3ac5b
JM
1899 dev[0].dump_monitor()
1900 dev[0].request("SET wps_fragment_size 50")
33d0b157 1901 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1902 dev[0].wait_connected(timeout=30)
bff3ac5b
JM
1903 status = dev[0].get_status()
1904 if status['wpa_state'] != 'COMPLETED':
9602b355
JM
1905 raise Exception("Not fully connected")
1906 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1907 raise Exception("Unexpected encryption configuration")
1908 if status['key_mgmt'] != 'WPA2-PSK':
1909 raise Exception("Unexpected key_mgmt")
1910
1911 logger.info("WPS provisioning step (PIN)")
1912 pin = dev[1].wps_read_pin()
1913 hapd.request("WPS_PIN any " + pin)
33d0b157 1914 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
9602b355 1915 dev[1].request("SET wps_fragment_size 50")
33d0b157 1916 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 1917 dev[1].wait_connected(timeout=30)
9602b355
JM
1918 status = dev[1].get_status()
1919 if status['wpa_state'] != 'COMPLETED':
1920 raise Exception("Not fully connected")
1921 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1922 raise Exception("Unexpected encryption configuration")
1923 if status['key_mgmt'] != 'WPA2-PSK':
1924 raise Exception("Unexpected key_mgmt")
1925
1926 logger.info("WPS connection as registrar")
33d0b157 1927 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
9602b355
JM
1928 dev[2].request("SET wps_fragment_size 50")
1929 dev[2].wps_reg(apdev[0]['bssid'], appin)
1930 status = dev[2].get_status()
1931 if status['wpa_state'] != 'COMPLETED':
bff3ac5b
JM
1932 raise Exception("Not fully connected")
1933 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1934 raise Exception("Unexpected encryption configuration")
1935 if status['key_mgmt'] != 'WPA2-PSK':
1936 raise Exception("Unexpected key_mgmt")
10ea6848
JM
1937
1938def test_ap_wps_new_version_sta(dev, apdev):
1939 """WPS compatibility with new version number on the station"""
1940 ssid = "test-wps-ver"
6f334bf7
JD
1941 hapd = hostapd.add_ap(apdev[0],
1942 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1943 "wpa_passphrase": "12345678", "wpa": "2",
1944 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
10ea6848
JM
1945 logger.info("WPS provisioning step")
1946 hapd.request("WPS_PBC")
33d0b157 1947 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10ea6848
JM
1948 dev[0].dump_monitor()
1949 dev[0].request("SET wps_version_number 0x43")
dccafedb 1950 dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
33d0b157 1951 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1952 dev[0].wait_connected(timeout=30)
10ea6848
JM
1953
1954def test_ap_wps_new_version_ap(dev, apdev):
1955 """WPS compatibility with new version number on the AP"""
1956 ssid = "test-wps-ver"
6f334bf7
JD
1957 hapd = hostapd.add_ap(apdev[0],
1958 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1959 "wpa_passphrase": "12345678", "wpa": "2",
1960 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
10ea6848
JM
1961 logger.info("WPS provisioning step")
1962 if "FAIL" in hapd.request("SET wps_version_number 0x43"):
1963 raise Exception("Failed to enable test functionality")
1964 hapd.request("WPS_PBC")
33d0b157 1965 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10ea6848 1966 dev[0].dump_monitor()
33d0b157 1967 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1968 dev[0].wait_connected(timeout=30)
10ea6848 1969 hapd.request("SET wps_version_number 0x20")
3bdf7d7f
JM
1970
1971def test_ap_wps_check_pin(dev, apdev):
1972 """Verify PIN checking through control interface"""
6f334bf7
JD
1973 hapd = hostapd.add_ap(apdev[0],
1974 { "ssid": "wps", "eap_server": "1", "wps_state": "2",
1975 "wpa_passphrase": "12345678", "wpa": "2",
1976 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
3bdf7d7f
JM
1977 for t in [ ("12345670", "12345670"),
1978 ("12345678", "FAIL-CHECKSUM"),
df58939c 1979 ("12345", "FAIL"),
6e12eaa4 1980 ("123456789", "FAIL"),
3bdf7d7f
JM
1981 ("1234-5670", "12345670"),
1982 ("1234 5670", "12345670"),
1983 ("1-2.3:4 5670", "12345670") ]:
1984 res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
1985 res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
1986 if res != res2:
1987 raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
1988 if res != t[1]:
1989 raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
9ba1fcb0 1990
ac786d67
JM
1991 if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
1992 raise Exception("Unexpected WPS_CHECK_PIN success")
1993 if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
1994 raise Exception("Unexpected WPS_CHECK_PIN success")
1995
acd9b45a
JM
1996 for i in range(0, 10):
1997 pin = dev[0].request("WPS_PIN get")
1998 rpin = dev[0].request("WPS_CHECK_PIN " + pin).rstrip('\n')
1999 if pin != rpin:
2000 raise Exception("Random PIN validation failed for " + pin)
2001
9ba1fcb0
JM
2002def test_ap_wps_wep_config(dev, apdev):
2003 """WPS 2.0 AP rejecting WEP configuration"""
2004 ssid = "test-wps-config"
2005 appin = "12345670"
6f334bf7
JD
2006 hapd = hostapd.add_ap(apdev[0],
2007 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2008 "ap_pin": appin})
33d0b157 2009 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
9ba1fcb0
JM
2010 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
2011 "hello", no_wait=True)
2012 ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
2013 if ev is None:
2014 raise Exception("WPS-FAIL timed out")
2015 if "reason=2" not in ev:
2016 raise Exception("Unexpected reason code in WPS-FAIL")
2017 status = hapd.request("WPS_GET_STATUS")
2018 if "Last WPS result: Failed" not in status:
2019 raise Exception("WPS failure result not shown correctly")
2020 if "Failure Reason: WEP Prohibited" not in status:
2021 raise Exception("Failure reason not reported correctly")
2022 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
2023 raise Exception("Peer address not shown correctly")
1013a576 2024
11d78bb1
JM
2025def test_ap_wps_wep_enroll(dev, apdev):
2026 """WPS 2.0 STA rejecting WEP configuration"""
2027 ssid = "test-wps-wep"
6f334bf7
JD
2028 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2029 "skip_cred_build": "1", "extra_cred": "wps-wep-cred" }
2030 hapd = hostapd.add_ap(apdev[0], params)
11d78bb1 2031 hapd.request("WPS_PBC")
33d0b157
JM
2032 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2033 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
11d78bb1
JM
2034 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
2035 if ev is None:
2036 raise Exception("WPS-FAIL event timed out")
2037 if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
2038 raise Exception("Unexpected WPS-FAIL event: " + ev)
2039
1013a576
JM
2040def test_ap_wps_ie_fragmentation(dev, apdev):
2041 """WPS AP using fragmented WPS IE"""
2042 ssid = "test-wps-ie-fragmentation"
2043 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2044 "wpa_passphrase": "12345678", "wpa": "2",
2045 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2046 "device_name": "1234567890abcdef1234567890abcdef",
2047 "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
2048 "model_name": "1234567890abcdef1234567890abcdef",
2049 "model_number": "1234567890abcdef1234567890abcdef",
2050 "serial_number": "1234567890abcdef1234567890abcdef" }
6f334bf7 2051 hapd = hostapd.add_ap(apdev[0], params)
1013a576 2052 hapd.request("WPS_PBC")
33d0b157
JM
2053 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2054 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2055 dev[0].wait_connected(timeout=30)
1013a576
JM
2056 bss = dev[0].get_bss(apdev[0]['bssid'])
2057 if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
cf3f0ec8 2058 logger.info("Device Name not received correctly")
d7a68ad6 2059 logger.info(bss)
cf3f0ec8
JM
2060 # This can fail if Probe Response frame is missed and Beacon frame was
2061 # used to fill in the BSS entry. This can happen, e.g., during heavy
2062 # load every now and then and is not really an error, so try to
2063 # workaround by runnign another scan.
2064 dev[0].scan(freq="2412", only_new=True)
2065 bss = dev[0].get_bss(apdev[0]['bssid'])
84a40841 2066 if not bss or "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
cf3f0ec8
JM
2067 logger.info(bss)
2068 raise Exception("Device Name not received correctly")
1013a576
JM
2069 if len(re.findall("dd..0050f204", bss['ie'])) != 2:
2070 raise Exception("Unexpected number of WPS IEs")
44ff0400 2071
2035b170
JM
2072def get_psk(pskfile):
2073 psks = {}
2074 with open(pskfile, "r") as f:
2075 lines = f.read().splitlines()
2076 for l in lines:
2077 if l == "# WPA PSKs":
2078 continue
2079 (addr,psk) = l.split(' ')
2080 psks[addr] = psk
2081 return psks
2082
2083def test_ap_wps_per_station_psk(dev, apdev):
2084 """WPS PBC provisioning with per-station PSK"""
1d21a5be
B
2085 addr0 = dev[0].own_addr()
2086 addr1 = dev[1].own_addr()
2087 addr2 = dev[2].own_addr()
2035b170
JM
2088 ssid = "wps"
2089 appin = "12345670"
2090 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2091 try:
2092 os.remove(pskfile)
2093 except:
2094 pass
2095
4f524e99 2096 hapd = None
2035b170
JM
2097 try:
2098 with open(pskfile, "w") as f:
2099 f.write("# WPA PSKs\n")
2100
2101 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2102 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2103 "rsn_pairwise": "CCMP", "ap_pin": appin,
2104 "wpa_psk_file": pskfile }
8b8a1864 2105 hapd = hostapd.add_ap(apdev[0], params)
2035b170
JM
2106
2107 logger.info("First enrollee")
2108 hapd.request("WPS_PBC")
33d0b157
JM
2109 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2110 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2111 dev[0].wait_connected(timeout=30)
2035b170
JM
2112
2113 logger.info("Second enrollee")
2114 hapd.request("WPS_PBC")
33d0b157
JM
2115 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2116 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2117 dev[1].wait_connected(timeout=30)
2035b170
JM
2118
2119 logger.info("External registrar")
33d0b157 2120 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2035b170
JM
2121 dev[2].wps_reg(apdev[0]['bssid'], appin)
2122
2123 logger.info("Verifying PSK results")
2124 psks = get_psk(pskfile)
2125 if addr0 not in psks:
2126 raise Exception("No PSK recorded for sta0")
2127 if addr1 not in psks:
2128 raise Exception("No PSK recorded for sta1")
2129 if addr2 not in psks:
2130 raise Exception("No PSK recorded for sta2")
2131 if psks[addr0] == psks[addr1]:
2132 raise Exception("Same PSK recorded for sta0 and sta1")
2133 if psks[addr0] == psks[addr2]:
2134 raise Exception("Same PSK recorded for sta0 and sta2")
2135 if psks[addr1] == psks[addr2]:
2136 raise Exception("Same PSK recorded for sta1 and sta2")
2137
2138 dev[0].request("REMOVE_NETWORK all")
2139 logger.info("Second external registrar")
33d0b157 2140 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2035b170
JM
2141 dev[0].wps_reg(apdev[0]['bssid'], appin)
2142 psks2 = get_psk(pskfile)
2143 if addr0 not in psks2:
2144 raise Exception("No PSK recorded for sta0(reg)")
2145 if psks[addr0] == psks2[addr0]:
2146 raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
2147 finally:
2148 os.remove(pskfile)
4f524e99
JM
2149 if hapd:
2150 dev[0].request("DISCONNECT")
2151 dev[1].request("DISCONNECT")
2152 dev[2].request("DISCONNECT")
2153 hapd.disable()
2154 dev[0].flush_scan_cache()
2155 dev[1].flush_scan_cache()
2156 dev[2].flush_scan_cache()
2035b170 2157
373cce55
JM
2158def test_ap_wps_per_station_psk_failure(dev, apdev):
2159 """WPS PBC provisioning with per-station PSK (file not writable)"""
2160 addr0 = dev[0].p2p_dev_addr()
2161 addr1 = dev[1].p2p_dev_addr()
2162 addr2 = dev[2].p2p_dev_addr()
2163 ssid = "wps"
2164 appin = "12345670"
2165 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2166 try:
2167 os.remove(pskfile)
2168 except:
2169 pass
2170
2171 try:
2172 with open(pskfile, "w") as f:
2173 f.write("# WPA PSKs\n")
2174
2175 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2176 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2177 "rsn_pairwise": "CCMP", "ap_pin": appin,
2178 "wpa_psk_file": pskfile }
8b8a1864 2179 hapd = hostapd.add_ap(apdev[0], params)
373cce55
JM
2180 if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
2181 raise Exception("Failed to set wpa_psk_file")
2182
2183 logger.info("First enrollee")
2184 hapd.request("WPS_PBC")
33d0b157
JM
2185 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2186 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2187 dev[0].wait_connected(timeout=30)
373cce55
JM
2188
2189 logger.info("Second enrollee")
2190 hapd.request("WPS_PBC")
33d0b157
JM
2191 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2192 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2193 dev[1].wait_connected(timeout=30)
373cce55
JM
2194
2195 logger.info("External registrar")
33d0b157 2196 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
373cce55
JM
2197 dev[2].wps_reg(apdev[0]['bssid'], appin)
2198
2199 logger.info("Verifying PSK results")
2200 psks = get_psk(pskfile)
2201 if len(psks) > 0:
2202 raise Exception("PSK recorded unexpectedly")
2203 finally:
2204 os.remove(pskfile)
2205
e8518757
JM
2206def test_ap_wps_pin_request_file(dev, apdev):
2207 """WPS PIN provisioning with configured AP"""
2208 ssid = "wps"
2209 pinfile = "/tmp/ap_wps_pin_request_file.log"
2210 if os.path.exists(pinfile):
b638f703 2211 os.remove(pinfile)
6f334bf7
JD
2212 hapd = hostapd.add_ap(apdev[0],
2213 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2214 "wps_pin_requests": pinfile,
2215 "wpa_passphrase": "12345678", "wpa": "2",
2216 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e8518757
JM
2217 uuid = dev[0].get_status_field("uuid")
2218 pin = dev[0].wps_read_pin()
2219 try:
33d0b157
JM
2220 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2221 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
e8518757
JM
2222 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
2223 if ev is None:
2224 raise Exception("PIN needed event not shown")
2225 if uuid not in ev:
2226 raise Exception("UUID mismatch")
2227 dev[0].request("WPS_CANCEL")
2228 success = False
2229 with open(pinfile, "r") as f:
2230 lines = f.readlines()
2231 for l in lines:
2232 if uuid in l:
2233 success = True
2234 break
2235 if not success:
2236 raise Exception("PIN request entry not in the log file")
2237 finally:
b638f703
JM
2238 try:
2239 os.remove(pinfile)
2240 except:
2241 pass
e8518757 2242
56887c35
JM
2243def test_ap_wps_auto_setup_with_config_file(dev, apdev):
2244 """WPS auto-setup with configuration file"""
2245 conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
2246 ifname = apdev[0]['ifname']
2247 try:
2248 with open(conffile, "w") as f:
2249 f.write("driver=nl80211\n")
2250 f.write("hw_mode=g\n")
2251 f.write("channel=1\n")
2252 f.write("ieee80211n=1\n")
2253 f.write("interface=%s\n" % ifname)
2254 f.write("ctrl_interface=/var/run/hostapd\n")
2255 f.write("ssid=wps\n")
2256 f.write("eap_server=1\n")
2257 f.write("wps_state=1\n")
5148b392 2258 hapd = hostapd.add_bss(apdev[0], ifname, conffile)
56887c35 2259 hapd.request("WPS_PBC")
33d0b157
JM
2260 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2261 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2262 dev[0].wait_connected(timeout=30)
56887c35
JM
2263 with open(conffile, "r") as f:
2264 lines = f.read().splitlines()
2265 vals = dict()
2266 for l in lines:
2267 try:
2268 [name,value] = l.split('=', 1)
2269 vals[name] = value
2270 except ValueError, e:
2271 if "# WPS configuration" in l:
2272 pass
2273 else:
2274 raise Exception("Unexpected configuration line: " + l)
2275 if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
2276 raise Exception("Incorrect configuration: " + str(vals))
2277 finally:
b638f703
JM
2278 try:
2279 os.remove(conffile)
2280 except:
2281 pass
56887c35 2282
91f3cf69 2283def test_ap_wps_pbc_timeout(dev, apdev, params):
31e56b95 2284 """wpa_supplicant PBC walk time and WPS ER SelReg timeout [long]"""
91f3cf69 2285 if not params['long']:
81e787b7 2286 raise HwsimSkip("Skip test case with long duration due to --long not specified")
31e56b95 2287 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2288 hapd = add_ssdp_ap(apdev[0], ap_uuid)
31e56b95
JM
2289
2290 location = ssdp_get_location(ap_uuid)
2291 urls = upnp_get_urls(location)
2292 eventurl = urlparse.urlparse(urls['event_sub_url'])
2293 ctrlurl = urlparse.urlparse(urls['control_url'])
2294
2295 url = urlparse.urlparse(location)
2296 conn = httplib.HTTPConnection(url.netloc)
2297
2298 class WPSERHTTPServer(SocketServer.StreamRequestHandler):
2299 def handle(self):
2300 data = self.rfile.readline().strip()
2301 logger.debug(data)
2302 self.wfile.write(gen_wps_event())
2303
2304 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
2305 server.timeout = 1
2306
2307 headers = { "callback": '<http://127.0.0.1:12345/event>',
2308 "NT": "upnp:event",
2309 "timeout": "Second-1234" }
2310 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2311 resp = conn.getresponse()
2312 if resp.status != 200:
2313 raise Exception("Unexpected HTTP response: %d" % resp.status)
2314 sid = resp.getheader("sid")
2315 logger.debug("Subscription SID " + sid)
2316
2317 msg = '''<?xml version="1.0"?>
2318<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
2319<s:Body>
2320<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
2321<NewMessage>EEoAARAQQQABARASAAIAABBTAAIxSBBJAA4ANyoAASABBv///////xBIABA2LbR7pTpRkYj7
2322VFi5hrLk
2323</NewMessage>
2324</u:SetSelectedRegistrar>
2325</s:Body>
2326</s:Envelope>'''
2327 headers = { "Content-type": 'text/xml; charset="utf-8"' }
2328 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
2329 conn.request("POST", ctrlurl.path, msg, headers)
2330 resp = conn.getresponse()
2331 if resp.status != 200:
2332 raise Exception("Unexpected HTTP response: %d" % resp.status)
2333
2334 server.handle_request()
2335
91f3cf69
JM
2336 logger.info("Start WPS_PBC and wait for PBC walk time expiration")
2337 if "OK" not in dev[0].request("WPS_PBC"):
2338 raise Exception("WPS_PBC failed")
31e56b95
JM
2339
2340 start = os.times()[4]
2341
2342 server.handle_request()
2343 dev[1].request("BSS_FLUSH 0")
2344 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2345 only_new=True)
2346 bss = dev[1].get_bss(apdev[0]['bssid'])
2347 logger.debug("BSS: " + str(bss))
2348 if '[WPS-AUTH]' not in bss['flags']:
2349 raise Exception("WPS not indicated authorized")
2350
2351 server.handle_request()
2352
2353 wps_timeout_seen = False
2354
2355 while True:
2356 hapd.dump_monitor()
2357 dev[1].dump_monitor()
2358 if not wps_timeout_seen:
2359 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=0)
2360 if ev is not None:
2361 logger.info("PBC timeout seen")
2362 wps_timeout_seen = True
2363 else:
2364 dev[0].dump_monitor()
2365 now = os.times()[4]
2366 if now - start > 130:
2367 raise Exception("Selected registration information not removed")
2368 dev[1].request("BSS_FLUSH 0")
2369 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2370 only_new=True)
2371 bss = dev[1].get_bss(apdev[0]['bssid'])
2372 logger.debug("BSS: " + str(bss))
2373 if '[WPS-AUTH]' not in bss['flags']:
2374 break
2375 server.handle_request()
2376
2377 server.server_close()
2378
2379 if wps_timeout_seen:
2380 return
2381
2382 now = os.times()[4]
2383 if now < start + 150:
2384 dur = start + 150 - now
2385 else:
2386 dur = 1
2387 logger.info("Continue waiting for PBC timeout (%d sec)" % dur)
2388 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=dur)
91f3cf69
JM
2389 if ev is None:
2390 raise Exception("WPS-TIMEOUT not reported")
2391
21aa8b7e 2392def add_ssdp_ap(ap, ap_uuid):
44ff0400
JM
2393 ssid = "wps-ssdp"
2394 ap_pin = "12345670"
24b7f282
JM
2395 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2396 "wpa_passphrase": "12345678", "wpa": "2",
2397 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2398 "device_name": "Wireless AP", "manufacturer": "Company",
2399 "model_name": "WAP", "model_number": "123",
2400 "serial_number": "12345", "device_type": "6-0050F204-1",
2401 "os_version": "01020300",
2402 "config_methods": "label push_button",
2403 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
2404 "friendly_name": "WPS Access Point",
2405 "manufacturer_url": "http://www.example.com/",
2406 "model_description": "Wireless Access Point",
2407 "model_url": "http://www.example.com/model/",
2408 "upc": "123456789012" }
21aa8b7e 2409 return hostapd.add_ap(ap, params)
44ff0400
JM
2410
2411def ssdp_send(msg, no_recv=False):
2412 socket.setdefaulttimeout(1)
2413 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2414 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2415 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2416 sock.bind(("127.0.0.1", 0))
2417 sock.sendto(msg, ("239.255.255.250", 1900))
2418 if no_recv:
2419 return None
2420 return sock.recv(1000)
2421
96038a5f 2422def ssdp_send_msearch(st, no_recv=False):
44ff0400
JM
2423 msg = '\r\n'.join([
2424 'M-SEARCH * HTTP/1.1',
2425 'HOST: 239.255.255.250:1900',
2426 'MX: 1',
2427 'MAN: "ssdp:discover"',
2428 'ST: ' + st,
2429 '', ''])
96038a5f 2430 return ssdp_send(msg, no_recv=no_recv)
44ff0400
JM
2431
2432def test_ap_wps_ssdp_msearch(dev, apdev):
2433 """WPS AP and SSDP M-SEARCH messages"""
2434 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2435 add_ssdp_ap(apdev[0], ap_uuid)
44ff0400
JM
2436
2437 msg = '\r\n'.join([
2438 'M-SEARCH * HTTP/1.1',
2439 'Host: 239.255.255.250:1900',
2440 'Mx: 1',
2441 'Man: "ssdp:discover"',
2442 'St: urn:schemas-wifialliance-org:device:WFADevice:1',
2443 '', ''])
2444 ssdp_send(msg)
2445
2446 msg = '\r\n'.join([
2447 'M-SEARCH * HTTP/1.1',
2448 'host:\t239.255.255.250:1900\t\t\t\t \t\t',
2449 'mx: \t1\t\t ',
2450 'man: \t \t "ssdp:discover" ',
2451 'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
2452 '', ''])
2453 ssdp_send(msg)
2454
2455 ssdp_send_msearch("ssdp:all")
2456 ssdp_send_msearch("upnp:rootdevice")
2457 ssdp_send_msearch("uuid:" + ap_uuid)
2458 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
2459 ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1");
2460
2461 msg = '\r\n'.join([
2462 'M-SEARCH * HTTP/1.1',
2463 'HOST:\t239.255.255.250:1900',
2464 'MAN: "ssdp:discover"',
2465 'MX: 130',
2466 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2467 '', ''])
2468 ssdp_send(msg, no_recv=True)
2469
2470def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
2471 """WPS AP and invalid SSDP M-SEARCH messages"""
2472 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2473 add_ssdp_ap(apdev[0], ap_uuid)
44ff0400
JM
2474
2475 socket.setdefaulttimeout(1)
2476 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2477 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2478 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2479 sock.bind(("127.0.0.1", 0))
2480
2481 logger.debug("Missing MX")
2482 msg = '\r\n'.join([
2483 'M-SEARCH * HTTP/1.1',
2484 'HOST: 239.255.255.250:1900',
2485 'MAN: "ssdp:discover"',
2486 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2487 '', ''])
2488 sock.sendto(msg, ("239.255.255.250", 1900))
2489
2490 logger.debug("Negative MX")
2491 msg = '\r\n'.join([
2492 'M-SEARCH * HTTP/1.1',
2493 'HOST: 239.255.255.250:1900',
2494 'MX: -1',
2495 'MAN: "ssdp:discover"',
2496 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2497 '', ''])
2498 sock.sendto(msg, ("239.255.255.250", 1900))
2499
2500 logger.debug("Invalid MX")
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 MAN")
2511 msg = '\r\n'.join([
2512 'M-SEARCH * HTTP/1.1',
2513 'HOST: 239.255.255.250:1900',
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("Invalid MAN")
2520 msg = '\r\n'.join([
2521 'M-SEARCH * HTTP/1.1',
2522 'HOST: 239.255.255.250:1900',
2523 'MX: 1',
2524 'MAN: foo',
2525 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2526 '', ''])
2527 sock.sendto(msg, ("239.255.255.250", 1900))
2528 msg = '\r\n'.join([
2529 'M-SEARCH * HTTP/1.1',
2530 'HOST: 239.255.255.250:1900',
2531 'MX: 1',
2532 'MAN; "ssdp:discover"',
2533 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2534 '', ''])
2535 sock.sendto(msg, ("239.255.255.250", 1900))
2536
2537 logger.debug("Missing HOST")
2538 msg = '\r\n'.join([
2539 'M-SEARCH * HTTP/1.1',
2540 'MAN: "ssdp:discover"',
2541 'MX: 1',
2542 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2543 '', ''])
2544 sock.sendto(msg, ("239.255.255.250", 1900))
2545
2546 logger.debug("Missing ST")
2547 msg = '\r\n'.join([
2548 'M-SEARCH * HTTP/1.1',
2549 'HOST: 239.255.255.250:1900',
2550 'MAN: "ssdp:discover"',
2551 'MX: 1',
2552 '', ''])
2553 sock.sendto(msg, ("239.255.255.250", 1900))
2554
2555 logger.debug("Mismatching ST")
2556 msg = '\r\n'.join([
2557 'M-SEARCH * HTTP/1.1',
2558 'HOST: 239.255.255.250:1900',
2559 'MAN: "ssdp:discover"',
2560 'MX: 1',
2561 'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
2562 '', ''])
2563 sock.sendto(msg, ("239.255.255.250", 1900))
2564 msg = '\r\n'.join([
2565 'M-SEARCH * HTTP/1.1',
2566 'HOST: 239.255.255.250:1900',
2567 'MAN: "ssdp:discover"',
2568 'MX: 1',
2569 'ST: foo:bar',
2570 '', ''])
2571 sock.sendto(msg, ("239.255.255.250", 1900))
2572 msg = '\r\n'.join([
2573 'M-SEARCH * HTTP/1.1',
2574 'HOST: 239.255.255.250:1900',
2575 'MAN: "ssdp:discover"',
2576 'MX: 1',
2577 'ST: foobar',
2578 '', ''])
2579 sock.sendto(msg, ("239.255.255.250", 1900))
2580
2581 logger.debug("Invalid ST")
2582 msg = '\r\n'.join([
2583 'M-SEARCH * HTTP/1.1',
2584 'HOST: 239.255.255.250:1900',
2585 'MAN: "ssdp:discover"',
2586 'MX: 1',
2587 'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
2588 '', ''])
2589 sock.sendto(msg, ("239.255.255.250", 1900))
2590
2591 logger.debug("Invalid M-SEARCH")
2592 msg = '\r\n'.join([
2593 'M+SEARCH * HTTP/1.1',
2594 'HOST: 239.255.255.250:1900',
2595 'MAN: "ssdp:discover"',
2596 'MX: 1',
2597 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2598 '', ''])
2599 sock.sendto(msg, ("239.255.255.250", 1900))
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 logger.debug("Invalid message format")
2610 sock.sendto("NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
2611 msg = '\r'.join([
2612 'M-SEARCH * HTTP/1.1',
2613 'HOST: 239.255.255.250:1900',
2614 'MAN: "ssdp:discover"',
2615 'MX: 1',
2616 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2617 '', ''])
2618 sock.sendto(msg, ("239.255.255.250", 1900))
2619
2620 try:
2621 r = sock.recv(1000)
2622 raise Exception("Unexpected M-SEARCH response: " + r)
2623 except socket.timeout:
2624 pass
2625
2626 logger.debug("Valid M-SEARCH")
2627 msg = '\r\n'.join([
2628 'M-SEARCH * HTTP/1.1',
2629 'HOST: 239.255.255.250:1900',
2630 'MAN: "ssdp:discover"',
2631 'MX: 1',
2632 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2633 '', ''])
2634 sock.sendto(msg, ("239.255.255.250", 1900))
2635
2636 try:
2637 r = sock.recv(1000)
2638 pass
2639 except socket.timeout:
2640 raise Exception("No SSDP response")
2641
2642def test_ap_wps_ssdp_burst(dev, apdev):
2643 """WPS AP and SSDP burst"""
2644 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2645 add_ssdp_ap(apdev[0], ap_uuid)
44ff0400
JM
2646
2647 msg = '\r\n'.join([
2648 'M-SEARCH * HTTP/1.1',
2649 'HOST: 239.255.255.250:1900',
2650 'MAN: "ssdp:discover"',
2651 'MX: 1',
2652 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2653 '', ''])
2654 socket.setdefaulttimeout(1)
2655 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2656 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2657 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2658 sock.bind(("127.0.0.1", 0))
2659 for i in range(0, 25):
2660 sock.sendto(msg, ("239.255.255.250", 1900))
2661 resp = 0
2662 while True:
2663 try:
2664 r = sock.recv(1000)
2665 if not r.startswith("HTTP/1.1 200 OK\r\n"):
2666 raise Exception("Unexpected message: " + r)
2667 resp += 1
2668 except socket.timeout:
2669 break
2670 if resp < 20:
2671 raise Exception("Too few SSDP responses")
2672
2673 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2674 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2675 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2676 sock.bind(("127.0.0.1", 0))
2677 for i in range(0, 25):
2678 sock.sendto(msg, ("239.255.255.250", 1900))
2679 while True:
2680 try:
2681 r = sock.recv(1000)
2682 if ap_uuid in r:
2683 break
2684 except socket.timeout:
2685 raise Exception("No SSDP response")
47c549fd
JM
2686
2687def ssdp_get_location(uuid):
2688 res = ssdp_send_msearch("uuid:" + uuid)
2689 location = None
2690 for l in res.splitlines():
2691 if l.lower().startswith("location:"):
2692 location = l.split(':', 1)[1].strip()
2693 break
2694 if location is None:
2695 raise Exception("No UPnP location found")
2696 return location
2697
2698def upnp_get_urls(location):
aa713e71 2699 conn = urllib.urlopen(location, proxies={})
47c549fd
JM
2700 tree = ET.parse(conn)
2701 root = tree.getroot()
2702 urn = '{urn:schemas-upnp-org:device-1-0}'
2703 service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
2704 res = {}
2705 res['scpd_url'] = urlparse.urljoin(location, service.find(urn + 'SCPDURL').text)
2706 res['control_url'] = urlparse.urljoin(location, service.find(urn + 'controlURL').text)
2707 res['event_sub_url'] = urlparse.urljoin(location, service.find(urn + 'eventSubURL').text)
2708 return res
2709
dd124ee8
JM
2710def upnp_soap_action(conn, path, action, include_soap_action=True,
2711 soap_action_override=None, newmsg=None, neweventtype=None,
2712 neweventmac=None):
47c549fd
JM
2713 soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
2714 wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
2715 ET.register_namespace('soapenv', soapns)
2716 ET.register_namespace('wfa', wpsns)
2717 attrib = {}
2718 attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
2719 root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
2720 body = ET.SubElement(root, "{%s}Body" % soapns)
2721 act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
dd124ee8
JM
2722 if newmsg:
2723 msg = ET.SubElement(act, "NewMessage")
2724 msg.text = base64.b64encode(newmsg)
2725 if neweventtype:
2726 msg = ET.SubElement(act, "NewWLANEventType")
2727 msg.text = neweventtype
2728 if neweventmac:
2729 msg = ET.SubElement(act, "NewWLANEventMAC")
2730 msg.text = neweventmac
47c549fd
JM
2731 tree = ET.ElementTree(root)
2732 soap = StringIO.StringIO()
2733 tree.write(soap, xml_declaration=True, encoding='utf-8')
2734
2735 headers = { "Content-type": 'text/xml; charset="utf-8"' }
2736 if include_soap_action:
2737 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
2738 elif soap_action_override:
2739 headers["SOAPAction"] = soap_action_override
2740 conn.request("POST", path, soap.getvalue(), headers)
2741 return conn.getresponse()
2742
2743def test_ap_wps_upnp(dev, apdev):
2744 """WPS AP and UPnP operations"""
2745 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2746 add_ssdp_ap(apdev[0], ap_uuid)
47c549fd
JM
2747
2748 location = ssdp_get_location(ap_uuid)
2749 urls = upnp_get_urls(location)
2750
aa713e71 2751 conn = urllib.urlopen(urls['scpd_url'], proxies={})
47c549fd
JM
2752 scpd = conn.read()
2753
aa713e71
AO
2754 conn = urllib.urlopen(urlparse.urljoin(location, "unknown.html"),
2755 proxies={})
47c549fd
JM
2756 if conn.getcode() != 404:
2757 raise Exception("Unexpected HTTP response to GET unknown URL")
2758
2759 url = urlparse.urlparse(location)
2760 conn = httplib.HTTPConnection(url.netloc)
2761 #conn.set_debuglevel(1)
2762 headers = { "Content-type": 'text/xml; charset="utf-8"',
2763 "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"' }
2764 conn.request("POST", "hello", "\r\n\r\n", headers)
2765 resp = conn.getresponse()
2766 if resp.status != 404:
5c267d71 2767 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2768
2769 conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
2770 resp = conn.getresponse()
2771 if resp.status != 501:
5c267d71 2772 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2773
2774 headers = { "Content-type": 'text/xml; charset="utf-8"',
2775 "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"' }
2776 ctrlurl = urlparse.urlparse(urls['control_url'])
2777 conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
2778 resp = conn.getresponse()
2779 if resp.status != 401:
5c267d71 2780 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2781
2782 logger.debug("GetDeviceInfo without SOAPAction header")
2783 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2784 include_soap_action=False)
2785 if resp.status != 401:
5c267d71 2786 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2787
2788 logger.debug("GetDeviceInfo with invalid SOAPAction header")
2789 for act in [ "foo",
2790 "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
2791 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
2792 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
2793 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2794 include_soap_action=False,
2795 soap_action_override=act)
2796 if resp.status != 401:
5c267d71 2797 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2798
2799 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
2800 if resp.status != 200:
5c267d71 2801 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2802 dev = resp.read()
2803 if "NewDeviceInfo" not in dev:
2804 raise Exception("Unexpected GetDeviceInfo response")
2805
2806 logger.debug("PutMessage without required parameters")
2807 resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
2808 if resp.status != 600:
5c267d71 2809 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2810
2811 logger.debug("PutWLANResponse without required parameters")
2812 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
2813 if resp.status != 600:
5c267d71 2814 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2815
2816 logger.debug("SetSelectedRegistrar from unregistered ER")
2817 resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
2818 if resp.status != 501:
5c267d71 2819 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2820
2821 logger.debug("Unknown action")
2822 resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
2823 if resp.status != 401:
5c267d71 2824 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2825
2826def test_ap_wps_upnp_subscribe(dev, apdev):
2827 """WPS AP and UPnP event subscription"""
2828 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2829 hapd = add_ssdp_ap(apdev[0], ap_uuid)
47c549fd
JM
2830
2831 location = ssdp_get_location(ap_uuid)
2832 urls = upnp_get_urls(location)
2833 eventurl = urlparse.urlparse(urls['event_sub_url'])
2834
2835 url = urlparse.urlparse(location)
2836 conn = httplib.HTTPConnection(url.netloc)
2837 #conn.set_debuglevel(1)
2838 headers = { "callback": '<http://127.0.0.1:12345/event>',
2839 "timeout": "Second-1234" }
2840 conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
2841 resp = conn.getresponse()
2842 if resp.status != 412:
5c267d71 2843 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2844
2845 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2846 resp = conn.getresponse()
2847 if resp.status != 412:
5c267d71 2848 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2849
2850 headers = { "NT": "upnp:event",
2851 "timeout": "Second-1234" }
2852 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2853 resp = conn.getresponse()
2854 if resp.status != 412:
5c267d71 2855 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2856
2857 headers = { "callback": '<http://127.0.0.1:12345/event>',
2858 "NT": "upnp:foobar",
2859 "timeout": "Second-1234" }
2860 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2861 resp = conn.getresponse()
2862 if resp.status != 400:
5c267d71 2863 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2864
2865 logger.debug("Valid subscription")
2866 headers = { "callback": '<http://127.0.0.1:12345/event>',
2867 "NT": "upnp:event",
2868 "timeout": "Second-1234" }
2869 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2870 resp = conn.getresponse()
2871 if resp.status != 200:
5c267d71 2872 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2873 sid = resp.getheader("sid")
2874 logger.debug("Subscription SID " + sid)
2875
2876 logger.debug("Invalid re-subscription")
2877 headers = { "NT": "upnp:event",
2878 "sid": "123456734567854",
2879 "timeout": "Second-1234" }
2880 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2881 resp = conn.getresponse()
2882 if resp.status != 400:
5c267d71 2883 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2884
2885 logger.debug("Invalid re-subscription")
2886 headers = { "NT": "upnp:event",
2887 "sid": "uuid:123456734567854",
2888 "timeout": "Second-1234" }
2889 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2890 resp = conn.getresponse()
2891 if resp.status != 400:
5c267d71 2892 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2893
2894 logger.debug("Invalid re-subscription")
2895 headers = { "callback": '<http://127.0.0.1:12345/event>',
2896 "NT": "upnp:event",
2897 "sid": sid,
2898 "timeout": "Second-1234" }
2899 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2900 resp = conn.getresponse()
2901 if resp.status != 400:
5c267d71 2902 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2903
2904 logger.debug("SID mismatch in re-subscription")
2905 headers = { "NT": "upnp:event",
2906 "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
2907 "timeout": "Second-1234" }
2908 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2909 resp = conn.getresponse()
2910 if resp.status != 412:
5c267d71 2911 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2912
2913 logger.debug("Valid re-subscription")
2914 headers = { "NT": "upnp:event",
2915 "sid": sid,
2916 "timeout": "Second-1234" }
2917 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2918 resp = conn.getresponse()
2919 if resp.status != 200:
5c267d71 2920 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2921 sid2 = resp.getheader("sid")
2922 logger.debug("Subscription SID " + sid2)
2923
2924 if sid != sid2:
2925 raise Exception("Unexpected SID change")
2926
2927 logger.debug("Valid re-subscription")
2928 headers = { "NT": "upnp:event",
2929 "sid": "uuid: \t \t" + sid.split(':')[1],
2930 "timeout": "Second-1234" }
2931 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2932 resp = conn.getresponse()
2933 if resp.status != 200:
5c267d71 2934 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2935
2936 logger.debug("Invalid unsubscription")
2937 headers = { "sid": sid }
2938 conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
2939 resp = conn.getresponse()
2940 if resp.status != 412:
5c267d71 2941 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2942 headers = { "foo": "bar" }
2943 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2944 resp = conn.getresponse()
2945 if resp.status != 412:
5c267d71 2946 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2947
2948 logger.debug("Valid unsubscription")
2949 headers = { "sid": sid }
2950 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2951 resp = conn.getresponse()
2952 if resp.status != 200:
5c267d71 2953 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2954
2955 logger.debug("Unsubscription for not existing SID")
2956 headers = { "sid": sid }
2957 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2958 resp = conn.getresponse()
2959 if resp.status != 412:
5c267d71 2960 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2961
2962 logger.debug("Invalid unsubscription")
2963 headers = { "sid": " \t \tfoo" }
2964 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2965 resp = conn.getresponse()
2966 if resp.status != 400:
5c267d71 2967 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2968
2969 logger.debug("Invalid unsubscription")
2970 headers = { "sid": "uuid:\t \tfoo" }
2971 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2972 resp = conn.getresponse()
2973 if resp.status != 400:
5c267d71 2974 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2975
2976 logger.debug("Invalid unsubscription")
2977 headers = { "NT": "upnp:event",
2978 "sid": sid }
2979 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2980 resp = conn.getresponse()
2981 if resp.status != 400:
5c267d71 2982 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2983 headers = { "callback": '<http://127.0.0.1:12345/event>',
2984 "sid": sid }
2985 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2986 resp = conn.getresponse()
2987 if resp.status != 400:
5c267d71 2988 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2989
2990 logger.debug("Valid subscription with multiple callbacks")
2991 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>',
2992 "NT": "upnp:event",
2993 "timeout": "Second-1234" }
2994 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2995 resp = conn.getresponse()
2996 if resp.status != 200:
5c267d71 2997 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2998 sid = resp.getheader("sid")
2999 logger.debug("Subscription SID " + sid)
d352c407 3000
24b7f282
JM
3001 # Force subscription to be deleted due to errors
3002 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3003 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3004 with alloc_fail(hapd, 1, "event_build_message"):
3005 for i in range(10):
3006 dev[1].dump_monitor()
3007 dev[2].dump_monitor()
3008 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3009 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3010 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3011 dev[1].request("WPS_CANCEL")
3012 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3013 dev[2].request("WPS_CANCEL")
3014 if i % 4 == 1:
3015 time.sleep(1)
3016 else:
3017 time.sleep(0.1)
3018 time.sleep(0.2)
3019
3020 headers = { "sid": sid }
3021 conn.request("UNSUBSCRIBE", eventurl.path, "", headers)
3022 resp = conn.getresponse()
3023 if resp.status != 200 and resp.status != 412:
3024 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3025
3026 headers = { "callback": '<http://127.0.0.1:12345/event>',
3027 "NT": "upnp:event",
3028 "timeout": "Second-1234" }
3029 with alloc_fail(hapd, 1, "http_client_addr;event_send_start"):
3030 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3031 resp = conn.getresponse()
3032 if resp.status != 200:
3033 raise Exception("Unexpected HTTP response for SUBSCRIBE: %d" % resp.status)
3034 sid = resp.getheader("sid")
3035 logger.debug("Subscription SID " + sid)
3036
3037 headers = { "sid": sid }
3038 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3039 resp = conn.getresponse()
3040 if resp.status != 200:
3041 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3042
3043 headers = { "callback": '<http://127.0.0.1:12345/event>',
3044 "NT": "upnp:event",
3045 "timeout": "Second-1234" }
3046 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3047 resp = conn.getresponse()
3048 if resp.status != 200:
3049 raise Exception("Unexpected HTTP response: %d" % resp.status)
3050 sid = resp.getheader("sid")
3051 logger.debug("Subscription SID " + sid)
3052
3053 with alloc_fail(hapd, 1, "=event_add"):
3054 for i in range(2):
3055 dev[1].dump_monitor()
3056 dev[2].dump_monitor()
3057 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3058 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3059 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3060 dev[1].request("WPS_CANCEL")
3061 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3062 dev[2].request("WPS_CANCEL")
3063 if i == 0:
3064 time.sleep(1)
3065 else:
3066 time.sleep(0.1)
3067
3068 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3069 resp = conn.getresponse()
3070 if resp.status != 200:
3071 raise Exception("Unexpected HTTP response: %d" % resp.status)
3072
3073 with alloc_fail(hapd, 1, "wpabuf_dup;event_add"):
3074 dev[1].dump_monitor()
3075 dev[2].dump_monitor()
3076 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3077 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3078 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3079 dev[1].request("WPS_CANCEL")
3080 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3081 dev[2].request("WPS_CANCEL")
3082 time.sleep(0.1)
3083
3084 with fail_test(hapd, 1, "os_get_random;uuid_make;subscription_start"):
3085 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3086 resp = conn.getresponse()
3087 if resp.status != 500:
3088 raise Exception("Unexpected HTTP response: %d" % resp.status)
3089
3090 with alloc_fail(hapd, 1, "=subscription_start"):
3091 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3092 resp = conn.getresponse()
3093 if resp.status != 500:
3094 raise Exception("Unexpected HTTP response: %d" % resp.status)
3095
3096 headers = { "callback": '',
3097 "NT": "upnp:event",
3098 "timeout": "Second-1234" }
3099 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3100 resp = conn.getresponse()
3101 if resp.status != 500:
3102 raise Exception("Unexpected HTTP response: %d" % resp.status)
3103
3104 headers = { "callback": ' <',
3105 "NT": "upnp:event",
3106 "timeout": "Second-1234" }
3107 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3108 resp = conn.getresponse()
3109 if resp.status != 500:
3110 raise Exception("Unexpected HTTP response: %d" % resp.status)
3111
3112 headers = { "callback": '<http://127.0.0.1:12345/event>',
3113 "NT": "upnp:event",
3114 "timeout": "Second-1234" }
3115 with alloc_fail(hapd, 1, "wpabuf_alloc;subscription_first_event"):
3116 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3117 resp = conn.getresponse()
3118 if resp.status != 500:
3119 raise Exception("Unexpected HTTP response: %d" % resp.status)
3120
3121 with alloc_fail(hapd, 1, "event_add;subscription_first_event"):
3122 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3123 resp = conn.getresponse()
3124 if resp.status != 500:
3125 raise Exception("Unexpected HTTP response: %d" % resp.status)
3126
3127 with alloc_fail(hapd, 1, "subscr_addr_add_url"):
3128 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3129 resp = conn.getresponse()
3130 if resp.status != 500:
3131 raise Exception("Unexpected HTTP response: %d" % resp.status)
3132
3133 with alloc_fail(hapd, 2, "subscr_addr_add_url"):
3134 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3135 resp = conn.getresponse()
3136 if resp.status != 500:
3137 raise Exception("Unexpected HTTP response: %d" % resp.status)
3138
3139 for i in range(6):
3140 headers = { "callback": '<http://127.0.0.1:%d/event>' % (12345 + i),
3141 "NT": "upnp:event",
3142 "timeout": "Second-1234" }
3143 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3144 resp = conn.getresponse()
3145 if resp.status != 200:
3146 raise Exception("Unexpected HTTP response: %d" % resp.status)
3147
3148 with alloc_fail(hapd, 1, "=upnp_wps_device_send_wlan_event"):
3149 dev[1].dump_monitor()
3150 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3151 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3152 dev[1].request("WPS_CANCEL")
3153 time.sleep(0.1)
3154
3155 with alloc_fail(hapd, 1, "wpabuf_alloc;upnp_wps_device_send_event"):
3156 dev[1].dump_monitor()
3157 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3158 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3159 dev[1].request("WPS_CANCEL")
3160 time.sleep(0.1)
3161
3162 with alloc_fail(hapd, 1, "base64_encode;upnp_wps_device_send_wlan_event"):
3163 dev[1].dump_monitor()
3164 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3165 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3166 dev[1].request("WPS_CANCEL")
3167 time.sleep(0.1)
3168
3169 hapd.disable()
3170 with alloc_fail(hapd, 1, "get_netif_info"):
3171 if "FAIL" not in hapd.request("ENABLE"):
3172 raise Exception("ENABLE succeeded during OOM")
3173
d91a64c4
JM
3174def test_ap_wps_upnp_subscribe_events(dev, apdev):
3175 """WPS AP and UPnP event subscription and many events"""
3176 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 3177 hapd = add_ssdp_ap(apdev[0], ap_uuid)
d91a64c4
JM
3178
3179 location = ssdp_get_location(ap_uuid)
3180 urls = upnp_get_urls(location)
3181 eventurl = urlparse.urlparse(urls['event_sub_url'])
3182
3183 class WPSERHTTPServer(SocketServer.StreamRequestHandler):
3184 def handle(self):
3185 data = self.rfile.readline().strip()
3186 logger.debug(data)
3187 self.wfile.write(gen_wps_event())
3188
3189 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
3190 server.timeout = 1
3191
3192 url = urlparse.urlparse(location)
3193 conn = httplib.HTTPConnection(url.netloc)
3194
3195 headers = { "callback": '<http://127.0.0.1:12345/event>',
3196 "NT": "upnp:event",
3197 "timeout": "Second-1234" }
3198 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3199 resp = conn.getresponse()
3200 if resp.status != 200:
3201 raise Exception("Unexpected HTTP response: %d" % resp.status)
3202 sid = resp.getheader("sid")
3203 logger.debug("Subscription SID " + sid)
3204
3205 # Fetch the first event message
3206 server.handle_request()
3207
3208 # Force subscription event queue to reach the maximum length by generating
3209 # new proxied events without the ER fetching any of the pending events.
3210 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3211 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3212 for i in range(16):
3213 dev[1].dump_monitor()
3214 dev[2].dump_monitor()
3215 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3216 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3217 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3218 dev[1].request("WPS_CANCEL")
3219 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3220 dev[2].request("WPS_CANCEL")
3221 if i % 4 == 1:
3222 time.sleep(1)
3223 else:
3224 time.sleep(0.1)
3225
3226 hapd.request("WPS_PIN any 12345670")
3227 dev[1].dump_monitor()
3228 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3229 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=10)
3230 if ev is None:
3231 raise Exception("WPS success not reported")
3232
3233 # Close the WPS ER HTTP server without fetching all the pending events.
3234 # This tests hostapd code path that clears subscription and the remaining
3235 # event queue when the interface is deinitialized.
3236 server.handle_request()
3237 server.server_close()
3238
3239 dev[1].wait_connected()
3240
b2047531
JM
3241def test_ap_wps_upnp_http_proto(dev, apdev):
3242 """WPS AP and UPnP/HTTP protocol testing"""
3243 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 3244 add_ssdp_ap(apdev[0], ap_uuid)
b2047531
JM
3245
3246 location = ssdp_get_location(ap_uuid)
3247
3248 url = urlparse.urlparse(location)
81f8e7e9 3249 conn = httplib.HTTPConnection(url.netloc, timeout=0.2)
b2047531
JM
3250 #conn.set_debuglevel(1)
3251
3252 conn.request("HEAD", "hello")
3253 resp = conn.getresponse()
3254 if resp.status != 501:
3255 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3256 conn.close()
3257
3258 for cmd in [ "PUT", "DELETE", "TRACE", "CONNECT", "M-SEARCH", "M-POST" ]:
3259 try:
3260 conn.request(cmd, "hello")
3261 resp = conn.getresponse()
3262 except Exception, e:
3263 pass
3264 conn.close()
3265
3266 headers = { "Content-Length": 'abc' }
3267 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3268 try:
3269 resp = conn.getresponse()
3270 except Exception, e:
3271 pass
3272 conn.close()
3273
3274 headers = { "Content-Length": '-10' }
3275 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3276 try:
3277 resp = conn.getresponse()
3278 except Exception, e:
3279 pass
3280 conn.close()
3281
3282 headers = { "Content-Length": '10000000000000' }
3283 conn.request("HEAD", "hello", "\r\n\r\nhello", headers)
3284 try:
3285 resp = conn.getresponse()
3286 except Exception, e:
3287 pass
3288 conn.close()
3289
3290 headers = { "Transfer-Encoding": 'abc' }
3291 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3292 resp = conn.getresponse()
3293 if resp.status != 501:
3294 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3295 conn.close()
3296
3297 headers = { "Transfer-Encoding": 'chunked' }
3298 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3299 resp = conn.getresponse()
3300 if resp.status != 501:
3301 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3302 conn.close()
3303
3304 # Too long a header
3305 conn.request("HEAD", 5000 * 'A')
3306 try:
3307 resp = conn.getresponse()
3308 except Exception, e:
3309 pass
3310 conn.close()
3311
3312 # Long URL but within header length limits
3313 conn.request("HEAD", 3000 * 'A')
3314 resp = conn.getresponse()
3315 if resp.status != 501:
3316 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3317 conn.close()
3318
3319 headers = { "Content-Length": '20' }
3320 conn.request("POST", "hello", 10 * 'A' + "\r\n\r\n", headers)
3321 try:
3322 resp = conn.getresponse()
3323 except Exception, e:
3324 pass
3325 conn.close()
3326
3327 conn.request("POST", "hello", 5000 * 'A' + "\r\n\r\n")
3328 resp = conn.getresponse()
3329 if resp.status != 404:
5c267d71 3330 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
3331 conn.close()
3332
3333 conn.request("POST", "hello", 60000 * 'A' + "\r\n\r\n")
3334 try:
3335 resp = conn.getresponse()
3336 except Exception, e:
3337 pass
3338 conn.close()
3339
3340def test_ap_wps_upnp_http_proto_chunked(dev, apdev):
3341 """WPS AP and UPnP/HTTP protocol testing for chunked encoding"""
3342 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 3343 add_ssdp_ap(apdev[0], ap_uuid)
b2047531
JM
3344
3345 location = ssdp_get_location(ap_uuid)
3346
3347 url = urlparse.urlparse(location)
3348 conn = httplib.HTTPConnection(url.netloc)
3349 #conn.set_debuglevel(1)
3350
3351 headers = { "Transfer-Encoding": 'chunked' }
3352 conn.request("POST", "hello",
3353 "a\r\nabcdefghij\r\n" + "2\r\nkl\r\n" + "0\r\n\r\n",
3354 headers)
3355 resp = conn.getresponse()
3356 if resp.status != 404:
5c267d71 3357 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
3358 conn.close()
3359
3360 conn.putrequest("POST", "hello")
3361 conn.putheader('Transfer-Encoding', 'chunked')
3362 conn.endheaders()
3363 conn.send("a\r\nabcdefghij\r\n")
3364 time.sleep(0.1)
3365 conn.send("2\r\nkl\r\n")
3366 conn.send("0\r\n\r\n")
3367 resp = conn.getresponse()
3368 if resp.status != 404:
5c267d71 3369 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
3370 conn.close()
3371
3372 conn.putrequest("POST", "hello")
3373 conn.putheader('Transfer-Encoding', 'chunked')
3374 conn.endheaders()
3375 completed = False
3376 try:
3377 for i in range(20000):
3378 conn.send("1\r\nZ\r\n")
3379 conn.send("0\r\n\r\n")
3380 resp = conn.getresponse()
3381 completed = True
3382 except Exception, e:
3383 pass
3384 conn.close()
3385 if completed:
3386 raise Exception("Too long chunked request did not result in connection reset")
3387
3388 headers = { "Transfer-Encoding": 'chunked' }
3389 conn.request("POST", "hello", "80000000\r\na", headers)
3390 try:
3391 resp = conn.getresponse()
3392 except Exception, e:
3393 pass
3394 conn.close()
3395
3396 conn.request("POST", "hello", "10000000\r\na", headers)
3397 try:
3398 resp = conn.getresponse()
3399 except Exception, e:
3400 pass
3401 conn.close()
3402
d352c407
JM
3403def test_ap_wps_disabled(dev, apdev):
3404 """WPS operations while WPS is disabled"""
3405 ssid = "test-wps-disabled"
6f334bf7 3406 hapd = hostapd.add_ap(apdev[0], { "ssid": ssid })
d352c407
JM
3407 if "FAIL" not in hapd.request("WPS_PBC"):
3408 raise Exception("WPS_PBC succeeded unexpectedly")
3409 if "FAIL" not in hapd.request("WPS_CANCEL"):
3410 raise Exception("WPS_CANCEL succeeded unexpectedly")
a0fd2ae6
JM
3411
3412def test_ap_wps_mixed_cred(dev, apdev):
3413 """WPS 2.0 STA merging mixed mode WPA/WPA2 credentials"""
3414 ssid = "test-wps-wep"
6f334bf7
JD
3415 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3416 "skip_cred_build": "1", "extra_cred": "wps-mixed-cred" }
3417 hapd = hostapd.add_ap(apdev[0], params)
a0fd2ae6 3418 hapd.request("WPS_PBC")
33d0b157
JM
3419 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3420 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
9ed53f5e 3421 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
a0fd2ae6
JM
3422 if ev is None:
3423 raise Exception("WPS-SUCCESS event timed out")
3424 nets = dev[0].list_networks()
3425 if len(nets) != 1:
3426 raise Exception("Unexpected number of network blocks")
3427 id = nets[0]['id']
3428 proto = dev[0].get_network(id, "proto")
3429 if proto != "WPA RSN":
3430 raise Exception("Unexpected merged proto field value: " + proto)
3431 pairwise = dev[0].get_network(id, "pairwise")
72a8e30b 3432 if pairwise != "CCMP TKIP" and pairwise != "CCMP GCMP TKIP":
a0fd2ae6 3433 raise Exception("Unexpected merged pairwise field value: " + pairwise)
e5a79e3f
JM
3434
3435def test_ap_wps_while_connected(dev, apdev):
3436 """WPS PBC provisioning while connected to another AP"""
3437 ssid = "test-wps-conf"
6f334bf7
JD
3438 hapd = hostapd.add_ap(apdev[0],
3439 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3440 "wpa_passphrase": "12345678", "wpa": "2",
3441 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e5a79e3f 3442
8b8a1864 3443 hostapd.add_ap(apdev[1], { "ssid": "open" })
e5a79e3f
JM
3444 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3445
3446 logger.info("WPS provisioning step")
3447 hapd.request("WPS_PBC")
3448 dev[0].dump_monitor()
33d0b157 3449 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 3450 dev[0].wait_connected(timeout=30)
e5a79e3f
JM
3451 status = dev[0].get_status()
3452 if status['bssid'] != apdev[0]['bssid']:
3453 raise Exception("Unexpected BSSID")
3454
3455def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
3456 """WPS PBC provisioning while connected to another AP and STA_AUTOCONNECT disabled"""
3457 ssid = "test-wps-conf"
6f334bf7
JD
3458 hapd = hostapd.add_ap(apdev[0],
3459 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3460 "wpa_passphrase": "12345678", "wpa": "2",
3461 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e5a79e3f 3462
8b8a1864 3463 hostapd.add_ap(apdev[1], { "ssid": "open" })
e5a79e3f
JM
3464
3465 try:
3466 dev[0].request("STA_AUTOCONNECT 0")
3467 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3468
3469 logger.info("WPS provisioning step")
3470 hapd.request("WPS_PBC")
3471 dev[0].dump_monitor()
33d0b157 3472 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 3473 dev[0].wait_connected(timeout=30)
e5a79e3f
JM
3474 status = dev[0].get_status()
3475 if status['bssid'] != apdev[0]['bssid']:
3476 raise Exception("Unexpected BSSID")
3477 finally:
3478 dev[0].request("STA_AUTOCONNECT 1")
3f08d1cd
JM
3479
3480def test_ap_wps_from_event(dev, apdev):
3481 """WPS PBC event on AP to enable PBC"""
3482 ssid = "test-wps-conf"
8b8a1864 3483 hapd = hostapd.add_ap(apdev[0],
3f08d1cd
JM
3484 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3485 "wpa_passphrase": "12345678", "wpa": "2",
3486 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
33d0b157 3487 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3f08d1cd 3488 dev[0].dump_monitor()
33d0b157
JM
3489 hapd.dump_monitor()
3490 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3f08d1cd
JM
3491
3492 ev = hapd.wait_event(['WPS-ENROLLEE-SEEN'], timeout=15)
3493 if ev is None:
3494 raise Exception("No WPS-ENROLLEE-SEEN event on AP")
3495 vals = ev.split(' ')
3496 if vals[1] != dev[0].p2p_interface_addr():
3497 raise Exception("Unexpected enrollee address: " + vals[1])
3498 if vals[5] != '4':
3499 raise Exception("Unexpected Device Password Id: " + vals[5])
3500 hapd.request("WPS_PBC")
5f35a5e2 3501 dev[0].wait_connected(timeout=30)
1531402e
JM
3502
3503def test_ap_wps_ap_scan_2(dev, apdev):
3504 """AP_SCAN 2 for WPS"""
3505 ssid = "test-wps-conf"
8b8a1864 3506 hapd = hostapd.add_ap(apdev[0],
1531402e
JM
3507 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3508 "wpa_passphrase": "12345678", "wpa": "2",
3509 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3510 hapd.request("WPS_PBC")
3511
3512 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
3513 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
4b9d79b6 3514 wpas.dump_monitor()
1531402e
JM
3515
3516 if "OK" not in wpas.request("AP_SCAN 2"):
3517 raise Exception("Failed to set AP_SCAN 2")
3518
e51c8b2e 3519 wpas.flush_scan_cache()
33d0b157 3520 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
4b9d79b6 3521 wpas.dump_monitor()
33d0b157 3522 wpas.request("WPS_PBC " + apdev[0]['bssid'])
1531402e
JM
3523 ev = wpas.wait_event(["WPS-SUCCESS"], timeout=15)
3524 if ev is None:
3525 raise Exception("WPS-SUCCESS event timed out")
5f35a5e2 3526 wpas.wait_connected(timeout=30)
4b9d79b6 3527 wpas.dump_monitor()
1531402e
JM
3528 wpas.request("DISCONNECT")
3529 wpas.request("BSS_FLUSH 0")
3530 wpas.dump_monitor()
3531 wpas.request("REASSOCIATE")
5f35a5e2 3532 wpas.wait_connected(timeout=30)
4b9d79b6 3533 wpas.dump_monitor()
a08fdb17
JM
3534
3535def test_ap_wps_eapol_workaround(dev, apdev):
3536 """EAPOL workaround code path for 802.1X header length mismatch"""
3537 ssid = "test-wps"
6f334bf7
JD
3538 hapd = hostapd.add_ap(apdev[0],
3539 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
a08fdb17
JM
3540 bssid = apdev[0]['bssid']
3541 hapd.request("SET ext_eapol_frame_io 1")
3542 dev[0].request("SET ext_eapol_frame_io 1")
3543 hapd.request("WPS_PBC")
3544 dev[0].request("WPS_PBC")
3545
3546 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3547 if ev is None:
3548 raise Exception("Timeout on EAPOL-TX from hostapd")
3549
3550 res = dev[0].request("EAPOL_RX " + bssid + " 020000040193000501FFFF")
3551 if "OK" not in res:
3552 raise Exception("EAPOL_RX to wpa_supplicant failed")
46dea617
JM
3553
3554def test_ap_wps_iteration(dev, apdev):
3555 """WPS PIN and iterate through APs without selected registrar"""
3556 ssid = "test-wps-conf"
8b8a1864 3557 hapd = hostapd.add_ap(apdev[0],
46dea617
JM
3558 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3559 "wpa_passphrase": "12345678", "wpa": "2",
3560 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3561
3562 ssid2 = "test-wps-conf2"
8b8a1864 3563 hapd2 = hostapd.add_ap(apdev[1],
46dea617
JM
3564 { "ssid": ssid2, "eap_server": "1", "wps_state": "2",
3565 "wpa_passphrase": "12345678", "wpa": "2",
3566 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3567
3568 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3569 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
3570 dev[0].dump_monitor()
3571 pin = dev[0].request("WPS_PIN any")
3572
3573 # Wait for iteration through all WPS APs to happen before enabling any
3574 # Registrar.
3575 for i in range(2):
3576 ev = dev[0].wait_event(["Associated with"], timeout=30)
3577 if ev is None:
3578 raise Exception("No association seen")
3579 ev = dev[0].wait_event(["WPS-M2D"], timeout=10)
3580 if ev is None:
3581 raise Exception("No M2D from AP")
3582 dev[0].wait_disconnected()
3583
3584 # Verify that each AP requested PIN
3585 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3586 if ev is None:
3587 raise Exception("No WPS-PIN-NEEDED event from AP")
3588 ev = hapd2.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3589 if ev is None:
3590 raise Exception("No WPS-PIN-NEEDED event from AP2")
3591
3592 # Provide PIN to one of the APs and verify that connection gets formed
3593 hapd.request("WPS_PIN any " + pin)
3594 dev[0].wait_connected(timeout=30)
2272f5aa
JM
3595
3596def test_ap_wps_iteration_error(dev, apdev):
3597 """WPS AP iteration on no Selected Registrar and error case with an AP"""
3598 ssid = "test-wps-conf-pin"
8b8a1864 3599 hapd = hostapd.add_ap(apdev[0],
2272f5aa
JM
3600 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3601 "wpa_passphrase": "12345678", "wpa": "2",
3602 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3603 "wps_independent": "1" })
3604 hapd.request("SET ext_eapol_frame_io 1")
3605 bssid = apdev[0]['bssid']
3606 pin = dev[0].wps_read_pin()
3607 dev[0].request("WPS_PIN any " + pin)
3608
3609 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3610 if ev is None:
3611 raise Exception("No EAPOL-TX (EAP-Request/Identity) from hostapd")
3612 dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
3613
3614 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3615 if ev is None:
3616 raise Exception("No EAPOL-TX (EAP-WSC/Start) from hostapd")
3617 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=5)
3618 if ev is None:
3619 raise Exception("No CTRL-EVENT-EAP-STARTED")
3620
3621 # Do not forward any more EAPOL frames to test wpa_supplicant behavior for
3622 # a case with an incorrectly behaving WPS AP.
3623
3624 # Start the real target AP and activate registrar on it.
8b8a1864 3625 hapd2 = hostapd.add_ap(apdev[1],
2272f5aa
JM
3626 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3627 "wpa_passphrase": "12345678", "wpa": "2",
3628 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3629 "wps_independent": "1" })
3630 hapd2.request("WPS_PIN any " + pin)
3631
3632 dev[0].wait_disconnected(timeout=15)
3633 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
3634 if ev is None:
3635 raise Exception("No CTRL-EVENT-EAP-STARTED for the second AP")
3636 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
3637 if ev is None:
3638 raise Exception("No WPS-CRED-RECEIVED for the second AP")
3639 dev[0].wait_connected(timeout=15)
d6f6a86a
JM
3640
3641def test_ap_wps_priority(dev, apdev):
3642 """WPS PIN provisioning with configured AP and wps_priority"""
3643 ssid = "test-wps-conf-pin"
6f334bf7
JD
3644 hapd = hostapd.add_ap(apdev[0],
3645 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3646 "wpa_passphrase": "12345678", "wpa": "2",
3647 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
d6f6a86a
JM
3648 logger.info("WPS provisioning step")
3649 pin = dev[0].wps_read_pin()
3650 hapd.request("WPS_PIN any " + pin)
3651 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3652 dev[0].dump_monitor()
3653 try:
3654 dev[0].request("SET wps_priority 6")
3655 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3656 dev[0].wait_connected(timeout=30)
3657 netw = dev[0].list_networks()
3658 prio = dev[0].get_network(netw[0]['id'], 'priority')
3659 if prio != '6':
3660 raise Exception("Unexpected network priority: " + prio)
3661 finally:
3662 dev[0].request("SET wps_priority 0")
2c3a0190 3663
df1d01cf
JM
3664def test_ap_wps_and_non_wps(dev, apdev):
3665 """WPS and non-WPS AP in single hostapd process"""
3666 params = { "ssid": "wps", "eap_server": "1", "wps_state": "1" }
8b8a1864 3667 hapd = hostapd.add_ap(apdev[0], params)
df1d01cf
JM
3668
3669 params = { "ssid": "no wps" }
8b8a1864 3670 hapd2 = hostapd.add_ap(apdev[1], params)
df1d01cf
JM
3671
3672 appin = hapd.request("WPS_AP_PIN random")
3673 if "FAIL" in appin:
3674 raise Exception("Could not generate random AP PIN")
3675 if appin not in hapd.request("WPS_AP_PIN get"):
3676 raise Exception("Could not fetch current AP PIN")
3677
3678 if "FAIL" in hapd.request("WPS_PBC"):
3679 raise Exception("WPS_PBC failed")
3680 if "FAIL" in hapd.request("WPS_CANCEL"):
3681 raise Exception("WPS_CANCEL failed")
3682
2c3a0190
JM
3683def test_ap_wps_init_oom(dev, apdev):
3684 """Initial AP configuration and OOM during PSK generation"""
3685 ssid = "test-wps"
3686 params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
8b8a1864 3687 hapd = hostapd.add_ap(apdev[0], params)
2c3a0190
JM
3688
3689 with alloc_fail(hapd, 1, "base64_encode;wps_build_cred"):
3690 pin = dev[0].wps_read_pin()
3691 hapd.request("WPS_PIN any " + pin)
3692 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3693 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3694 dev[0].wait_disconnected()
3695
3696 hapd.request("WPS_PIN any " + pin)
3697 dev[0].wait_connected(timeout=30)
ccf4d764
JM
3698
3699def test_ap_wps_er_oom(dev, apdev):
3700 """WPS ER OOM in XML processing"""
3701 try:
3702 _test_ap_wps_er_oom(dev, apdev)
3703 finally:
3704 dev[0].request("WPS_ER_STOP")
3705 dev[1].request("WPS_CANCEL")
3706 dev[0].request("DISCONNECT")
3707
3708def _test_ap_wps_er_oom(dev, apdev):
3709 ssid = "wps-er-ap-config"
3710 ap_pin = "12345670"
3711 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 3712 hostapd.add_ap(apdev[0],
ccf4d764
JM
3713 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3714 "wpa_passphrase": "12345678", "wpa": "2",
3715 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3716 "device_name": "Wireless AP", "manufacturer": "Company",
3717 "model_name": "WAP", "model_number": "123",
3718 "serial_number": "12345", "device_type": "6-0050F204-1",
3719 "os_version": "01020300",
3720 "config_methods": "label push_button",
3721 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
3722
3723 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
3724
3725 with alloc_fail(dev[0], 1, "base64_decode;xml_get_base64_item"):
3726 dev[0].request("WPS_ER_START ifname=lo")
3727 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=3)
3728 if ev is not None:
3729 raise Exception("Unexpected AP discovery")
3730
3731 dev[0].request("WPS_ER_STOP")
3732 dev[0].request("WPS_ER_START ifname=lo")
3733 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
3734 if ev is None:
3735 raise Exception("AP discovery timed out")
3736
3737 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3738 with alloc_fail(dev[0], 1, "base64_decode;xml_get_base64_item"):
3739 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
3740 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
3741 if ev is None:
3742 raise Exception("PBC scan failed")
3743 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
3744 if ev is None:
3745 raise Exception("Enrollee discovery timed out")
2602a2ff 3746
c965ae03
JM
3747def test_ap_wps_er_init_oom(dev, apdev):
3748 """WPS ER and OOM during init"""
3749 try:
3750 _test_ap_wps_er_init_oom(dev, apdev)
3751 finally:
3752 dev[0].request("WPS_ER_STOP")
3753
3754def _test_ap_wps_er_init_oom(dev, apdev):
3755 with alloc_fail(dev[0], 1, "wps_er_init"):
3756 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3757 raise Exception("WPS_ER_START succeeded during OOM")
3758 with alloc_fail(dev[0], 1, "http_server_init"):
3759 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3760 raise Exception("WPS_ER_START succeeded during OOM")
3761 with alloc_fail(dev[0], 2, "http_server_init"):
3762 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3763 raise Exception("WPS_ER_START succeeded during OOM")
9b35afd6 3764 with alloc_fail(dev[0], 1, "eloop_sock_table_add_sock;?eloop_register_sock;wps_er_ssdp_init"):
c965ae03
JM
3765 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3766 raise Exception("WPS_ER_START succeeded during OOM")
3767 with fail_test(dev[0], 1, "os_get_random;wps_er_init"):
3768 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3769 raise Exception("WPS_ER_START succeeded during os_get_random failure")
3770
07536b18
JM
3771def test_ap_wps_er_init_fail(dev, apdev):
3772 """WPS ER init failure"""
3773 if "FAIL" not in dev[0].request("WPS_ER_START ifname=does-not-exist"):
3774 dev[0].request("WPS_ER_STOP")
3775 raise Exception("WPS_ER_START with non-existing ifname succeeded")
3776
2602a2ff
JM
3777def test_ap_wps_wpa_cli_action(dev, apdev, test_params):
3778 """WPS events and wpa_cli action script"""
8936b095
JM
3779 logdir = os.path.abspath(test_params['logdir'])
3780 pidfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.pid')
3781 logfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.res')
3782 actionfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.action.sh')
2602a2ff
JM
3783
3784 with open(actionfile, 'w') as f:
3785 f.write('#!/bin/sh\n')
3786 f.write('echo $* >> %s\n' % logfile)
3787 # Kill the process and wait some time before returning to allow all the
3788 # pending events to be processed with some of this happening after the
3789 # eloop SIGALRM signal has been scheduled.
3790 f.write('if [ $2 = "WPS-SUCCESS" -a -r %s ]; then kill `cat %s`; sleep 1; fi\n' % (pidfile, pidfile))
3791
8936b095
JM
3792 os.chmod(actionfile, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC |
3793 stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
2602a2ff
JM
3794
3795 ssid = "test-wps-conf"
6f334bf7
JD
3796 hapd = hostapd.add_ap(apdev[0],
3797 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3798 "wpa_passphrase": "12345678", "wpa": "2",
3799 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2602a2ff
JM
3800
3801 prg = os.path.join(test_params['logdir'],
3802 'alt-wpa_supplicant/wpa_supplicant/wpa_cli')
3803 if not os.path.exists(prg):
3804 prg = '../../wpa_supplicant/wpa_cli'
3805 arg = [ prg, '-P', pidfile, '-B', '-i', dev[0].ifname, '-a', actionfile ]
3806 subprocess.call(arg)
3807
3808 arg = [ 'ps', 'ax' ]
3809 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3810 out = cmd.communicate()[0]
3811 cmd.wait()
3812 logger.debug("Processes:\n" + out)
3813 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) not in out:
3814 raise Exception("Did not see wpa_cli running")
3815
3816 hapd.request("WPS_PIN any 12345670")
3817 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3818 dev[0].dump_monitor()
3819 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3820 dev[0].wait_connected(timeout=30)
3821
3822 for i in range(30):
3823 if not os.path.exists(pidfile):
3824 break
3825 time.sleep(0.1)
3826
3827 if not os.path.exists(logfile):
3828 raise Exception("wpa_cli action results file not found")
3829 with open(logfile, 'r') as f:
3830 res = f.read()
3831 if "WPS-SUCCESS" not in res:
3832 raise Exception("WPS-SUCCESS event not seen in action file")
3833
3834 arg = [ 'ps', 'ax' ]
3835 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3836 out = cmd.communicate()[0]
3837 cmd.wait()
3838 logger.debug("Remaining processes:\n" + out)
3839 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) in out:
3840 raise Exception("wpa_cli still running")
3841
3842 if os.path.exists(pidfile):
3843 raise Exception("PID file not removed")
c965ae03
JM
3844
3845def test_ap_wps_er_ssdp_proto(dev, apdev):
3846 """WPS ER SSDP protocol testing"""
3847 try:
3848 _test_ap_wps_er_ssdp_proto(dev, apdev)
3849 finally:
3850 dev[0].request("WPS_ER_STOP")
3851
3852def _test_ap_wps_er_ssdp_proto(dev, apdev):
3853 socket.setdefaulttimeout(1)
3854 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
3855 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
3856 sock.bind(("239.255.255.250", 1900))
3857 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo foo"):
3858 raise Exception("Invalid filter accepted")
3859 if "OK" not in dev[0].request("WPS_ER_START ifname=lo 1.2.3.4"):
3860 raise Exception("WPS_ER_START with filter failed")
3861 (msg,addr) = sock.recvfrom(1000)
3862 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3863 if "M-SEARCH" not in msg:
3864 raise Exception("Not an M-SEARCH")
3865 sock.sendto("FOO", addr)
3866 time.sleep(0.1)
3867 dev[0].request("WPS_ER_STOP")
3868
3869 dev[0].request("WPS_ER_START ifname=lo")
3870 (msg,addr) = sock.recvfrom(1000)
3871 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3872 if "M-SEARCH" not in msg:
3873 raise Exception("Not an M-SEARCH")
3874 sock.sendto("FOO", addr)
3875 sock.sendto("HTTP/1.1 200 OK\r\nFOO\r\n\r\n", addr)
3876 sock.sendto("HTTP/1.1 200 OK\r\nNTS:foo\r\n\r\n", addr)
3877 sock.sendto("HTTP/1.1 200 OK\r\nNTS:ssdp:byebye\r\n\r\n", addr)
3878 sock.sendto("HTTP/1.1 200 OK\r\ncache-control: foo=1\r\n\r\n", addr)
3879 sock.sendto("HTTP/1.1 200 OK\r\ncache-control: max-age=1\r\n\r\n", addr)
3880 sock.sendto("HTTP/1.1 200 OK\r\nusn:\r\n\r\n", addr)
3881 sock.sendto("HTTP/1.1 200 OK\r\nusn:foo\r\n\r\n", addr)
3882 sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid:\r\n\r\n", addr)
3883 sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid: \r\n\r\n", addr)
3884 sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid: foo\r\n\r\n", addr)
3885 sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\n\r\n", addr)
3886 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)
3887 sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\n\r\n", addr)
3888 with alloc_fail(dev[0], 1, "wps_er_ap_add"):
3889 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)
3890 time.sleep(0.1)
3891 with alloc_fail(dev[0], 2, "wps_er_ap_add"):
3892 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)
3893 time.sleep(0.1)
3894
3895 # Add an AP with bogus URL
3896 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)
3897 # Update timeout on AP without updating URL
3898 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)
3899 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
3900 if ev is None:
3901 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3902
3903 # Add an AP with a valid URL (but no server listing to it)
3904 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)
3905 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
3906 if ev is None:
3907 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3908
3909 sock.close()
3910
3911wps_event_url = None
3912
6aaa661a
JM
3913def gen_upnp_info(eventSubURL='wps_event', controlURL='wps_control',
3914 udn='uuid:27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'):
4c3ae1c0 3915 payload = '''<?xml version="1.0"?>
c965ae03
JM
3916<root xmlns="urn:schemas-upnp-org:device-1-0">
3917<specVersion>
3918<major>1</major>
3919<minor>0</minor>
3920</specVersion>
3921<device>
3922<deviceType>urn:schemas-wifialliance-org:device:WFADevice:1</deviceType>
3923<friendlyName>WPS Access Point</friendlyName>
3924<manufacturer>Company</manufacturer>
3925<modelName>WAP</modelName>
3926<modelNumber>123</modelNumber>
3927<serialNumber>12345</serialNumber>
6aaa661a
JM
3928'''
3929 if udn:
3930 payload += '<UDN>' + udn + '</UDN>'
3931 payload += '''<serviceList>
c965ae03
JM
3932<service>
3933<serviceType>urn:schemas-wifialliance-org:service:WFAWLANConfig:1</serviceType>
3934<serviceId>urn:wifialliance-org:serviceId:WFAWLANConfig1</serviceId>
3935<SCPDURL>wps_scpd.xml</SCPDURL>
4c3ae1c0 3936'''
6aaa661a
JM
3937 if controlURL:
3938 payload += '<controlURL>' + controlURL + '</controlURL>\n'
4c3ae1c0 3939 if eventSubURL:
6aaa661a 3940 payload += '<eventSubURL>' + eventSubURL + '</eventSubURL>\n'
4c3ae1c0 3941 payload += '''</service>
c965ae03
JM
3942</serviceList>
3943</device>
3944</root>
3945'''
4c3ae1c0
JM
3946 hdr = 'HTTP/1.1 200 OK\r\n' + \
3947 'Content-Type: text/xml; charset="utf-8"\r\n' + \
3948 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3949 'Connection: close\r\n' + \
3950 'Content-Length: ' + str(len(payload)) + '\r\n' + \
3951 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3952 return hdr + payload
3953
6aaa661a 3954def gen_wps_control(payload_override=None):
4c3ae1c0 3955 payload = '''<?xml version="1.0"?>
c965ae03
JM
3956<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
3957<s:Body>
3958<u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
3959<NewDeviceInfo>EEoAARAQIgABBBBHABAn6oAanlxOc72C+Jy80Q1+ECAABgIAAAADABAaABCJZ7DPtbU3Ust9
3960Z3wJF07WEDIAwH45D3i1OqB7eJGwTzqeapS71h3KyXncK2xJZ+xqScrlorNEg6LijBJzG2Ca
3961+FZli0iliDJd397yAx/jk4nFXco3q5ylBSvSw9dhJ5u1xBKSnTilKGlUHPhLP75PUqM3fot9
39627zwtFZ4bx6x1sBA6oEe2d0aUJmLumQGCiKEIWlnxs44zego/2tAe81bDzdPBM7o5HH/FUhD+
3963KoGzFXp51atP+1n9Vta6AkI0Vye99JKLcC6Md9dMJltSVBgd4Xc4lRAEAAIAIxAQAAIADRAN
3964AAEBEAgAAgAEEEQAAQIQIQAHQ29tcGFueRAjAANXQVAQJAADMTIzEEIABTEyMzQ1EFQACAAG
3965AFDyBAABEBEAC1dpcmVsZXNzIEFQEDwAAQEQAgACAAAQEgACAAAQCQACAAAQLQAEgQIDABBJ
3966AAYANyoAASA=
3967</NewDeviceInfo>
3968</u:GetDeviceInfoResponse>
3969</s:Body>
3970</s:Envelope>
3971'''
6aaa661a
JM
3972 if payload_override:
3973 payload = payload_override
4c3ae1c0
JM
3974 hdr = 'HTTP/1.1 200 OK\r\n' + \
3975 'Content-Type: text/xml; charset="utf-8"\r\n' + \
3976 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3977 'Connection: close\r\n' + \
3978 'Content-Length: ' + str(len(payload)) + '\r\n' + \
3979 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3980 return hdr + payload
3981
6aaa661a 3982def gen_wps_event(sid='uuid:7eb3342a-8a5f-47fe-a585-0785bfec6d8a'):
4c3ae1c0
JM
3983 payload = ""
3984 hdr = 'HTTP/1.1 200 OK\r\n' + \
3985 'Content-Type: text/xml; charset="utf-8"\r\n' + \
3986 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3987 'Connection: close\r\n' + \
6aaa661a
JM
3988 'Content-Length: ' + str(len(payload)) + '\r\n'
3989 if sid:
3990 hdr += 'SID: ' + sid + '\r\n'
3991 hdr += 'Timeout: Second-1801\r\n' + \
4c3ae1c0
JM
3992 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3993 return hdr + payload
3994
3995class WPSAPHTTPServer(SocketServer.StreamRequestHandler):
3996 def handle(self):
3997 data = self.rfile.readline().strip()
3998 logger.info("HTTP server received: " + data)
3999 while True:
4000 hdr = self.rfile.readline().strip()
4001 if len(hdr) == 0:
4002 break
4003 logger.info("HTTP header: " + hdr)
4004 if "CALLBACK:" in hdr:
4005 global wps_event_url
4006 wps_event_url = hdr.split(' ')[1].strip('<>')
4007
4008 if "GET /foo.xml" in data:
6aaa661a
JM
4009 self.handle_upnp_info()
4010 elif "POST /wps_control" in data:
4011 self.handle_wps_control()
4012 elif "SUBSCRIBE /wps_event" in data:
4013 self.handle_wps_event()
24b7f282
JM
4014 else:
4015 self.handle_others(data)
6aaa661a
JM
4016
4017 def handle_upnp_info(self):
4018 self.wfile.write(gen_upnp_info())
4c3ae1c0 4019
6aaa661a
JM
4020 def handle_wps_control(self):
4021 self.wfile.write(gen_wps_control())
c965ae03 4022
6aaa661a
JM
4023 def handle_wps_event(self):
4024 self.wfile.write(gen_wps_event())
c965ae03 4025
24b7f282
JM
4026 def handle_others(self, data):
4027 logger.info("Ignore HTTP request: " + data)
4028
4c3ae1c0
JM
4029class MyTCPServer(SocketServer.TCPServer):
4030 def __init__(self, addr, handler):
4031 self.allow_reuse_address = True
4032 SocketServer.TCPServer.__init__(self, addr, handler)
c965ae03 4033
24b7f282
JM
4034def wps_er_start(dev, http_server, max_age=1, wait_m_search=False,
4035 location_url=None):
c965ae03
JM
4036 socket.setdefaulttimeout(1)
4037 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4038 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4039 sock.bind(("239.255.255.250", 1900))
4c3ae1c0 4040 dev.request("WPS_ER_START ifname=lo")
24b7f282
JM
4041 for i in range(100):
4042 (msg,addr) = sock.recvfrom(1000)
4043 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4044 if "M-SEARCH" in msg:
4045 break
4046 if not wait_m_search:
4047 raise Exception("Not an M-SEARCH")
4048 if i == 99:
4049 raise Exception("No M-SEARCH seen")
c965ae03
JM
4050
4051 # Add an AP with a valid URL and server listing to it
4c3ae1c0 4052 server = MyTCPServer(("127.0.0.1", 12345), http_server)
24b7f282
JM
4053 if not location_url:
4054 location_url = 'http://127.0.0.1:12345/foo.xml'
4055 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 4056 server.timeout = 1
4c3ae1c0
JM
4057 return server,sock
4058
4059def wps_er_stop(dev, sock, server, on_alloc_fail=False):
4060 sock.close()
4061 server.server_close()
4062
4063 if on_alloc_fail:
4064 done = False
4065 for i in range(50):
4066 res = dev.request("GET_ALLOC_FAIL")
4067 if res.startswith("0:"):
4068 done = True
4069 break
4070 time.sleep(0.1)
4071 if not done:
4072 raise Exception("No allocation failure reported")
4073 else:
4074 ev = dev.wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4075 if ev is None:
4076 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4077 dev.request("WPS_ER_STOP")
4078
24b7f282 4079def run_wps_er_proto_test(dev, handler, no_event_url=False, location_url=None):
6aaa661a
JM
4080 try:
4081 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
24b7f282 4082 server,sock = wps_er_start(dev, handler, location_url=location_url)
6aaa661a
JM
4083 global wps_event_url
4084 wps_event_url = None
4085 server.handle_request()
4086 server.handle_request()
4087 server.handle_request()
4088 server.server_close()
4089 if no_event_url:
4090 if wps_event_url:
4091 raise Exception("Received event URL unexpectedly")
4092 return
4093 if wps_event_url is None:
4094 raise Exception("Did not get event URL")
4095 logger.info("Event URL: " + wps_event_url)
4096 finally:
24b7f282 4097 dev.request("WPS_ER_STOP")
6aaa661a 4098
18478107 4099def send_wlanevent(url, uuid, data, no_response=False):
6aaa661a
JM
4100 conn = httplib.HTTPConnection(url.netloc)
4101 payload = '''<?xml version="1.0" encoding="utf-8"?>
4102<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4103<e:property><STAStatus>1</STAStatus></e:property>
4104<e:property><APStatus>1</APStatus></e:property>
4105<e:property><WLANEvent>'''
4106 payload += base64.b64encode(data)
4107 payload += '</WLANEvent></e:property></e:propertyset>'
4108 headers = { "Content-type": 'text/xml; charset="utf-8"',
4109 "Server": "Unspecified, UPnP/1.0, Unspecified",
4110 "HOST": url.netloc,
4111 "NT": "upnp:event",
4112 "SID": "uuid:" + uuid,
4113 "SEQ": "0",
4114 "Content-Length": str(len(payload)) }
4115 conn.request("NOTIFY", url.path, payload, headers)
18478107
JM
4116 if no_response:
4117 try:
4118 conn.getresponse()
4119 except Exception, e:
4120 pass
4121 return
6aaa661a
JM
4122 resp = conn.getresponse()
4123 if resp.status != 200:
4124 raise Exception("Unexpected HTTP response: %d" % resp.status)
4125
4c3ae1c0
JM
4126def test_ap_wps_er_http_proto(dev, apdev):
4127 """WPS ER HTTP protocol testing"""
4128 try:
4129 _test_ap_wps_er_http_proto(dev, apdev)
4130 finally:
4131 dev[0].request("WPS_ER_STOP")
4132
4133def _test_ap_wps_er_http_proto(dev, apdev):
4134 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
6aaa661a 4135 server,sock = wps_er_start(dev[0], WPSAPHTTPServer, max_age=15)
c965ae03
JM
4136 global wps_event_url
4137 wps_event_url = None
4138 server.handle_request()
4139 server.handle_request()
4140 server.handle_request()
4141 server.server_close()
4142 if wps_event_url is None:
4143 raise Exception("Did not get event URL")
4144 logger.info("Event URL: " + wps_event_url)
4145
4146 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
4147 if ev is None:
4148 raise Exception("No WPS-ER-AP-ADD event")
4149 if uuid not in ev:
4150 raise Exception("UUID mismatch")
4151
4152 sock.close()
4153
4154 logger.info("Valid Probe Request notification")
4155 url = urlparse.urlparse(wps_event_url)
4156 conn = httplib.HTTPConnection(url.netloc)
4157 payload = '''<?xml version="1.0" encoding="utf-8"?>
4158<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4159<e:property><STAStatus>1</STAStatus></e:property>
4160<e:property><APStatus>1</APStatus></e:property>
4161<e:property><WLANEvent>ATAyOjAwOjAwOjAwOjAwOjAwEEoAARAQOgABAhAIAAIxSBBHABA2LbR7pTpRkYj7VFi5hrLk
4162EFQACAAAAAAAAAAAEDwAAQMQAgACAAAQCQACAAAQEgACAAAQIQABIBAjAAEgECQAASAQEQAI
4163RGV2aWNlIEEQSQAGADcqAAEg
4164</WLANEvent></e:property>
4165</e:propertyset>
4166'''
4167 headers = { "Content-type": 'text/xml; charset="utf-8"',
4168 "Server": "Unspecified, UPnP/1.0, Unspecified",
4169 "HOST": url.netloc,
4170 "NT": "upnp:event",
4171 "SID": "uuid:" + uuid,
4172 "SEQ": "0",
4173 "Content-Length": str(len(payload)) }
4174 conn.request("NOTIFY", url.path, payload, headers)
4175 resp = conn.getresponse()
4176 if resp.status != 200:
4177 raise Exception("Unexpected HTTP response: %d" % resp.status)
4178
4179 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=5)
4180 if ev is None:
4181 raise Exception("No WPS-ER-ENROLLEE-ADD event")
4182 if "362db47b-a53a-5191-88fb-5458b986b2e4" not in ev:
4183 raise Exception("No Enrollee UUID match")
4184
4185 logger.info("Incorrect event URL AP id")
4186 conn = httplib.HTTPConnection(url.netloc)
4187 conn.request("NOTIFY", url.path + '123', payload, headers)
4188 resp = conn.getresponse()
4189 if resp.status != 404:
4190 raise Exception("Unexpected HTTP response: %d" % resp.status)
4191
4192 logger.info("Missing AP id")
4193 conn = httplib.HTTPConnection(url.netloc)
4194 conn.request("NOTIFY", '/event/' + url.path.split('/')[2],
4195 payload, headers)
4196 time.sleep(0.1)
4197
4198 logger.info("Incorrect event URL event id")
4199 conn = httplib.HTTPConnection(url.netloc)
4200 conn.request("NOTIFY", '/event/123456789/123', payload, headers)
4201 time.sleep(0.1)
4202
4203 logger.info("Incorrect event URL prefix")
4204 conn = httplib.HTTPConnection(url.netloc)
4205 conn.request("NOTIFY", '/foobar/123456789/123', payload, headers)
4206 resp = conn.getresponse()
4207 if resp.status != 404:
4208 raise Exception("Unexpected HTTP response: %d" % resp.status)
4209
4210 logger.info("Unsupported request")
4211 conn = httplib.HTTPConnection(url.netloc)
4212 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4213 resp = conn.getresponse()
4214 if resp.status != 501:
4215 raise Exception("Unexpected HTTP response: %d" % resp.status)
4216
4217 logger.info("Unsupported request and OOM")
4218 with alloc_fail(dev[0], 1, "wps_er_http_req"):
4219 conn = httplib.HTTPConnection(url.netloc)
4220 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4221 time.sleep(0.5)
4c3ae1c0 4222
6aaa661a
JM
4223 logger.info("Too short WLANEvent")
4224 data = '\x00'
4225 send_wlanevent(url, uuid, data)
4226
4227 logger.info("Invalid WLANEventMAC")
4228 data = '\x00qwertyuiopasdfghjklzxcvbnm'
4229 send_wlanevent(url, uuid, data)
4230
4231 logger.info("Unknown WLANEventType")
4232 data = '\xff02:00:00:00:00:00'
4233 send_wlanevent(url, uuid, data)
4234
4235 logger.info("Probe Request notification without any attributes")
4236 data = '\x0102:00:00:00:00:00'
4237 send_wlanevent(url, uuid, data)
4238
4239 logger.info("Probe Request notification with invalid attribute")
4240 data = '\x0102:00:00:00:00:00\xff'
4241 send_wlanevent(url, uuid, data)
4242
4243 logger.info("EAP message without any attributes")
4244 data = '\x0202:00:00:00:00:00'
4245 send_wlanevent(url, uuid, data)
4246
4247 logger.info("EAP message with invalid attribute")
4248 data = '\x0202:00:00:00:00:00\xff'
4249 send_wlanevent(url, uuid, data)
4250
4251 logger.info("EAP message from new STA and not M1")
4252 data = '\x0202:ff:ff:ff:ff:ff' + '\x10\x22\x00\x01\x05'
4253 send_wlanevent(url, uuid, data)
4254
4255 logger.info("EAP message: M1")
4256 data = '\x0202:00:00:00:00:00'
4257 data += '\x10\x22\x00\x01\x04'
4258 data += '\x10\x47\x00\x10' + 16*'\x00'
4259 data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4260 data += '\x10\x1a\x00\x10' + 16*'\x00'
4261 data += '\x10\x32\x00\xc0' + 192*'\x00'
4262 data += '\x10\x04\x00\x02\x00\x00'
4263 data += '\x10\x10\x00\x02\x00\x00'
4264 data += '\x10\x0d\x00\x01\x00'
4265 data += '\x10\x08\x00\x02\x00\x00'
4266 data += '\x10\x44\x00\x01\x00'
4267 data += '\x10\x21\x00\x00'
4268 data += '\x10\x23\x00\x00'
4269 data += '\x10\x24\x00\x00'
4270 data += '\x10\x42\x00\x00'
4271 data += '\x10\x54\x00\x08' + 8*'\x00'
4272 data += '\x10\x11\x00\x00'
4273 data += '\x10\x3c\x00\x01\x00'
4274 data += '\x10\x02\x00\x02\x00\x00'
4275 data += '\x10\x12\x00\x02\x00\x00'
4276 data += '\x10\x09\x00\x02\x00\x00'
4277 data += '\x10\x2d\x00\x04\x00\x00\x00\x00'
4278 m1 = data
4279 send_wlanevent(url, uuid, data)
4280
4281 logger.info("EAP message: WSC_ACK")
4282 data = '\x0202:00:00:00:00:00' + '\x10\x22\x00\x01\x0d'
4283 send_wlanevent(url, uuid, data)
4284
4285 logger.info("EAP message: M1")
4286 send_wlanevent(url, uuid, m1)
4287
4288 logger.info("EAP message: WSC_NACK")
4289 data = '\x0202:00:00:00:00:00' + '\x10\x22\x00\x01\x0e'
4290 send_wlanevent(url, uuid, data)
4291
4292 logger.info("EAP message: M1 - Too long attribute values")
4293 data = '\x0202:00:00:00:00:00'
4294 data += '\x10\x11\x00\x21' + 33*'\x00'
4295 data += '\x10\x45\x00\x21' + 33*'\x00'
4296 data += '\x10\x42\x00\x21' + 33*'\x00'
4297 data += '\x10\x24\x00\x21' + 33*'\x00'
4298 data += '\x10\x23\x00\x21' + 33*'\x00'
4299 data += '\x10\x21\x00\x41' + 65*'\x00'
4300 data += '\x10\x49\x00\x09\x00\x37\x2a\x05\x02\x00\x00\x05\x00'
4301 send_wlanevent(url, uuid, data)
4302
4303 logger.info("EAP message: M1 missing UUID-E")
4304 data = '\x0202:00:00:00:00:00'
4305 data += '\x10\x22\x00\x01\x04'
4306 send_wlanevent(url, uuid, data)
4307
4308 logger.info("EAP message: M1 missing MAC Address")
4309 data += '\x10\x47\x00\x10' + 16*'\x00'
4310 send_wlanevent(url, uuid, data)
4311
4312 logger.info("EAP message: M1 missing Enrollee Nonce")
4313 data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4314 send_wlanevent(url, uuid, data)
4315
4316 logger.info("EAP message: M1 missing Public Key")
4317 data += '\x10\x1a\x00\x10' + 16*'\x00'
4318 send_wlanevent(url, uuid, data)
4319
4320 logger.info("EAP message: M1 missing Authentication Type flags")
4321 data += '\x10\x32\x00\xc0' + 192*'\x00'
4322 send_wlanevent(url, uuid, data)
4323
4324 logger.info("EAP message: M1 missing Encryption Type Flags")
4325 data += '\x10\x04\x00\x02\x00\x00'
4326 send_wlanevent(url, uuid, data)
4327
4328 logger.info("EAP message: M1 missing Connection Type flags")
4329 data += '\x10\x10\x00\x02\x00\x00'
4330 send_wlanevent(url, uuid, data)
4331
4332 logger.info("EAP message: M1 missing Config Methods")
4333 data += '\x10\x0d\x00\x01\x00'
4334 send_wlanevent(url, uuid, data)
4335
4336 logger.info("EAP message: M1 missing Wi-Fi Protected Setup State")
4337 data += '\x10\x08\x00\x02\x00\x00'
4338 send_wlanevent(url, uuid, data)
4339
4340 logger.info("EAP message: M1 missing Manufacturer")
4341 data += '\x10\x44\x00\x01\x00'
4342 send_wlanevent(url, uuid, data)
4343
4344 logger.info("EAP message: M1 missing Model Name")
4345 data += '\x10\x21\x00\x00'
4346 send_wlanevent(url, uuid, data)
4347
4348 logger.info("EAP message: M1 missing Model Number")
4349 data += '\x10\x23\x00\x00'
4350 send_wlanevent(url, uuid, data)
4351
4352 logger.info("EAP message: M1 missing Serial Number")
4353 data += '\x10\x24\x00\x00'
4354 send_wlanevent(url, uuid, data)
4355
4356 logger.info("EAP message: M1 missing Primary Device Type")
4357 data += '\x10\x42\x00\x00'
4358 send_wlanevent(url, uuid, data)
4359
4360 logger.info("EAP message: M1 missing Device Name")
4361 data += '\x10\x54\x00\x08' + 8*'\x00'
4362 send_wlanevent(url, uuid, data)
4363
4364 logger.info("EAP message: M1 missing RF Bands")
4365 data += '\x10\x11\x00\x00'
4366 send_wlanevent(url, uuid, data)
4367
4368 logger.info("EAP message: M1 missing Association State")
4369 data += '\x10\x3c\x00\x01\x00'
4370 send_wlanevent(url, uuid, data)
4371
4372 logger.info("EAP message: M1 missing Device Password ID")
4373 data += '\x10\x02\x00\x02\x00\x00'
4374 send_wlanevent(url, uuid, data)
4375
4376 logger.info("EAP message: M1 missing Configuration Error")
4377 data += '\x10\x12\x00\x02\x00\x00'
4378 send_wlanevent(url, uuid, data)
4379
4380 logger.info("EAP message: M1 missing OS Version")
4381 data += '\x10\x09\x00\x02\x00\x00'
4382 send_wlanevent(url, uuid, data)
4c3ae1c0 4383
24b7f282
JM
4384 logger.info("Check max concurrent requests")
4385 addr = (url.hostname, url.port)
4386 socks = {}
4387 for i in range(20):
4388 socks[i] = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4389 socket.IPPROTO_TCP)
4390 socks[i].connect(addr)
4391 for i in range(20):
4392 socks[i].send("GET / HTTP/1.1\r\n\r\n")
4393 count = 0
4394 for i in range(20):
4395 try:
4396 res = socks[i].recv(100)
4397 if "HTTP/1" in res:
4398 count += 1
4399 except:
4400 pass
4401 socks[i].close()
4402 logger.info("%d concurrent HTTP GET operations returned response" % count)
4403 if count < 10:
4404 raise Exception("Too few concurrent HTTP connections accepted")
4405
4406 logger.info("OOM in HTTP server")
4407 for func in [ "http_request_init", "httpread_create",
4408 "eloop_register_timeout;httpread_create",
9b35afd6 4409 "eloop_sock_table_add_sock;?eloop_register_sock;httpread_create",
24b7f282
JM
4410 "httpread_hdr_analyze" ]:
4411 with alloc_fail(dev[0], 1, func):
4412 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4413 socket.IPPROTO_TCP)
4414 sock.connect(addr)
4415 sock.send("GET / HTTP/1.1\r\n\r\n")
4416 try:
4417 sock.recv(100)
4418 except:
4419 pass
4420 sock.close()
4421
4422 logger.info("Invalid HTTP header")
4423 for req in [ " GET / HTTP/1.1\r\n\r\n",
4424 "HTTP/1.1 200 OK\r\n\r\n",
4425 "HTTP/\r\n\r\n",
4426 "GET %%a%aa% HTTP/1.1\r\n\r\n",
4427 "GET / HTTP/1.1\r\n FOO\r\n\r\n",
4428 "NOTIFY / HTTP/1.1\r\n" + 4097*'a' + '\r\n\r\n',
4429 "NOTIFY / HTTP/1.1\r\n\r\n" + 8193*'a',
4430 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n foo\r\n",
4431 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n1\r\nfoo\r\n",
4432 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\n",
4433 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\naa\ra\r\n\ra" ]:
4434 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4435 socket.IPPROTO_TCP)
4436 sock.settimeout(0.1)
4437 sock.connect(addr)
4438 sock.send(req)
4439 try:
4440 sock.recv(100)
4441 except:
4442 pass
4443 sock.close()
4444
4445 with alloc_fail(dev[0], 2, "httpread_read_handler"):
4446 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4447 socket.IPPROTO_TCP)
4448 sock.connect(addr)
4449 sock.send("NOTIFY / HTTP/1.1\r\n\r\n" + 4500*'a')
4450 try:
4451 sock.recv(100)
4452 except:
4453 pass
4454 sock.close()
4455
4456 conn = httplib.HTTPConnection(url.netloc)
4457 payload = '<foo'
4458 headers = { "Content-type": 'text/xml; charset="utf-8"',
4459 "Server": "Unspecified, UPnP/1.0, Unspecified",
4460 "HOST": url.netloc,
4461 "NT": "upnp:event",
4462 "SID": "uuid:" + uuid,
4463 "SEQ": "0",
4464 "Content-Length": str(len(payload)) }
4465 conn.request("NOTIFY", url.path, payload, headers)
4466 resp = conn.getresponse()
4467 if resp.status != 200:
4468 raise Exception("Unexpected HTTP response: %d" % resp.status)
4469
4470 conn = httplib.HTTPConnection(url.netloc)
4471 payload = '<WLANEvent foo></WLANEvent>'
4472 headers = { "Content-type": 'text/xml; charset="utf-8"',
4473 "Server": "Unspecified, UPnP/1.0, Unspecified",
4474 "HOST": url.netloc,
4475 "NT": "upnp:event",
4476 "SID": "uuid:" + uuid,
4477 "SEQ": "0",
4478 "Content-Length": str(len(payload)) }
4479 conn.request("NOTIFY", url.path, payload, headers)
4480 resp = conn.getresponse()
4481 if resp.status != 200:
4482 raise Exception("Unexpected HTTP response: %d" % resp.status)
4483
4484 with alloc_fail(dev[0], 1, "xml_get_first_item"):
4485 send_wlanevent(url, uuid, '')
4486
4487 with alloc_fail(dev[0], 1, "wpabuf_alloc_ext_data;xml_get_base64_item"):
4488 send_wlanevent(url, uuid, 'foo')
4489
4490 for func in [ "wps_init",
4491 "wps_process_manufacturer",
4492 "wps_process_model_name",
4493 "wps_process_model_number",
4494 "wps_process_serial_number",
4495 "wps_process_dev_name" ]:
4496 with alloc_fail(dev[0], 1, func):
4497 send_wlanevent(url, uuid, m1)
4498
18478107
JM
4499 with alloc_fail(dev[0], 1, "wps_er_http_resp_ok"):
4500 send_wlanevent(url, uuid, m1, no_response=True)
4501
4502 with alloc_fail(dev[0], 1, "wps_er_http_resp_not_found"):
4503 url2 = urlparse.urlparse(wps_event_url.replace('/event/', '/notfound/'))
4504 send_wlanevent(url2, uuid, m1, no_response=True)
4505
3d105cdf
JM
4506 logger.info("EAP message: M1")
4507 data = '\x0202:11:22:00:00:00'
4508 data += '\x10\x22\x00\x01\x04'
4509 data += '\x10\x47\x00\x10' + 16*'\x00'
4510 data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4511 data += '\x10\x1a\x00\x10' + 16*'\x00'
4512 data += '\x10\x32\x00\xc0' + 192*'\x00'
4513 data += '\x10\x04\x00\x02\x00\x00'
4514 data += '\x10\x10\x00\x02\x00\x00'
4515 data += '\x10\x0d\x00\x01\x00'
4516 data += '\x10\x08\x00\x02\x00\x00'
4517 data += '\x10\x44\x00\x01\x00'
4518 data += '\x10\x21\x00\x00'
4519 data += '\x10\x23\x00\x00'
4520 data += '\x10\x24\x00\x00'
4521 data += '\x10\x42\x00\x00'
4522 data += '\x10\x54\x00\x08' + 8*'\x00'
4523 data += '\x10\x11\x00\x00'
4524 data += '\x10\x3c\x00\x01\x00'
4525 data += '\x10\x02\x00\x02\x00\x00'
4526 data += '\x10\x12\x00\x02\x00\x00'
4527 data += '\x10\x09\x00\x02\x00\x00'
4528 data += '\x10\x2d\x00\x04\x00\x00\x00\x00'
4529 dev[0].dump_monitor()
4530 with alloc_fail(dev[0], 1, "wps_er_add_sta_data"):
4531 send_wlanevent(url, uuid, data)
4532 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=0.1)
4533 if ev is not None:
4534 raise Exception("Unexpected enrollee add event")
4535 send_wlanevent(url, uuid, data)
4536 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=2)
4537 if ev is None:
4538 raise Exception("Enrollee add event not seen")
4539
fe67b945
JM
4540 with alloc_fail(dev[0], 1, "base64_encode;wps_er_soap_hdr"):
4541 send_wlanevent(url, uuid, data)
4542
4543 with alloc_fail(dev[0], 1, "wpabuf_alloc;wps_er_soap_hdr"):
4544 send_wlanevent(url, uuid, data)
4545
4546 with alloc_fail(dev[0], 1, "http_client_url_parse;wps_er_sta_send_msg"):
4547 send_wlanevent(url, uuid, data)
4548
4549 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_sta_send_msg"):
4550 send_wlanevent(url, uuid, data)
4551
4c3ae1c0
JM
4552def test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
4553 """WPS ER HTTP protocol testing - no eventSubURL"""
6aaa661a
JM
4554 class WPSAPHTTPServer_no_event_sub_url(WPSAPHTTPServer):
4555 def handle_upnp_info(self):
4556 self.wfile.write(gen_upnp_info(eventSubURL=None))
4557 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_event_sub_url,
4558 no_event_url=True)
4c3ae1c0
JM
4559
4560def test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev):
4561 """WPS ER HTTP protocol testing - DNS name in eventSubURL"""
6aaa661a
JM
4562 class WPSAPHTTPServer_event_sub_url_dns(WPSAPHTTPServer):
4563 def handle_upnp_info(self):
4564 self.wfile.write(gen_upnp_info(eventSubURL='http://example.com/wps_event'))
4565 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_event_sub_url_dns,
4566 no_event_url=True)
4c3ae1c0
JM
4567
4568def test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4569 """WPS ER HTTP protocol testing - subscribe OOM"""
4570 try:
4571 _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev)
4572 finally:
4573 dev[0].request("WPS_ER_STOP")
4574
4575def _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4576 tests = [ (1, "http_client_url_parse"),
4577 (1, "wpabuf_alloc;wps_er_subscribe"),
4578 (1, "http_client_addr"),
9b35afd6 4579 (1, "eloop_sock_table_add_sock;?eloop_register_sock;http_client_addr"),
4c3ae1c0
JM
4580 (1, "eloop_register_timeout;http_client_addr") ]
4581 for count,func in tests:
4582 with alloc_fail(dev[0], count, func):
4583 server,sock = wps_er_start(dev[0], WPSAPHTTPServer)
4584 server.handle_request()
4585 server.handle_request()
4586 wps_er_stop(dev[0], sock, server, on_alloc_fail=True)
6aaa661a
JM
4587
4588def test_ap_wps_er_http_proto_no_sid(dev, apdev):
4589 """WPS ER HTTP protocol testing - no SID"""
4590 class WPSAPHTTPServer_no_sid(WPSAPHTTPServer):
4591 def handle_wps_event(self):
4592 self.wfile.write(gen_wps_event(sid=None))
4593 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_sid)
4594
4595def test_ap_wps_er_http_proto_invalid_sid_no_uuid(dev, apdev):
4596 """WPS ER HTTP protocol testing - invalid SID - no UUID"""
4597 class WPSAPHTTPServer_invalid_sid_no_uuid(WPSAPHTTPServer):
4598 def handle_wps_event(self):
4599 self.wfile.write(gen_wps_event(sid='FOO'))
4600 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_no_uuid)
4601
4602def test_ap_wps_er_http_proto_invalid_sid_uuid(dev, apdev):
4603 """WPS ER HTTP protocol testing - invalid SID UUID"""
4604 class WPSAPHTTPServer_invalid_sid_uuid(WPSAPHTTPServer):
4605 def handle_wps_event(self):
4606 self.wfile.write(gen_wps_event(sid='uuid:FOO'))
4607 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_uuid)
4608
4609def test_ap_wps_er_http_proto_subscribe_failing(dev, apdev):
4610 """WPS ER HTTP protocol testing - SUBSCRIBE failing"""
4611 class WPSAPHTTPServer_fail_subscribe(WPSAPHTTPServer):
4612 def handle_wps_event(self):
4613 payload = ""
4614 hdr = 'HTTP/1.1 404 Not Found\r\n' + \
4615 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4616 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4617 'Connection: close\r\n' + \
4618 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4619 'Timeout: Second-1801\r\n' + \
4620 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4621 self.wfile.write(hdr + payload)
4622 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_fail_subscribe)
4623
4624def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4625 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4626 class WPSAPHTTPServer_subscribe_invalid_response(WPSAPHTTPServer):
4627 def handle_wps_event(self):
4628 payload = ""
4629 hdr = 'HTTP/1.1 FOO\r\n' + \
4630 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4631 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4632 'Connection: close\r\n' + \
4633 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4634 'Timeout: Second-1801\r\n' + \
4635 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4636 self.wfile.write(hdr + payload)
4637 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_subscribe_invalid_response)
4638
4639def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4640 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4641 class WPSAPHTTPServer_invalid_m1(WPSAPHTTPServer):
4642 def handle_wps_control(self):
4643 payload = '''<?xml version="1.0"?>
4644<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4645<s:Body>
4646<u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4647<NewDeviceInfo>Rk9P</NewDeviceInfo>
4648</u:GetDeviceInfoResponse>
4649</s:Body>
4650</s:Envelope>
4651'''
4652 self.wfile.write(gen_wps_control(payload_override=payload))
4653 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_m1, no_event_url=True)
4654
4655def test_ap_wps_er_http_proto_upnp_info_no_device(dev, apdev):
4656 """WPS ER HTTP protocol testing - No device 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</root>
4666'''
4667 hdr = 'HTTP/1.1 200 OK\r\n' + \
4668 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4669 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4670 'Connection: close\r\n' + \
4671 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4672 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4673 self.wfile.write(hdr + payload)
4674 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4675
4676def test_ap_wps_er_http_proto_upnp_info_no_device_type(dev, apdev):
4677 """WPS ER HTTP protocol testing - No deviceType in UPnP info"""
4678 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4679 def handle_upnp_info(self):
4680 payload = '''<?xml version="1.0"?>
4681<root xmlns="urn:schemas-upnp-org:device-1-0">
4682<specVersion>
4683<major>1</major>
4684<minor>0</minor>
4685</specVersion>
4686<device>
4687</device>
4688</root>
4689'''
4690 hdr = 'HTTP/1.1 200 OK\r\n' + \
4691 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4692 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4693 'Connection: close\r\n' + \
4694 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4695 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4696 self.wfile.write(hdr + payload)
4697 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4698
4699def test_ap_wps_er_http_proto_upnp_info_invalid_udn_uuid(dev, apdev):
4700 """WPS ER HTTP protocol testing - Invalid UDN UUID"""
4701 class WPSAPHTTPServer_invalid_udn_uuid(WPSAPHTTPServer):
4702 def handle_upnp_info(self):
4703 self.wfile.write(gen_upnp_info(udn='uuid:foo'))
4704 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_udn_uuid)
4705
4706def test_ap_wps_er_http_proto_no_control_url(dev, apdev):
4707 """WPS ER HTTP protocol testing - no controlURL"""
4708 class WPSAPHTTPServer_no_control_url(WPSAPHTTPServer):
4709 def handle_upnp_info(self):
4710 self.wfile.write(gen_upnp_info(controlURL=None))
4711 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_control_url,
4712 no_event_url=True)
4713
4714def test_ap_wps_er_http_proto_control_url_dns(dev, apdev):
4715 """WPS ER HTTP protocol testing - DNS name in controlURL"""
4716 class WPSAPHTTPServer_control_url_dns(WPSAPHTTPServer):
4717 def handle_upnp_info(self):
4718 self.wfile.write(gen_upnp_info(controlURL='http://example.com/wps_control'))
4719 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_control_url_dns,
4720 no_event_url=True)
24b7f282
JM
4721
4722def test_ap_wps_http_timeout(dev, apdev):
4723 """WPS AP/ER and HTTP timeout"""
4724 try:
4725 _test_ap_wps_http_timeout(dev, apdev)
4726 finally:
4727 dev[0].request("WPS_ER_STOP")
4728
4729def _test_ap_wps_http_timeout(dev, apdev):
4730 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 4731 add_ssdp_ap(apdev[0], ap_uuid)
24b7f282
JM
4732
4733 location = ssdp_get_location(ap_uuid)
4734 url = urlparse.urlparse(location)
4735 addr = (url.hostname, url.port)
4736 logger.debug("Open HTTP connection to hostapd, but do not complete request")
4737 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4738 socket.IPPROTO_TCP)
4739 sock.connect(addr)
4740 sock.send("G")
4741
4742 class DummyServer(SocketServer.StreamRequestHandler):
4743 def handle(self):
4744 logger.debug("DummyServer - start 31 sec wait")
4745 time.sleep(31)
4746 logger.debug("DummyServer - wait done")
4747
4748 logger.debug("Start WPS ER")
4749 server,sock2 = wps_er_start(dev[0], DummyServer, max_age=40,
4750 wait_m_search=True)
4751
4752 logger.debug("Start server to accept, but not complete, HTTP connection from WPS ER")
4753 # This will wait for 31 seconds..
4754 server.handle_request()
4755
4756 logger.debug("Complete HTTP connection with hostapd (that should have already closed the connection)")
4757 try:
4758 sock.send("ET / HTTP/1.1\r\n\r\n")
4759 res = sock.recv(100)
4760 sock.close()
4761 except:
4762 pass
4763
4764def test_ap_wps_er_url_parse(dev, apdev):
4765 """WPS ER and URL parsing special cases"""
4766 try:
4767 _test_ap_wps_er_url_parse(dev, apdev)
4768 finally:
4769 dev[0].request("WPS_ER_STOP")
4770
4771def _test_ap_wps_er_url_parse(dev, apdev):
4772 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4773 sock.settimeout(1)
4774 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4775 sock.bind(("239.255.255.250", 1900))
4776 dev[0].request("WPS_ER_START ifname=lo")
4777 (msg,addr) = sock.recvfrom(1000)
4778 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4779 if "M-SEARCH" not in msg:
4780 raise Exception("Not an M-SEARCH")
4781 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)
4782 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4783 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)
4784 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4785 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)
4786 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4787
4788 sock.close()
4789
4790def test_ap_wps_er_link_update(dev, apdev):
4791 """WPS ER and link update special cases"""
4792 class WPSAPHTTPServer_link_update(WPSAPHTTPServer):
4793 def handle_upnp_info(self):
4794 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4795 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update)
4796
4797 class WPSAPHTTPServer_link_update2(WPSAPHTTPServer):
4798 def handle_others(self, data):
4799 if "GET / " in data:
4800 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4801 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update2,
4802 location_url='http://127.0.0.1:12345')
4803
4804def test_ap_wps_er_http_client(dev, apdev):
4805 """WPS ER and HTTP client special cases"""
4806 with alloc_fail(dev[0], 1, "http_link_update"):
4807 run_wps_er_proto_test(dev[0], WPSAPHTTPServer)
4808
4809 with alloc_fail(dev[0], 1, "wpabuf_alloc;http_client_url"):
4810 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4811
4812 with alloc_fail(dev[0], 1, "httpread_create;http_client_tx_ready"):
4813 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4814
4815 class WPSAPHTTPServer_req_as_resp(WPSAPHTTPServer):
4816 def handle_upnp_info(self):
4817 self.wfile.write("GET / HTTP/1.1\r\n\r\n")
4818 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_req_as_resp,
4819 no_event_url=True)
4820
4821def test_ap_wps_init_oom(dev, apdev):
4822 """wps_init OOM cases"""
4823 ssid = "test-wps"
4824 appin = "12345670"
4825 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4826 "ap_pin": appin }
8b8a1864 4827 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
4828 pin = dev[0].wps_read_pin()
4829
4830 with alloc_fail(hapd, 1, "wps_init"):
4831 hapd.request("WPS_PIN any " + pin)
4832 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4833 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4834 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4835 if ev is None:
4836 raise Exception("No EAP failure reported")
4837 dev[0].request("WPS_CANCEL")
4838
4839 with alloc_fail(dev[0], 2, "wps_init"):
4840 hapd.request("WPS_PIN any " + pin)
4841 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4842 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4843 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4844 if ev is None:
4845 raise Exception("No EAP failure reported")
4846 dev[0].request("WPS_CANCEL")
4847
4848 with alloc_fail(dev[0], 2, "wps_init"):
4849 hapd.request("WPS_PBC")
4850 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4851 dev[0].request("WPS_PBC %s" % (apdev[0]['bssid']))
4852 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4853 if ev is None:
4854 raise Exception("No EAP failure reported")
4855 dev[0].request("WPS_CANCEL")
4856
4857 dev[0].dump_monitor()
4858 new_ssid = "wps-new-ssid"
4859 new_passphrase = "1234567890"
4860 with alloc_fail(dev[0], 3, "wps_init"):
4861 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
4862 new_passphrase, no_wait=True)
4863 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4864 if ev is None:
4865 raise Exception("No EAP failure reported")
4866
4867 dev[0].flush_scan_cache()
4868
4869def test_ap_wps_invalid_assoc_req_elem(dev, apdev):
4870 """WPS and invalid IE in Association Request frame"""
4871 ssid = "test-wps"
4872 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
8b8a1864 4873 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
4874 pin = "12345670"
4875 hapd.request("WPS_PIN any " + pin)
4876 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4877 try:
4878 dev[0].request("VENDOR_ELEM_ADD 13 dd050050f20410")
4879 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4880 for i in range(5):
4881 ev = hapd.wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=10)
4882 if ev and "vendor=14122" in ev:
4883 break
4884 if ev is None or "vendor=14122" not in ev:
4885 raise Exception("EAP-WSC not started")
4886 dev[0].request("WPS_CANCEL")
4887 finally:
4888 dev[0].request("VENDOR_ELEM_REMOVE 13 *")
4889
4890def test_ap_wps_pbc_pin_mismatch(dev, apdev):
4891 """WPS PBC/PIN mismatch"""
4892 ssid = "test-wps"
4893 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
8b8a1864 4894 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
4895 hapd.request("SET wps_version_number 0x10")
4896 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4897 hapd.request("WPS_PBC")
4898 pin = dev[0].wps_read_pin()
4899 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4900 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4901 if ev is None:
4902 raise Exception("Scan did not complete")
4903 dev[0].request("WPS_CANCEL")
4904
4905 hapd.request("WPS_CANCEL")
4906 dev[0].flush_scan_cache()
4907
4908def test_ap_wps_ie_invalid(dev, apdev):
4909 """WPS PIN attempt with AP that has invalid WSC IE"""
4910 ssid = "test-wps"
4911 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4912 "vendor_elements": "dd050050f20410" }
8b8a1864 4913 hapd = hostapd.add_ap(apdev[0], params)
24b7f282 4914 params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
8b8a1864 4915 hostapd.add_ap(apdev[1], params)
24b7f282
JM
4916 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4917 pin = dev[0].wps_read_pin()
4918 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4919 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4920 if ev is None:
4921 raise Exception("Scan did not complete")
4922 dev[0].request("WPS_CANCEL")
4923
4924def test_ap_wps_scan_prio_order(dev, apdev):
4925 """WPS scan priority ordering"""
4926 ssid = "test-wps"
4927 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
8b8a1864 4928 hapd = hostapd.add_ap(apdev[0], params)
24b7f282 4929 params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
8b8a1864 4930 hostapd.add_ap(apdev[1], params)
24b7f282
JM
4931 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4932 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
4933 pin = dev[0].wps_read_pin()
4934 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4935 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4936 if ev is None:
4937 raise Exception("Scan did not complete")
4938 dev[0].request("WPS_CANCEL")
4939
4940def test_ap_wps_probe_req_ie_oom(dev, apdev):
4941 """WPS ProbeReq IE OOM"""
4942 ssid = "test-wps"
4943 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
8b8a1864 4944 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
4945 pin = dev[0].wps_read_pin()
4946 hapd.request("WPS_PIN any " + pin)
4947 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4948 with alloc_fail(dev[0], 1, "wps_build_probe_req_ie"):
4949 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4950 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4951 if ev is None:
4952 raise Exception("Association not seen")
4953 dev[0].request("WPS_CANCEL")
161c8515 4954 dev[0].wait_disconnected()
24b7f282
JM
4955
4956 with alloc_fail(dev[0], 1, "wps_ie_encapsulate"):
4957 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4958 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4959 if ev is None:
4960 raise Exception("Association not seen")
4961 dev[0].request("WPS_CANCEL")
161c8515
JM
4962 hapd.disable()
4963 dev[0].request("REMOVE_NETWORK all")
4964 dev[0].wait_disconnected()
4965 time.sleep(0.2)
4966 dev[0].flush_scan_cache()
24b7f282
JM
4967
4968def test_ap_wps_assoc_req_ie_oom(dev, apdev):
4969 """WPS AssocReq IE OOM"""
4970 ssid = "test-wps"
4971 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
8b8a1864 4972 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
4973 pin = dev[0].wps_read_pin()
4974 hapd.request("WPS_PIN any " + pin)
4975 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4976 with alloc_fail(dev[0], 1, "wps_build_assoc_req_ie"):
4977 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4978 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4979 if ev is None:
4980 raise Exception("Association not seen")
4981 dev[0].request("WPS_CANCEL")
4982
4983def test_ap_wps_assoc_resp_ie_oom(dev, apdev):
4984 """WPS AssocResp IE OOM"""
4985 ssid = "test-wps"
4986 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
8b8a1864 4987 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
4988 pin = dev[0].wps_read_pin()
4989 hapd.request("WPS_PIN any " + pin)
4990 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4991 with alloc_fail(hapd, 1, "wps_build_assoc_resp_ie"):
4992 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4993 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4994 if ev is None:
4995 raise Exception("Association not seen")
4996 dev[0].request("WPS_CANCEL")
4997
4998def test_ap_wps_bss_info_errors(dev, apdev):
4999 """WPS BSS info errors"""
5000 params = { "ssid": "1",
5001 "vendor_elements": "dd0e0050f20410440001ff101100010a" }
8b8a1864 5002 hostapd.add_ap(apdev[0], params)
24b7f282 5003 params = { 'ssid': "2", "vendor_elements": "dd050050f20410" }
8b8a1864 5004 hostapd.add_ap(apdev[1], params)
24b7f282
JM
5005 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5006 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
5007 bss = dev[0].get_bss(apdev[0]['bssid'])
5008 logger.info("BSS: " + str(bss))
5009 if "wps_state" in bss:
5010 raise Exception("Unexpected wps_state in BSS info")
5011 if 'wps_device_name' not in bss:
5012 raise Exception("No wps_device_name in BSS info")
5013 if bss['wps_device_name'] != '_':
5014 raise Exception("Unexpected wps_device_name value")
5015 bss = dev[0].get_bss(apdev[1]['bssid'])
5016 logger.info("BSS: " + str(bss))
5017
5018 with alloc_fail(dev[0], 1, "=wps_attr_text"):
5019 bss = dev[0].get_bss(apdev[0]['bssid'])
5020 logger.info("BSS(OOM): " + str(bss))
5021
5022def wps_run_pbc_fail_ap(apdev, dev, hapd):
5023 hapd.request("WPS_PBC")
5024 dev.scan_for_bss(apdev['bssid'], freq="2412")
5025 dev.request("WPS_PBC " + apdev['bssid'])
5026 ev = dev.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5027 if ev is None:
5028 raise Exception("No EAP failure reported")
5029 dev.request("WPS_CANCEL")
5030 dev.wait_disconnected()
5031 for i in range(5):
5032 try:
5033 dev.flush_scan_cache()
5034 break
5035 except Exception, e:
5036 if str(e).startswith("Failed to trigger scan"):
5037 # Try again
5038 time.sleep(1)
5039 else:
5040 raise
5041
5042def wps_run_pbc_fail(apdev, dev):
5043 hapd = wps_start_ap(apdev)
5044 wps_run_pbc_fail_ap(apdev, dev, hapd)
5045
5046def test_ap_wps_pk_oom(dev, apdev):
5047 """WPS and public key OOM"""
5048 with alloc_fail(dev[0], 1, "wps_build_public_key"):
5049 wps_run_pbc_fail(apdev[0], dev[0])
5050
5051def test_ap_wps_pk_oom_ap(dev, apdev):
5052 """WPS and public key OOM on AP"""
5053 hapd = wps_start_ap(apdev[0])
5054 with alloc_fail(hapd, 1, "wps_build_public_key"):
5055 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5056
5057def test_ap_wps_encr_oom_ap(dev, apdev):
5058 """WPS and encrypted settings decryption OOM on AP"""
5059 hapd = wps_start_ap(apdev[0])
5060 pin = dev[0].wps_read_pin()
5061 hapd.request("WPS_PIN any " + pin)
5062 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5063 with alloc_fail(hapd, 1, "wps_decrypt_encr_settings"):
5064 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
5065 ev = hapd.wait_event(["WPS-FAIL"], timeout=10)
5066 if ev is None:
5067 raise Exception("No WPS-FAIL reported")
5068 dev[0].request("WPS_CANCEL")
5069 dev[0].wait_disconnected()
5070
5071def test_ap_wps_encr_no_random_ap(dev, apdev):
5072 """WPS and no random data available for encryption on AP"""
5073 hapd = wps_start_ap(apdev[0])
5074 with fail_test(hapd, 1, "os_get_random;wps_build_encr_settings"):
5075 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5076
5077def test_ap_wps_e_hash_no_random_sta(dev, apdev):
5078 """WPS and no random data available for e-hash on STA"""
5079 with fail_test(dev[0], 1, "os_get_random;wps_build_e_hash"):
5080 wps_run_pbc_fail(apdev[0], dev[0])
5081
5082def test_ap_wps_m1_no_random(dev, apdev):
5083 """WPS and no random for M1 on STA"""
5084 with fail_test(dev[0], 1, "os_get_random;wps_build_m1"):
5085 wps_run_pbc_fail(apdev[0], dev[0])
5086
5087def test_ap_wps_m1_oom(dev, apdev):
5088 """WPS and OOM for M1 on STA"""
5089 with alloc_fail(dev[0], 1, "wps_build_m1"):
5090 wps_run_pbc_fail(apdev[0], dev[0])
5091
5092def test_ap_wps_m3_oom(dev, apdev):
5093 """WPS and OOM for M3 on STA"""
5094 with alloc_fail(dev[0], 1, "wps_build_m3"):
5095 wps_run_pbc_fail(apdev[0], dev[0])
5096
5097def test_ap_wps_m5_oom(dev, apdev):
5098 """WPS and OOM for M5 on STA"""
5099 hapd = wps_start_ap(apdev[0])
5100 hapd.request("WPS_PBC")
5101 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5102 for i in range(1, 3):
5103 with alloc_fail(dev[0], i, "wps_build_m5"):
5104 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5105 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5106 if ev is None:
5107 raise Exception("No EAP failure reported")
5108 dev[0].request("WPS_CANCEL")
5109 dev[0].wait_disconnected()
5110 dev[0].flush_scan_cache()
5111
5112def test_ap_wps_m5_no_random(dev, apdev):
5113 """WPS and no random for M5 on STA"""
5114 with fail_test(dev[0], 1,
5115 "os_get_random;wps_build_encr_settings;wps_build_m5"):
5116 wps_run_pbc_fail(apdev[0], dev[0])
5117
5118def test_ap_wps_m7_oom(dev, apdev):
5119 """WPS and OOM for M7 on STA"""
5120 hapd = wps_start_ap(apdev[0])
5121 hapd.request("WPS_PBC")
5122 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5123 for i in range(1, 3):
5124 with alloc_fail(dev[0], i, "wps_build_m7"):
5125 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5126 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5127 if ev is None:
5128 raise Exception("No EAP failure reported")
5129 dev[0].request("WPS_CANCEL")
5130 dev[0].wait_disconnected()
5131 dev[0].flush_scan_cache()
5132
5133def test_ap_wps_m7_no_random(dev, apdev):
5134 """WPS and no random for M7 on STA"""
5135 with fail_test(dev[0], 1,
5136 "os_get_random;wps_build_encr_settings;wps_build_m7"):
5137 wps_run_pbc_fail(apdev[0], dev[0])
5138
5139def test_ap_wps_wsc_done_oom(dev, apdev):
5140 """WPS and OOM for WSC_Done on STA"""
5141 with alloc_fail(dev[0], 1, "wps_build_wsc_done"):
5142 wps_run_pbc_fail(apdev[0], dev[0])
5143
5144def test_ap_wps_random_psk_fail(dev, apdev):
5145 """WPS and no random for PSK on AP"""
5146 ssid = "test-wps"
5147 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
5148 appin = "12345670"
5149 try:
5150 os.remove(pskfile)
5151 except:
5152 pass
5153
5154 try:
5155 with open(pskfile, "w") as f:
5156 f.write("# WPA PSKs\n")
5157
5158 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5159 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
5160 "rsn_pairwise": "CCMP", "ap_pin": appin,
5161 "wpa_psk_file": pskfile }
8b8a1864 5162 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5163
5164 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5165 with fail_test(hapd, 1, "os_get_random;wps_build_cred_network_key"):
5166 dev[0].request("WPS_REG " + apdev[0]['bssid'] + " " + appin)
5167 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5168 if ev is None:
5169 raise Exception("No EAP failure reported")
5170 dev[0].request("WPS_CANCEL")
5171 dev[0].wait_disconnected()
5172
5173 with fail_test(hapd, 1, "os_get_random;wps_build_cred"):
5174 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5175
5176 with alloc_fail(hapd, 1, "wps_build_cred"):
5177 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5178
5179 with alloc_fail(hapd, 2, "wps_build_cred"):
5180 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5181 finally:
5182 os.remove(pskfile)
5183
5184def wps_ext_eap_identity_req(dev, hapd, bssid):
5185 logger.debug("EAP-Identity/Request")
5186 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5187 if ev is None:
5188 raise Exception("Timeout on EAPOL-TX from hostapd")
5189 res = dev.request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
5190 if "OK" not in res:
5191 raise Exception("EAPOL_RX to wpa_supplicant failed")
5192
5193def wps_ext_eap_identity_resp(hapd, dev, addr):
5194 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
5195 if ev is None:
5196 raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
5197 res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
5198 if "OK" not in res:
5199 raise Exception("EAPOL_RX to hostapd failed")
5200
5201def wps_ext_eap_wsc(dst, src, src_addr, msg):
5202 logger.debug(msg)
5203 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5204 if ev is None:
5205 raise Exception("Timeout on EAPOL-TX")
5206 res = dst.request("EAPOL_RX " + src_addr + " " + ev.split(' ')[2])
5207 if "OK" not in res:
5208 raise Exception("EAPOL_RX failed")
5209
7511ead0 5210def wps_start_ext(apdev, dev, pbc=False, pin=None):
24b7f282
JM
5211 addr = dev.own_addr()
5212 bssid = apdev['bssid']
5213 ssid = "test-wps-conf"
5214 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5215 "wpa_passphrase": "12345678", "wpa": "2",
5216 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
afc26df2 5217 hapd = hostapd.add_ap(apdev, params)
24b7f282 5218
d1883671
JM
5219 if pbc:
5220 hapd.request("WPS_PBC")
5221 else:
7511ead0
JM
5222 if pin is None:
5223 pin = dev.wps_read_pin()
d1883671 5224 hapd.request("WPS_PIN any " + pin)
24b7f282
JM
5225 dev.scan_for_bss(bssid, freq="2412")
5226 hapd.request("SET ext_eapol_frame_io 1")
5227 dev.request("SET ext_eapol_frame_io 1")
5228
d1883671
JM
5229 if pbc:
5230 dev.request("WPS_PBC " + bssid)
5231 else:
5232 dev.request("WPS_PIN " + bssid + " " + pin)
24b7f282
JM
5233 return addr,bssid,hapd
5234
5235def wps_auth_corrupt(dst, src, addr):
5236 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5237 if ev is None:
5238 raise Exception("Timeout on EAPOL-TX")
5239 src.request("SET ext_eapol_frame_io 0")
5240 dst.request("SET ext_eapol_frame_io 0")
5241 msg = ev.split(' ')[2]
5242 if msg[-24:-16] != '10050008':
5243 raise Exception("Could not find Authenticator attribute")
5244 # Corrupt Authenticator value
5245 msg = msg[:-1] + '%x' % ((int(msg[-1], 16) + 1) % 16)
5246 res = dst.request("EAPOL_RX " + addr + " " + msg)
5247 if "OK" not in res:
5248 raise Exception("EAPOL_RX failed")
5249
5250def wps_fail_finish(hapd, dev, fail_str):
5251 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5252 if ev is None:
5253 raise Exception("WPS-FAIL not indicated")
5254 if fail_str not in ev:
5255 raise Exception("Unexpected WPS-FAIL value: " + ev)
5256 dev.request("WPS_CANCEL")
5257 dev.wait_disconnected()
5258
5259def wps_auth_corrupt_from_ap(dev, hapd, bssid, fail_str):
5260 wps_auth_corrupt(dev, hapd, bssid)
5261 wps_fail_finish(hapd, dev, fail_str)
5262
5263def wps_auth_corrupt_to_ap(dev, hapd, addr, fail_str):
5264 wps_auth_corrupt(hapd, dev, addr)
5265 wps_fail_finish(hapd, dev, fail_str)
5266
5267def test_ap_wps_authenticator_mismatch_m2(dev, apdev):
5268 """WPS and Authenticator attribute mismatch in M2"""
5269 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5270 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5271 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5272 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5273 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5274 logger.debug("M2")
5275 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=5")
5276
5277def test_ap_wps_authenticator_mismatch_m3(dev, apdev):
5278 """WPS and Authenticator attribute mismatch in M3"""
5279 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5280 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5281 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5282 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5283 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5284 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5285 logger.debug("M3")
5286 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=7")
5287
5288def test_ap_wps_authenticator_mismatch_m4(dev, apdev):
5289 """WPS and Authenticator attribute mismatch in M4"""
5290 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5291 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5292 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5293 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5294 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5295 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5296 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5297 logger.debug("M4")
5298 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=8")
5299
5300def test_ap_wps_authenticator_mismatch_m5(dev, apdev):
5301 """WPS and Authenticator attribute mismatch in M5"""
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 logger.debug("M5")
5311 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=9")
5312
5313def test_ap_wps_authenticator_mismatch_m6(dev, apdev):
5314 """WPS and Authenticator attribute mismatch in M6"""
5315 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5316 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5317 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5318 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5319 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5320 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5321 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5322 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5323 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5324 logger.debug("M6")
5325 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=10")
5326
5327def test_ap_wps_authenticator_mismatch_m7(dev, apdev):
5328 """WPS and Authenticator attribute mismatch in M7"""
5329 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5330 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5331 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5332 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5333 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5334 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5335 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5336 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5337 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5338 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5339 logger.debug("M7")
5340 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=11")
5341
5342def test_ap_wps_authenticator_mismatch_m8(dev, apdev):
5343 """WPS and Authenticator attribute mismatch in M8"""
5344 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5345 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5346 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5347 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5348 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5349 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5350 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5351 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5352 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5353 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5354 wps_ext_eap_wsc(hapd, dev[0], addr, "M7")
5355 logger.debug("M8")
5356 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=12")
5357
5358def test_ap_wps_authenticator_missing_m2(dev, apdev):
5359 """WPS and Authenticator attribute missing from M2"""
5360 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5361 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5362 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5363 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5364 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5365 logger.debug("M2")
5366 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5367 if ev is None:
5368 raise Exception("Timeout on EAPOL-TX")
5369 hapd.request("SET ext_eapol_frame_io 0")
5370 dev[0].request("SET ext_eapol_frame_io 0")
5371 msg = ev.split(' ')[2]
5372 if msg[-24:-16] != '10050008':
5373 raise Exception("Could not find Authenticator attribute")
5374 # Remove Authenticator value
5375 msg = msg[:-24]
5376 mlen = "%04x" % (int(msg[4:8], 16) - 12)
5377 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:]
5378 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5379 if "OK" not in res:
5380 raise Exception("EAPOL_RX failed")
5381 wps_fail_finish(hapd, dev[0], "msg=5")
5382
d1883671
JM
5383def test_ap_wps_m2_dev_passwd_id_p2p(dev, apdev):
5384 """WPS and M2 with different Device Password ID (P2P)"""
5385 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5386 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5387 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5388 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5389 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5390 logger.debug("M2")
5391 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5392 if ev is None:
5393 raise Exception("Timeout on EAPOL-TX")
5394 hapd.request("SET ext_eapol_frame_io 0")
5395 dev[0].request("SET ext_eapol_frame_io 0")
5396 msg = ev.split(' ')[2]
5397 if msg[722:730] != '10120002':
5398 raise Exception("Could not find Device Password ID attribute")
5399 # Replace Device Password ID value. This will fail Authenticator check, but
5400 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5401 # log.
5402 msg = msg[0:730] + "0005" + msg[734:]
5403 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5404 if "OK" not in res:
5405 raise Exception("EAPOL_RX failed")
5406 wps_fail_finish(hapd, dev[0], "msg=5")
5407
5408def test_ap_wps_m2_dev_passwd_id_change_pin_to_pbc(dev, apdev):
5409 """WPS and M2 with different Device Password ID (PIN to PBC)"""
5410 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5411 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5412 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5413 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5414 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5415 logger.debug("M2")
5416 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5417 if ev is None:
5418 raise Exception("Timeout on EAPOL-TX")
5419 hapd.request("SET ext_eapol_frame_io 0")
5420 dev[0].request("SET ext_eapol_frame_io 0")
5421 msg = ev.split(' ')[2]
5422 if msg[722:730] != '10120002':
5423 raise Exception("Could not find Device Password ID attribute")
5424 # Replace Device Password ID value (PIN --> PBC). This will be rejected.
5425 msg = msg[0:730] + "0004" + msg[734:]
5426 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5427 if "OK" not in res:
5428 raise Exception("EAPOL_RX failed")
5429 wps_fail_finish(hapd, dev[0], "msg=5")
5430
5431def test_ap_wps_m2_dev_passwd_id_change_pbc_to_pin(dev, apdev):
5432 """WPS and M2 with different Device Password ID (PBC to PIN)"""
5433 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5434 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5435 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5436 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5437 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5438 logger.debug("M2")
5439 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5440 if ev is None:
5441 raise Exception("Timeout on EAPOL-TX")
5442 hapd.request("SET ext_eapol_frame_io 0")
5443 dev[0].request("SET ext_eapol_frame_io 0")
5444 msg = ev.split(' ')[2]
5445 if msg[722:730] != '10120002':
5446 raise Exception("Could not find Device Password ID attribute")
5447 # Replace Device Password ID value. This will fail Authenticator check, but
5448 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5449 # log.
5450 msg = msg[0:730] + "0000" + 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 dev[0].flush_scan_cache()
5456
5457def test_ap_wps_m2_missing_dev_passwd_id(dev, apdev):
5458 """WPS and M2 without Device Password ID"""
5459 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5460 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5461 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5462 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5463 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5464 logger.debug("M2")
5465 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5466 if ev is None:
5467 raise Exception("Timeout on EAPOL-TX")
5468 hapd.request("SET ext_eapol_frame_io 0")
5469 dev[0].request("SET ext_eapol_frame_io 0")
5470 msg = ev.split(' ')[2]
5471 if msg[722:730] != '10120002':
5472 raise Exception("Could not find Device Password ID attribute")
5473 # Remove Device Password ID value. This will fail Authenticator check, but
5474 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5475 # log.
5476 mlen = "%04x" % (int(msg[4:8], 16) - 6)
5477 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:722] + msg[734:]
5478 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5479 if "OK" not in res:
5480 raise Exception("EAPOL_RX failed")
5481 wps_fail_finish(hapd, dev[0], "msg=5")
5482
5483def test_ap_wps_m2_missing_registrar_nonce(dev, apdev):
5484 """WPS and M2 without Registrar Nonce"""
5485 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5486 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5487 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5488 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5489 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5490 logger.debug("M2")
5491 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5492 if ev is None:
5493 raise Exception("Timeout on EAPOL-TX")
5494 hapd.request("SET ext_eapol_frame_io 0")
5495 dev[0].request("SET ext_eapol_frame_io 0")
5496 msg = ev.split(' ')[2]
5497 if msg[96:104] != '10390010':
5498 raise Exception("Could not find Registrar Nonce attribute")
5499 # Remove Registrar Nonce. This will fail Authenticator check, but
5500 # allows the code path in wps_process_registrar_nonce() to be checked from
5501 # the debug log.
5502 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5503 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:96] + msg[136:]
5504 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5505 if "OK" not in res:
5506 raise Exception("EAPOL_RX failed")
5507 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5508 if ev is None:
5509 raise Exception("Disconnect event not seen")
5510 dev[0].request("WPS_CANCEL")
5511 dev[0].flush_scan_cache()
5512
5513def test_ap_wps_m2_missing_enrollee_nonce(dev, apdev):
5514 """WPS and M2 without Enrollee Nonce"""
5515 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5516 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5517 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5518 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5519 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5520 logger.debug("M2")
5521 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5522 if ev is None:
5523 raise Exception("Timeout on EAPOL-TX")
5524 hapd.request("SET ext_eapol_frame_io 0")
5525 dev[0].request("SET ext_eapol_frame_io 0")
5526 msg = ev.split(' ')[2]
5527 if msg[56:64] != '101a0010':
5528 raise Exception("Could not find enrollee Nonce attribute")
5529 # Remove Enrollee Nonce. This will fail Authenticator check, but
5530 # allows the code path in wps_process_enrollee_nonce() to be checked from
5531 # the debug log.
5532 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5533 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:56] + msg[96:]
5534 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5535 if "OK" not in res:
5536 raise Exception("EAPOL_RX failed")
5537 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5538 if ev is None:
5539 raise Exception("Disconnect event not seen")
5540 dev[0].request("WPS_CANCEL")
5541 dev[0].flush_scan_cache()
5542
5543def test_ap_wps_m2_missing_uuid_r(dev, apdev):
5544 """WPS and M2 without UUID-R"""
5545 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5546 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5547 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5548 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5549 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5550 logger.debug("M2")
5551 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5552 if ev is None:
5553 raise Exception("Timeout on EAPOL-TX")
5554 hapd.request("SET ext_eapol_frame_io 0")
5555 dev[0].request("SET ext_eapol_frame_io 0")
5556 msg = ev.split(' ')[2]
5557 if msg[136:144] != '10480010':
5558 raise Exception("Could not find enrollee Nonce attribute")
5559 # Remove UUID-R. This will fail Authenticator check, but allows the code
5560 # path in wps_process_uuid_r() to be checked from the debug log.
5561 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5562 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:136] + msg[176:]
5563 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5564 if "OK" not in res:
5565 raise Exception("EAPOL_RX failed")
5566 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5567 if ev is None:
5568 raise Exception("Disconnect event not seen")
5569 dev[0].request("WPS_CANCEL")
5570 dev[0].flush_scan_cache()
5571
5572def test_ap_wps_m2_invalid(dev, apdev):
5573 """WPS and M2 parsing failure"""
5574 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5575 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5576 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5577 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5578 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5579 logger.debug("M2")
5580 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5581 if ev is None:
5582 raise Exception("Timeout on EAPOL-TX")
5583 hapd.request("SET ext_eapol_frame_io 0")
5584 dev[0].request("SET ext_eapol_frame_io 0")
5585 msg = ev.split(' ')[2]
5586 if msg[136:144] != '10480010':
5587 raise Exception("Could not find enrollee Nonce attribute")
5588 # Remove UUID-R. This will fail Authenticator check, but allows the code
5589 # path in wps_process_uuid_r() to be checked from the debug log.
5590 mlen = "%04x" % (int(msg[4:8], 16) - 1)
5591 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:-2]
5592 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5593 if "OK" not in res:
5594 raise Exception("EAPOL_RX failed")
5595 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5596 if ev is None:
5597 raise Exception("Disconnect event not seen")
5598 dev[0].request("WPS_CANCEL")
5599 dev[0].flush_scan_cache()
5600
5601def test_ap_wps_m2_missing_msg_type(dev, apdev):
5602 """WPS and M2 without Message Type"""
5603 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5604 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5605 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5606 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5607 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5608 logger.debug("M2")
5609 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5610 if ev is None:
5611 raise Exception("Timeout on EAPOL-TX")
5612 hapd.request("SET ext_eapol_frame_io 0")
5613 dev[0].request("SET ext_eapol_frame_io 0")
5614 msg = ev.split(' ')[2]
5615 if msg[46:54] != '10220001':
5616 raise Exception("Could not find Message Type attribute")
5617 # Remove Message Type. This will fail Authenticator check, but allows the
5618 # code path in wps_process_wsc_msg() to be checked from the debug log.
5619 mlen = "%04x" % (int(msg[4:8], 16) - 5)
5620 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:46] + 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_msg_type(dev, apdev):
5631 """WPS and M2 but unknown Message Type"""
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 if msg[46:54] != '10220001':
5645 raise Exception("Could not find Message Type attribute")
5646 # Replace Message Type value. This will be rejected.
5647 msg = msg[0:54] + "00" + msg[56:]
5648 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5649 if "OK" not in res:
5650 raise Exception("EAPOL_RX failed")
5651 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5652 if ev is None:
5653 raise Exception("Disconnect event not seen")
5654 dev[0].request("WPS_CANCEL")
5655 dev[0].flush_scan_cache()
5656
5657def test_ap_wps_m2_unknown_opcode(dev, apdev):
5658 """WPS and M2 but unknown opcode"""
5659 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5660 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5661 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5662 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5663 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5664 logger.debug("M2")
5665 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5666 if ev is None:
5667 raise Exception("Timeout on EAPOL-TX")
5668 hapd.request("SET ext_eapol_frame_io 0")
5669 dev[0].request("SET ext_eapol_frame_io 0")
5670 msg = ev.split(' ')[2]
5671 # Replace opcode. This will be discarded in EAP-WSC processing.
5672 msg = msg[0:32] + "00" + msg[34:]
5673 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5674 if "OK" not in res:
5675 raise Exception("EAPOL_RX failed")
5676 dev[0].request("WPS_CANCEL")
5677 dev[0].wait_disconnected()
5678 dev[0].flush_scan_cache()
5679
5680def test_ap_wps_m2_unknown_opcode2(dev, apdev):
5681 """WPS and M2 but unknown opcode (WSC_Start)"""
5682 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5683 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5684 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5685 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5686 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5687 logger.debug("M2")
5688 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5689 if ev is None:
5690 raise Exception("Timeout on EAPOL-TX")
5691 hapd.request("SET ext_eapol_frame_io 0")
5692 dev[0].request("SET ext_eapol_frame_io 0")
5693 msg = ev.split(' ')[2]
5694 # Replace opcode. This will be discarded in EAP-WSC processing.
5695 msg = msg[0:32] + "01" + msg[34:]
5696 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5697 if "OK" not in res:
5698 raise Exception("EAPOL_RX failed")
5699 dev[0].request("WPS_CANCEL")
5700 dev[0].wait_disconnected()
5701 dev[0].flush_scan_cache()
5702
5703def test_ap_wps_m2_unknown_opcode3(dev, apdev):
5704 """WPS and M2 but unknown opcode (WSC_Done)"""
5705 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5706 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5707 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5708 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5709 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5710 logger.debug("M2")
5711 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5712 if ev is None:
5713 raise Exception("Timeout on EAPOL-TX")
5714 hapd.request("SET ext_eapol_frame_io 0")
5715 dev[0].request("SET ext_eapol_frame_io 0")
5716 msg = ev.split(' ')[2]
5717 # Replace opcode. This will be discarded in WPS Enrollee processing.
5718 msg = msg[0:32] + "05" + msg[34:]
5719 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5720 if "OK" not in res:
5721 raise Exception("EAPOL_RX failed")
5722 dev[0].request("WPS_CANCEL")
5723 dev[0].wait_disconnected()
5724 dev[0].flush_scan_cache()
5725
5726def wps_m2_but_other(dev, apdev, title, msgtype):
5727 addr,bssid,hapd = wps_start_ext(apdev, dev)
5728 wps_ext_eap_identity_req(dev, hapd, bssid)
5729 wps_ext_eap_identity_resp(hapd, dev, addr)
5730 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5731 wps_ext_eap_wsc(hapd, dev, addr, "M1")
5732 logger.debug(title)
5733 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5734 if ev is None:
5735 raise Exception("Timeout on EAPOL-TX")
5736 hapd.request("SET ext_eapol_frame_io 0")
5737 dev.request("SET ext_eapol_frame_io 0")
5738 msg = ev.split(' ')[2]
5739 if msg[46:54] != '10220001':
5740 raise Exception("Could not find Message Type attribute")
5741 # Replace Message Type value. This will be rejected.
5742 msg = msg[0:54] + msgtype + msg[56:]
5743 res = dev.request("EAPOL_RX " + bssid + " " + msg)
5744 if "OK" not in res:
5745 raise Exception("EAPOL_RX failed")
5746 ev = dev.wait_event(["WPS-FAIL"], timeout=5)
5747 if ev is None:
5748 raise Exception("WPS-FAIL event not seen")
5749 dev.request("WPS_CANCEL")
5750 dev.wait_disconnected()
5751
5752def wps_m4_but_other(dev, apdev, title, msgtype):
5753 addr,bssid,hapd = wps_start_ext(apdev, dev)
5754 wps_ext_eap_identity_req(dev, hapd, bssid)
5755 wps_ext_eap_identity_resp(hapd, dev, addr)
5756 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5757 wps_ext_eap_wsc(hapd, dev, addr, "M1")
5758 wps_ext_eap_wsc(dev, hapd, bssid, "M2")
5759 wps_ext_eap_wsc(hapd, dev, addr, "M3")
5760 logger.debug(title)
5761 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5762 if ev is None:
5763 raise Exception("Timeout on EAPOL-TX")
5764 hapd.request("SET ext_eapol_frame_io 0")
5765 dev.request("SET ext_eapol_frame_io 0")
5766 msg = ev.split(' ')[2]
5767 if msg[46:54] != '10220001':
5768 raise Exception("Could not find Message Type attribute")
5769 # Replace Message Type value. This will be rejected.
5770 msg = msg[0:54] + msgtype + msg[56:]
5771 res = dev.request("EAPOL_RX " + bssid + " " + msg)
5772 if "OK" not in res:
5773 raise Exception("EAPOL_RX failed")
5774 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5775 if ev is None:
5776 raise Exception("WPS-FAIL event not seen")
5777 dev.request("WPS_CANCEL")
5778 dev.wait_disconnected()
5779
5780def test_ap_wps_m2_msg_type_m4(dev, apdev):
5781 """WPS and M2 but Message Type M4"""
5782 wps_m2_but_other(dev[0], apdev[0], "M2/M4", "08")
5783
5784def test_ap_wps_m2_msg_type_m6(dev, apdev):
5785 """WPS and M2 but Message Type M6"""
5786 wps_m2_but_other(dev[0], apdev[0], "M2/M6", "0a")
5787
5788def test_ap_wps_m2_msg_type_m8(dev, apdev):
5789 """WPS and M2 but Message Type M8"""
5790 wps_m2_but_other(dev[0], apdev[0], "M2/M8", "0c")
5791
5792def test_ap_wps_m4_msg_type_m2(dev, apdev):
5793 """WPS and M4 but Message Type M2"""
5794 wps_m4_but_other(dev[0], apdev[0], "M4/M2", "05")
5795
5796def test_ap_wps_m4_msg_type_m2d(dev, apdev):
5797 """WPS and M4 but Message Type M2D"""
5798 wps_m4_but_other(dev[0], apdev[0], "M4/M2D", "06")
5799
24b7f282
JM
5800def test_ap_wps_config_methods(dev, apdev):
5801 """WPS configuration method parsing"""
5802 ssid = "test-wps-conf"
5803 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5804 "wpa_passphrase": "12345678", "wpa": "2",
5805 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5806 "config_methods": "ethernet display ext_nfc_token int_nfc_token physical_display physical_push_button" }
8b8a1864 5807 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5808 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5809 "wpa_passphrase": "12345678", "wpa": "2",
5810 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5811 "config_methods": "display push_button" }
8b8a1864 5812 hapd2 = hostapd.add_ap(apdev[1], params)
476daa05
JM
5813
5814def test_ap_wps_set_selected_registrar_proto(dev, apdev):
5815 """WPS UPnP SetSelectedRegistrar protocol testing"""
5816 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 5817 hapd = add_ssdp_ap(apdev[0], ap_uuid)
476daa05
JM
5818
5819 location = ssdp_get_location(ap_uuid)
5820 urls = upnp_get_urls(location)
5821 eventurl = urlparse.urlparse(urls['event_sub_url'])
5822 ctrlurl = urlparse.urlparse(urls['control_url'])
5823 url = urlparse.urlparse(location)
5824 conn = httplib.HTTPConnection(url.netloc)
5825
5826 class WPSERHTTPServer(SocketServer.StreamRequestHandler):
5827 def handle(self):
5828 data = self.rfile.readline().strip()
5829 logger.debug(data)
5830 self.wfile.write(gen_wps_event())
5831
5832 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
5833 server.timeout = 1
5834
5835 headers = { "callback": '<http://127.0.0.1:12345/event>',
5836 "NT": "upnp:event",
5837 "timeout": "Second-1234" }
5838 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
5839 resp = conn.getresponse()
5840 if resp.status != 200:
5841 raise Exception("Unexpected HTTP response: %d" % resp.status)
5842 sid = resp.getheader("sid")
5843 logger.debug("Subscription SID " + sid)
5844 server.handle_request()
5845
5846 tests = [ (500, "10"),
5847 (200, "104a000110" + "1041000101" + "101200020000" +
5848 "105300023148" +
5849 "1049002c00372a0001200124111111111111222222222222333333333333444444444444555555555555666666666666" +
5850 "10480010362db47ba53a519188fb5458b986b2e4"),
5851 (200, "104a000110" + "1041000100" + "101200020000" +
5852 "105300020000"),
5853 (200, "104a000110" + "1041000100"),
5854 (200, "104a000110") ]
5855 for status,test in tests:
5856 tlvs = binascii.unhexlify(test)
5857 newmsg = base64.b64encode(tlvs)
5858 msg = '<?xml version="1.0"?>\n'
5859 msg += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
5860 msg += '<s:Body>'
5861 msg += '<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">'
5862 msg += '<NewMessage>'
5863 msg += newmsg
5864 msg += "</NewMessage></u:SetSelectedRegistrar></s:Body></s:Envelope>"
5865 headers = { "Content-type": 'text/xml; charset="utf-8"' }
5866 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
5867 conn.request("POST", ctrlurl.path, msg, headers)
5868 resp = conn.getresponse()
5869 if resp.status != status:
5870 raise Exception("Unexpected HTTP response: %d (expected %d)" % (resp.status, status))
96038a5f
JM
5871
5872def test_ap_wps_adv_oom(dev, apdev):
5873 """WPS AP and advertisement OOM"""
5874 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 5875 hapd = add_ssdp_ap(apdev[0], ap_uuid)
96038a5f
JM
5876
5877 with alloc_fail(hapd, 1, "=msearchreply_state_machine_start"):
5878 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
5879 no_recv=True)
5880 time.sleep(0.2)
5881
5882 with alloc_fail(hapd, 1, "eloop_register_timeout;msearchreply_state_machine_start"):
5883 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
5884 no_recv=True)
5885 time.sleep(0.2)
5886
5887 with alloc_fail(hapd, 1,
5888 "next_advertisement;advertisement_state_machine_stop"):
5889 hapd.disable()
5890
5891 with alloc_fail(hapd, 1, "ssdp_listener_start"):
5892 if "FAIL" not in hapd.request("ENABLE"):
5893 raise Exception("ENABLE succeeded during OOM")
926404a6
JM
5894
5895def test_wps_config_methods(dev):
5896 """WPS config method update"""
5897 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
5898 wpas.interface_add("wlan5")
5899 if "OK" not in wpas.request("SET config_methods display label"):
5900 raise Exception("Failed to set config_methods")
5901 if wpas.request("GET config_methods").strip() != "display label":
5902 raise Exception("config_methods were not updated")
5903 if "OK" not in wpas.request("SET config_methods "):
5904 raise Exception("Failed to clear config_methods")
5905 if wpas.request("GET config_methods").strip() != "":
5906 raise Exception("config_methods were not cleared")
7511ead0
JM
5907
5908WPS_VENDOR_ID_WFA = 14122
5909WPS_VENDOR_TYPE = 1
5910
5911# EAP-WSC Op-Code values
5912WSC_Start = 0x01
5913WSC_ACK = 0x02
5914WSC_NACK = 0x03
5915WSC_MSG = 0x04
5916WSC_Done = 0x05
5917WSC_FRAG_ACK = 0x06
5918
5919ATTR_AP_CHANNEL = 0x1001
5920ATTR_ASSOC_STATE = 0x1002
5921ATTR_AUTH_TYPE = 0x1003
5922ATTR_AUTH_TYPE_FLAGS = 0x1004
5923ATTR_AUTHENTICATOR = 0x1005
5924ATTR_CONFIG_METHODS = 0x1008
5925ATTR_CONFIG_ERROR = 0x1009
5926ATTR_CONFIRM_URL4 = 0x100a
5927ATTR_CONFIRM_URL6 = 0x100b
5928ATTR_CONN_TYPE = 0x100c
5929ATTR_CONN_TYPE_FLAGS = 0x100d
5930ATTR_CRED = 0x100e
5931ATTR_ENCR_TYPE = 0x100f
5932ATTR_ENCR_TYPE_FLAGS = 0x1010
5933ATTR_DEV_NAME = 0x1011
5934ATTR_DEV_PASSWORD_ID = 0x1012
5935ATTR_E_HASH1 = 0x1014
5936ATTR_E_HASH2 = 0x1015
5937ATTR_E_SNONCE1 = 0x1016
5938ATTR_E_SNONCE2 = 0x1017
5939ATTR_ENCR_SETTINGS = 0x1018
5940ATTR_ENROLLEE_NONCE = 0x101a
5941ATTR_FEATURE_ID = 0x101b
5942ATTR_IDENTITY = 0x101c
5943ATTR_IDENTITY_PROOF = 0x101d
5944ATTR_KEY_WRAP_AUTH = 0x101e
5945ATTR_KEY_ID = 0x101f
5946ATTR_MAC_ADDR = 0x1020
5947ATTR_MANUFACTURER = 0x1021
5948ATTR_MSG_TYPE = 0x1022
5949ATTR_MODEL_NAME = 0x1023
5950ATTR_MODEL_NUMBER = 0x1024
5951ATTR_NETWORK_INDEX = 0x1026
5952ATTR_NETWORK_KEY = 0x1027
5953ATTR_NETWORK_KEY_INDEX = 0x1028
5954ATTR_NEW_DEVICE_NAME = 0x1029
5955ATTR_NEW_PASSWORD = 0x102a
5956ATTR_OOB_DEVICE_PASSWORD = 0x102c
5957ATTR_OS_VERSION = 0x102d
5958ATTR_POWER_LEVEL = 0x102f
5959ATTR_PSK_CURRENT = 0x1030
5960ATTR_PSK_MAX = 0x1031
5961ATTR_PUBLIC_KEY = 0x1032
5962ATTR_RADIO_ENABLE = 0x1033
5963ATTR_REBOOT = 0x1034
5964ATTR_REGISTRAR_CURRENT = 0x1035
5965ATTR_REGISTRAR_ESTABLISHED = 0x1036
5966ATTR_REGISTRAR_LIST = 0x1037
5967ATTR_REGISTRAR_MAX = 0x1038
5968ATTR_REGISTRAR_NONCE = 0x1039
5969ATTR_REQUEST_TYPE = 0x103a
5970ATTR_RESPONSE_TYPE = 0x103b
5971ATTR_RF_BANDS = 0x103c
5972ATTR_R_HASH1 = 0x103d
5973ATTR_R_HASH2 = 0x103e
5974ATTR_R_SNONCE1 = 0x103f
5975ATTR_R_SNONCE2 = 0x1040
5976ATTR_SELECTED_REGISTRAR = 0x1041
5977ATTR_SERIAL_NUMBER = 0x1042
5978ATTR_WPS_STATE = 0x1044
5979ATTR_SSID = 0x1045
5980ATTR_TOTAL_NETWORKS = 0x1046
5981ATTR_UUID_E = 0x1047
5982ATTR_UUID_R = 0x1048
5983ATTR_VENDOR_EXT = 0x1049
5984ATTR_VERSION = 0x104a
5985ATTR_X509_CERT_REQ = 0x104b
5986ATTR_X509_CERT = 0x104c
5987ATTR_EAP_IDENTITY = 0x104d
5988ATTR_MSG_COUNTER = 0x104e
5989ATTR_PUBKEY_HASH = 0x104f
5990ATTR_REKEY_KEY = 0x1050
5991ATTR_KEY_LIFETIME = 0x1051
5992ATTR_PERMITTED_CFG_METHODS = 0x1052
5993ATTR_SELECTED_REGISTRAR_CONFIG_METHODS = 0x1053
5994ATTR_PRIMARY_DEV_TYPE = 0x1054
5995ATTR_SECONDARY_DEV_TYPE_LIST = 0x1055
5996ATTR_PORTABLE_DEV = 0x1056
5997ATTR_AP_SETUP_LOCKED = 0x1057
5998ATTR_APPLICATION_EXT = 0x1058
5999ATTR_EAP_TYPE = 0x1059
6000ATTR_IV = 0x1060
6001ATTR_KEY_PROVIDED_AUTO = 0x1061
6002ATTR_802_1X_ENABLED = 0x1062
6003ATTR_APPSESSIONKEY = 0x1063
6004ATTR_WEPTRANSMITKEY = 0x1064
6005ATTR_REQUESTED_DEV_TYPE = 0x106a
6006
6007# Message Type
6008WPS_Beacon = 0x01
6009WPS_ProbeRequest = 0x02
6010WPS_ProbeResponse = 0x03
6011WPS_M1 = 0x04
6012WPS_M2 = 0x05
6013WPS_M2D = 0x06
6014WPS_M3 = 0x07
6015WPS_M4 = 0x08
6016WPS_M5 = 0x09
6017WPS_M6 = 0x0a
6018WPS_M7 = 0x0b
6019WPS_M8 = 0x0c
6020WPS_WSC_ACK = 0x0d
6021WPS_WSC_NACK = 0x0e
6022WPS_WSC_DONE = 0x0f
6023
6024def get_wsc_msg(dev):
6025 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
6026 if ev is None:
6027 raise Exception("Timeout on EAPOL-TX")
6028 data = binascii.unhexlify(ev.split(' ')[2])
6029 msg = {}
6030
6031 # Parse EAPOL header
6032 if len(data) < 4:
6033 raise Exception("No room for EAPOL header")
6034 version,type,length = struct.unpack('>BBH', data[0:4])
6035 msg['eapol_version'] = version
6036 msg['eapol_type'] = type
6037 msg['eapol_length'] = length
6038 data = data[4:]
6039 if length != len(data):
6040 raise Exception("EAPOL header length mismatch (%d != %d)" % (length, len(data)))
6041 if type != 0:
6042 raise Exception("Unexpected EAPOL header type: %d" % type)
6043
6044 # Parse EAP header
6045 if len(data) < 4:
6046 raise Exception("No room for EAP header")
6047 code,identifier,length = struct.unpack('>BBH', data[0:4])
6048 msg['eap_code'] = code
6049 msg['eap_identifier'] = identifier
6050 msg['eap_length'] = length
6051 data = data[4:]
6052 if msg['eapol_length'] != msg['eap_length']:
6053 raise Exception("EAP header length mismatch (%d != %d)" % (msg['eapol_length'], length))
6054
6055 # Parse EAP expanded header
6056 if len(data) < 1:
6057 raise Exception("No EAP type included")
6058 msg['eap_type'], = struct.unpack('B', data[0])
6059 data = data[1:]
6060
6061 if msg['eap_type'] == 254:
6062 if len(data) < 3 + 4:
6063 raise Exception("Truncated EAP expanded header")
6064 msg['eap_vendor_id'], msg['eap_vendor_type'] = struct.unpack('>LL', '\0' + data[0:7])
6065 data = data[7:]
6066 else:
6067 raise Exception("Unexpected EAP type")
6068
6069 if msg['eap_vendor_id'] != WPS_VENDOR_ID_WFA:
6070 raise Exception("Unexpected Vendor-Id")
6071 if msg['eap_vendor_type'] != WPS_VENDOR_TYPE:
6072 raise Exception("Unexpected Vendor-Type")
6073
6074 # Parse EAP-WSC header
6075 if len(data) < 2:
6076 raise Exception("Truncated EAP-WSC header")
6077 msg['wsc_opcode'], msg['wsc_flags'] = struct.unpack('BB', data[0:2])
6078 data = data[2:]
6079
6080 # Parse WSC attributes
6081 msg['raw_attrs'] = data
6082 attrs = {}
6083 while len(data) > 0:
6084 if len(data) < 4:
6085 raise Exception("Truncated attribute header")
6086 attr,length = struct.unpack('>HH', data[0:4])
6087 data = data[4:]
6088 if length > len(data):
6089 raise Exception("Truncated attribute 0x%04x" % attr)
6090 attrs[attr] = data[0:length]
6091 data = data[length:]
6092 msg['wsc_attrs'] = attrs
6093
6094 if ATTR_MSG_TYPE in attrs:
6095 msg['wsc_msg_type'], = struct.unpack('B', attrs[ATTR_MSG_TYPE])
6096
6097 return msg
6098
6099def recv_wsc_msg(dev, opcode, msg_type):
6100 msg = get_wsc_msg(dev)
6101 if msg['wsc_opcode'] != opcode or msg['wsc_msg_type'] != msg_type:
6102 raise Exception("Unexpected Op-Code/MsgType")
6103 return msg, msg['wsc_attrs'], msg['raw_attrs']
6104
6105def build_wsc_attr(attr, payload):
6106 return struct.pack('>HH', attr, len(payload)) + payload
6107
6108def build_attr_msg_type(msg_type):
6109 return build_wsc_attr(ATTR_MSG_TYPE, struct.pack('B', msg_type))
6110
6111def build_eap_wsc(eap_code, eap_id, payload, opcode=WSC_MSG):
6112 length = 4 + 8 + 2 + len(payload)
6113 # EAPOL header
6114 msg = struct.pack('>BBH', 2, 0, length)
6115 # EAP header
6116 msg += struct.pack('>BBH', eap_code, eap_id, length)
6117 # EAP expanded header for EAP-WSC
6118 msg += struct.pack('B', 254)
6119 msg += struct.pack('>L', WPS_VENDOR_ID_WFA)[1:4]
6120 msg += struct.pack('>L', WPS_VENDOR_TYPE)
6121 # EAP-WSC header
6122 msg += struct.pack('BB', opcode, 0)
6123 # WSC attributes
6124 msg += payload
6125 return msg
6126
6127def build_eap_success(eap_id):
6128 length = 4
6129 # EAPOL header
6130 msg = struct.pack('>BBH', 2, 0, length)
6131 # EAP header
6132 msg += struct.pack('>BBH', 3, eap_id, length)
6133 return msg
6134
6135def build_eap_failure(eap_id):
6136 length = 4
6137 # EAPOL header
6138 msg = struct.pack('>BBH', 2, 0, length)
6139 # EAP header
6140 msg += struct.pack('>BBH', 4, eap_id, length)
6141 return msg
6142
6143def send_wsc_msg(dev, src, msg):
6144 res = dev.request("EAPOL_RX " + src + " " + binascii.hexlify(msg))
6145 if "OK" not in res:
6146 raise Exception("EAPOL_RX failed")
6147
6148group_5_prime = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF
6149group_5_generator = 2
6150
6151def wsc_kdf(key, label, bits):
6152 result = ''
6153 i = 1
6154 while len(result) * 8 < bits:
6155 data = struct.pack('>L', i) + label + struct.pack('>L', bits)
6156 m = hmac.new(key, data, hashlib.sha256)
6157 result += m.digest()
6158 i += 1
6159 return result[0:bits / 8]
6160
6161def wsc_keys(kdk):
6162 keys = wsc_kdf(kdk, "Wi-Fi Easy and Secure Key Derivation", 640)
6163 authkey = keys[0:32]
6164 keywrapkey = keys[32:48]
6165 emsk = keys[48:80]
6166 return authkey,keywrapkey,emsk
6167
6168def wsc_dev_pw_half_psk(authkey, dev_pw):
6169 m = hmac.new(authkey, dev_pw, hashlib.sha256)
6170 return m.digest()[0:16]
6171
6172def wsc_dev_pw_psk(authkey, dev_pw):
6173 dev_pw_1 = dev_pw[0:len(dev_pw) / 2]
6174 dev_pw_2 = dev_pw[len(dev_pw) / 2:]
6175 psk1 = wsc_dev_pw_half_psk(authkey, dev_pw_1)
6176 psk2 = wsc_dev_pw_half_psk(authkey, dev_pw_2)
6177 return psk1,psk2
6178
6179def build_attr_authenticator(authkey, prev_msg, curr_msg):
6180 m = hmac.new(authkey, prev_msg + curr_msg, hashlib.sha256)
6181 auth = m.digest()[0:8]
6182 return build_wsc_attr(ATTR_AUTHENTICATOR, auth)
6183
6184def build_attr_encr_settings(authkey, keywrapkey, data):
6185 m = hmac.new(authkey, data, hashlib.sha256)
6186 kwa = m.digest()[0:8]
6187 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6188 iv = 16*'\x99'
6189 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6190 pad_len = 16 - len(data) % 16
6191 ps = pad_len * struct.pack('B', pad_len)
6192 data += ps
6193 wrapped = aes.encrypt(data)
6194 return build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6195
6196def decrypt_attr_encr_settings(authkey, keywrapkey, data):
6197 if len(data) < 32 or len(data) % 16 != 0:
6198 raise Exception("Unexpected Encrypted Settings length: %d" % len(data))
6199 iv = data[0:16]
6200 encr = data[16:]
6201 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6202 decrypted = aes.decrypt(encr)
6203 pad_len, = struct.unpack('B', decrypted[-1])
6204 if pad_len > len(decrypted):
6205 raise Exception("Invalid padding in Encrypted Settings")
6206 for i in range(-pad_len, -1):
6207 if decrypted[i] != decrypted[-1]:
6208 raise Exception("Invalid PS value in Encrypted Settings")
6209
6210 decrypted = decrypted[0:len(decrypted) - pad_len]
6211 if len(decrypted) < 12:
6212 raise Exception("Truncated Encrypted Settings plaintext")
6213 kwa = decrypted[-12:]
6214 attr,length = struct.unpack(">HH", kwa[0:4])
6215 if attr != ATTR_KEY_WRAP_AUTH or length != 8:
6216 raise Exception("Invalid KWA header")
6217 kwa = kwa[4:]
6218 decrypted = decrypted[0:len(decrypted) - 12]
6219
6220 m = hmac.new(authkey, decrypted, hashlib.sha256)
6221 calc_kwa = m.digest()[0:8]
6222 if kwa != calc_kwa:
6223 raise Exception("KWA mismatch")
6224
6225 return decrypted
6226
6227def zeropad_str(val, pad_len):
6228 while len(val) < pad_len * 2:
6229 val = '0' + val
6230 return val
6231
6232def wsc_dh_init():
6233 # For now, use a hardcoded private key. In theory, this is supposed to be
6234 # randomly selected.
6235 own_private = 0x123456789
6236 own_public = pow(group_5_generator, own_private, group_5_prime)
6237 pk = binascii.unhexlify(zeropad_str(format(own_public, '02x'), 192))
6238 return own_private, pk
6239
6240def wsc_dh_kdf(peer_pk, own_private, mac_addr, e_nonce, r_nonce):
6241 peer_public = long(binascii.hexlify(peer_pk), 16)
6242 if peer_public < 2 or peer_public >= group_5_prime:
6243 raise Exception("Invalid peer public key")
6244 if pow(peer_public, (group_5_prime - 1) / 2, group_5_prime) != 1:
6245 raise Exception("Unexpected Legendre symbol for peer public key")
6246
6247 shared_secret = pow(peer_public, own_private, group_5_prime)
6248 ss = zeropad_str(format(shared_secret, "02x"), 192)
6249 logger.debug("DH shared secret: " + ss)
6250
6251 dhkey = hashlib.sha256(binascii.unhexlify(ss)).digest()
6252 logger.debug("DHKey: " + binascii.hexlify(dhkey))
6253
6254 m = hmac.new(dhkey, e_nonce + mac_addr + r_nonce, hashlib.sha256)
6255 kdk = m.digest()
6256 logger.debug("KDK: " + binascii.hexlify(kdk))
6257 authkey,keywrapkey,emsk = wsc_keys(kdk)
6258 logger.debug("AuthKey: " + binascii.hexlify(authkey))
6259 logger.debug("KeyWrapKey: " + binascii.hexlify(keywrapkey))
6260 logger.debug("EMSK: " + binascii.hexlify(emsk))
6261 return authkey,keywrapkey
6262
6263def wsc_dev_pw_hash(authkey, dev_pw, e_pk, r_pk):
6264 psk1,psk2 = wsc_dev_pw_psk(authkey, dev_pw)
6265 logger.debug("PSK1: " + binascii.hexlify(psk1))
6266 logger.debug("PSK2: " + binascii.hexlify(psk2))
6267
6268 # Note: Secret values are supposed to be random, but hardcoded values are
6269 # fine for testing.
6270 s1 = 16*'\x77'
6271 m = hmac.new(authkey, s1 + psk1 + e_pk + r_pk, hashlib.sha256)
6272 hash1 = m.digest()
6273 logger.debug("Hash1: " + binascii.hexlify(hash1))
6274
6275 s2 = 16*'\x88'
6276 m = hmac.new(authkey, s2 + psk2 + e_pk + r_pk, hashlib.sha256)
6277 hash2 = m.digest()
6278 logger.debug("Hash2: " + binascii.hexlify(hash2))
6279 return s1,s2,hash1,hash2
6280
6281def build_m1(eap_id, uuid_e, mac_addr, e_nonce, e_pk,
6282 manufacturer='', model_name='', config_methods='\x00\x00'):
6283 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6284 attrs += build_attr_msg_type(WPS_M1)
6285 attrs += build_wsc_attr(ATTR_UUID_E, uuid_e)
6286 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6287 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6288 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, e_pk)
6289 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6290 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6291 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6292 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, config_methods)
6293 attrs += build_wsc_attr(ATTR_WPS_STATE, '\x00')
6294 attrs += build_wsc_attr(ATTR_MANUFACTURER, manufacturer)
6295 attrs += build_wsc_attr(ATTR_MODEL_NAME, model_name)
6296 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6297 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6298 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6299 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6300 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6301 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6302 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, '\x00\x00')
6303 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6304 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6305 m1 = build_eap_wsc(2, eap_id, attrs)
6306 return m1, attrs
6307
6308def build_m2(authkey, m1, eap_id, e_nonce, r_nonce, uuid_r, r_pk,
6309 dev_pw_id='\x00\x00', eap_code=1):
6310 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6311 attrs += build_attr_msg_type(WPS_M2)
6312 if e_nonce:
6313 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6314 if r_nonce:
6315 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6316 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6317 if r_pk:
6318 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, r_pk)
6319 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6320 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6321 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6322 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6323 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6324 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6325 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6326 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6327 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6328 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6329 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6330 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6331 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6332 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6333 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6334 attrs += build_attr_authenticator(authkey, m1, attrs)
6335 m2 = build_eap_wsc(eap_code, eap_id, attrs)
6336 return m2, attrs
6337
6338def build_m2d(m1, eap_id, e_nonce, r_nonce, uuid_r, dev_pw_id=None, eap_code=1):
6339 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6340 attrs += build_attr_msg_type(WPS_M2D)
6341 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6342 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6343 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6344 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6345 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6346 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6347 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6348 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6349 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6350 #attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6351 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6352 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6353 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6354 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6355 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6356 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6357 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6358 if dev_pw_id:
6359 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6360 m2d = build_eap_wsc(eap_code, eap_id, attrs)
6361 return m2d, attrs
6362
6363def build_ack(eap_id, e_nonce, r_nonce, msg_type=WPS_WSC_ACK, eap_code=1):
6364 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6365 if msg_type is not None:
6366 attrs += build_attr_msg_type(msg_type)
6367 if e_nonce:
6368 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6369 if r_nonce:
6370 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6371 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_ACK)
6372 return msg, attrs
6373
6374def build_nack(eap_id, e_nonce, r_nonce, config_error='\x00\x00',
6375 msg_type=WPS_WSC_NACK, eap_code=1):
6376 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6377 if msg_type is not None:
6378 attrs += build_attr_msg_type(msg_type)
6379 if e_nonce:
6380 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6381 if r_nonce:
6382 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6383 if config_error:
6384 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, config_error)
6385 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_NACK)
6386 return msg, attrs
6387
6388def test_wps_ext(dev, apdev):
6389 """WPS against external implementation"""
6390 pin = "12345670"
6391 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6392 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6393 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6394
6395 logger.debug("Receive WSC/Start from AP")
6396 msg = get_wsc_msg(hapd)
6397 if msg['wsc_opcode'] != WSC_Start:
6398 raise Exception("Unexpected Op-Code for WSC/Start")
6399 wsc_start_id = msg['eap_identifier']
6400
6401 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6402 uuid_e = 16*'\x11'
6403 e_nonce = 16*'\x22'
6404 own_private, e_pk = wsc_dh_init()
6405
6406 logger.debug("Send M1 to AP")
6407 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
6408 e_nonce, e_pk)
6409 send_wsc_msg(hapd, addr, m1)
6410
6411 logger.debug("Receive M2 from AP")
6412 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
6413
6414 authkey,keywrapkey = wsc_dh_kdf(m2_attrs[ATTR_PUBLIC_KEY], own_private,
6415 mac_addr, e_nonce,
6416 m2_attrs[ATTR_REGISTRAR_NONCE])
6417 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk,
6418 m2_attrs[ATTR_PUBLIC_KEY])
6419
6420 logger.debug("Send M3 to AP")
6421 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6422 attrs += build_attr_msg_type(WPS_M3)
6423 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6424 m2_attrs[ATTR_REGISTRAR_NONCE])
6425 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
6426 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
6427 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
6428 raw_m3_attrs = attrs
6429 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6430 send_wsc_msg(hapd, addr, m3)
6431
6432 logger.debug("Receive M4 from AP")
6433 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
6434
6435 logger.debug("Send M5 to AP")
6436 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6437 attrs += build_attr_msg_type(WPS_M5)
6438 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6439 m2_attrs[ATTR_REGISTRAR_NONCE])
6440 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
6441 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6442 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
6443 raw_m5_attrs = attrs
6444 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6445 send_wsc_msg(hapd, addr, m5)
6446
6447 logger.debug("Receive M6 from AP")
6448 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
6449
6450 logger.debug("Send M7 to AP")
6451 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6452 attrs += build_attr_msg_type(WPS_M7)
6453 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6454 m2_attrs[ATTR_REGISTRAR_NONCE])
6455 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
6456 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6457 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
6458 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6459 raw_m7_attrs = attrs
6460 send_wsc_msg(hapd, addr, m7)
6461
6462 logger.debug("Receive M8 from AP")
6463 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
6464 m8_cred = decrypt_attr_encr_settings(authkey, keywrapkey,
6465 m8_attrs[ATTR_ENCR_SETTINGS])
6466 logger.debug("M8 Credential: " + binascii.hexlify(m8_cred))
6467
6468 logger.debug("Prepare WSC_Done")
6469 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6470 attrs += build_attr_msg_type(WPS_WSC_DONE)
6471 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6472 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6473 m2_attrs[ATTR_REGISTRAR_NONCE])
6474 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
6475 # Do not send WSC_Done yet to allow exchangw with STA complete before the
6476 # AP disconnects.
6477
6478 uuid_r = 16*'\x33'
6479 r_nonce = 16*'\x44'
6480
6481 eap_id = wsc_start_id
6482 logger.debug("Send WSC/Start to STA")
6483 wsc_start = build_eap_wsc(1, eap_id, "", opcode=WSC_Start)
6484 send_wsc_msg(dev[0], bssid, wsc_start)
6485 eap_id = (eap_id + 1) % 256
6486
6487 logger.debug("Receive M1 from STA")
6488 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6489
6490 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6491 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6492 r_nonce)
6493 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6494 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6495
6496 logger.debug("Send M2 to STA")
6497 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6498 m1_attrs[ATTR_ENROLLEE_NONCE],
6499 r_nonce, uuid_r, e_pk)
6500 send_wsc_msg(dev[0], bssid, m2)
6501 eap_id = (eap_id + 1) % 256
6502
6503 logger.debug("Receive M3 from STA")
6504 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6505
6506 logger.debug("Send M4 to STA")
6507 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6508 attrs += build_attr_msg_type(WPS_M4)
6509 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6510 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6511 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6512 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6513 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6514 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6515 raw_m4_attrs = attrs
6516 m4 = build_eap_wsc(1, eap_id, attrs)
6517 send_wsc_msg(dev[0], bssid, m4)
6518 eap_id = (eap_id + 1) % 256
6519
6520 logger.debug("Receive M5 from STA")
6521 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6522
6523 logger.debug("Send M6 to STA")
6524 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6525 attrs += build_attr_msg_type(WPS_M6)
6526 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6527 m1_attrs[ATTR_ENROLLEE_NONCE])
6528 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6529 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6530 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6531 raw_m6_attrs = attrs
6532 m6 = build_eap_wsc(1, eap_id, attrs)
6533 send_wsc_msg(dev[0], bssid, m6)
6534 eap_id = (eap_id + 1) % 256
6535
6536 logger.debug("Receive M7 from STA")
6537 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6538
6539 logger.debug("Send M8 to STA")
6540 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6541 attrs += build_attr_msg_type(WPS_M8)
6542 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6543 m1_attrs[ATTR_ENROLLEE_NONCE])
6544 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6545 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6546 raw_m8_attrs = attrs
6547 m8 = build_eap_wsc(1, eap_id, attrs)
6548 send_wsc_msg(dev[0], bssid, m8)
6549 eap_id = (eap_id + 1) % 256
6550
6551 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=5)
6552 if ev is None:
6553 raise Exception("wpa_supplicant did not report credential")
6554
6555 logger.debug("Receive WSC_Done from STA")
6556 msg = get_wsc_msg(dev[0])
6557 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6558 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6559
6560 logger.debug("Send WSC_Done to AP")
6561 hapd.request("SET ext_eapol_frame_io 0")
6562 dev[0].request("SET ext_eapol_frame_io 0")
6563 send_wsc_msg(hapd, addr, wsc_done)
6564
6565 ev = hapd.wait_event(["WPS-REG-SUCCESS"], timeout=5)
6566 if ev is None:
6567 raise Exception("hostapd did not report WPS success")
6568
6569 dev[0].wait_connected()
6570
6571def wps_start_kwa(dev, apdev):
6572 pin = "12345670"
6573 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6574 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6575 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6576 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6577
6578 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6579 uuid_r = 16*'\x33'
6580 r_nonce = 16*'\x44'
6581 own_private, e_pk = wsc_dh_init()
6582
6583 logger.debug("Receive M1 from STA")
6584 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6585 eap_id = (msg['eap_identifier'] + 1) % 256
6586
6587 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6588 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6589 r_nonce)
6590 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6591 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6592
6593 logger.debug("Send M2 to STA")
6594 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6595 m1_attrs[ATTR_ENROLLEE_NONCE],
6596 r_nonce, uuid_r, e_pk)
6597 send_wsc_msg(dev[0], bssid, m2)
6598 eap_id = (eap_id + 1) % 256
6599
6600 logger.debug("Receive M3 from STA")
6601 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6602
6603 logger.debug("Send M4 to STA")
6604 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6605 attrs += build_attr_msg_type(WPS_M4)
6606 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6607 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6608 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6609
6610 return r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs
6611
6612def wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id):
6613 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6614 m4 = build_eap_wsc(1, eap_id, attrs)
6615 send_wsc_msg(dev[0], bssid, m4)
6616 eap_id = (eap_id + 1) % 256
6617
6618 logger.debug("Receive M5 from STA")
6619 msg = get_wsc_msg(dev[0])
6620 if msg['wsc_opcode'] != WSC_NACK:
6621 raise Exception("Unexpected message - expected WSC_Nack")
6622
6623 dev[0].request("WPS_CANCEL")
6624 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6625 dev[0].wait_disconnected()
6626
6627def test_wps_ext_kwa_proto_no_kwa(dev, apdev):
6628 """WPS and KWA error: No KWA attribute"""
6629 r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6630 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6631 # Encrypted Settings without KWA
6632 iv = 16*'\x99'
6633 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6634 pad_len = 16 - len(data) % 16
6635 ps = pad_len * struct.pack('B', pad_len)
6636 data += ps
6637 wrapped = aes.encrypt(data)
6638 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6639 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6640
6641def test_wps_ext_kwa_proto_data_after_kwa(dev, apdev):
6642 """WPS and KWA error: Data after KWA"""
6643 r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6644 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6645 # Encrypted Settings and data after KWA
6646 m = hmac.new(authkey, data, hashlib.sha256)
6647 kwa = m.digest()[0:8]
6648 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6649 data += build_wsc_attr(ATTR_VENDOR_EXT, "1234567890")
6650 iv = 16*'\x99'
6651 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6652 pad_len = 16 - len(data) % 16
6653 ps = pad_len * struct.pack('B', pad_len)
6654 data += ps
6655 wrapped = aes.encrypt(data)
6656 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6657 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6658
6659def test_wps_ext_kwa_proto_kwa_mismatch(dev, apdev):
6660 """WPS and KWA error: KWA mismatch"""
6661 r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6662 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6663 # Encrypted Settings and KWA with incorrect value
6664 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, 8*'\x00')
6665 iv = 16*'\x99'
6666 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6667 pad_len = 16 - len(data) % 16
6668 ps = pad_len * struct.pack('B', pad_len)
6669 data += ps
6670 wrapped = aes.encrypt(data)
6671 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6672 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6673
6674def wps_run_cred_proto(dev, apdev, m8_cred, connect=False, no_connect=False):
6675 pin = "12345670"
6676 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6677 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6678 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6679 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6680
6681 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6682 uuid_r = 16*'\x33'
6683 r_nonce = 16*'\x44'
6684 own_private, e_pk = wsc_dh_init()
6685
6686 logger.debug("Receive M1 from STA")
6687 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6688 eap_id = (msg['eap_identifier'] + 1) % 256
6689
6690 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6691 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6692 r_nonce)
6693 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6694 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6695
6696 logger.debug("Send M2 to STA")
6697 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6698 m1_attrs[ATTR_ENROLLEE_NONCE],
6699 r_nonce, uuid_r, e_pk)
6700 send_wsc_msg(dev[0], bssid, m2)
6701 eap_id = (eap_id + 1) % 256
6702
6703 logger.debug("Receive M3 from STA")
6704 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6705
6706 logger.debug("Send M4 to STA")
6707 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6708 attrs += build_attr_msg_type(WPS_M4)
6709 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6710 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6711 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6712 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6713 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6714 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6715 raw_m4_attrs = attrs
6716 m4 = build_eap_wsc(1, eap_id, attrs)
6717 send_wsc_msg(dev[0], bssid, m4)
6718 eap_id = (eap_id + 1) % 256
6719
6720 logger.debug("Receive M5 from STA")
6721 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6722
6723 logger.debug("Send M6 to STA")
6724 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6725 attrs += build_attr_msg_type(WPS_M6)
6726 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6727 m1_attrs[ATTR_ENROLLEE_NONCE])
6728 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6729 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6730 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6731 raw_m6_attrs = attrs
6732 m6 = build_eap_wsc(1, eap_id, attrs)
6733 send_wsc_msg(dev[0], bssid, m6)
6734 eap_id = (eap_id + 1) % 256
6735
6736 logger.debug("Receive M7 from STA")
6737 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6738
6739 logger.debug("Send M8 to STA")
6740 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6741 attrs += build_attr_msg_type(WPS_M8)
6742 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6743 m1_attrs[ATTR_ENROLLEE_NONCE])
6744 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6745 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6746 raw_m8_attrs = attrs
6747 m8 = build_eap_wsc(1, eap_id, attrs)
6748 send_wsc_msg(dev[0], bssid, m8)
6749 eap_id = (eap_id + 1) % 256
6750
6751 if no_connect:
6752 logger.debug("Receive WSC_Done from STA")
6753 msg = get_wsc_msg(dev[0])
6754 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6755 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6756
6757 hapd.request("SET ext_eapol_frame_io 0")
6758 dev[0].request("SET ext_eapol_frame_io 0")
6759
6760 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6761
6762 dev[0].wait_disconnected()
6763 dev[0].request("REMOVE_NETWORK all")
6764 elif connect:
6765 logger.debug("Receive WSC_Done from STA")
6766 msg = get_wsc_msg(dev[0])
6767 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6768 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6769
6770 hapd.request("SET ext_eapol_frame_io 0")
6771 dev[0].request("SET ext_eapol_frame_io 0")
6772
6773 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6774
6775 dev[0].wait_connected()
6776 else:
6777 # Verify STA NACK's the credential
6778 msg = get_wsc_msg(dev[0])
6779 if msg['wsc_opcode'] != WSC_NACK:
6780 raise Exception("Unexpected message - expected WSC_Nack")
6781 dev[0].request("WPS_CANCEL")
6782 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6783 dev[0].wait_disconnected()
6784
6785def build_cred(nw_idx='\x01', ssid='test-wps-conf', auth_type='\x00\x20',
6786 encr_type='\x00\x08', nw_key="12345678",
6787 mac_addr='\x00\x00\x00\x00\x00\x00'):
6788 attrs = ''
6789 if nw_idx is not None:
6790 attrs += build_wsc_attr(ATTR_NETWORK_INDEX, nw_idx)
6791 if ssid is not None:
6792 attrs += build_wsc_attr(ATTR_SSID, ssid)
6793 if auth_type is not None:
6794 attrs += build_wsc_attr(ATTR_AUTH_TYPE, auth_type)
6795 if encr_type is not None:
6796 attrs += build_wsc_attr(ATTR_ENCR_TYPE, encr_type)
6797 if nw_key is not None:
6798 attrs += build_wsc_attr(ATTR_NETWORK_KEY, nw_key)
6799 if mac_addr is not None:
6800 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6801 return build_wsc_attr(ATTR_CRED, attrs)
6802
6803def test_wps_ext_cred_proto_success(dev, apdev):
6804 """WPS and Credential: success"""
6805 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6806 m8_cred = build_cred(mac_addr=mac_addr)
6807 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6808
6809def test_wps_ext_cred_proto_mac_addr_mismatch(dev, apdev):
6810 """WPS and Credential: MAC Address mismatch"""
6811 m8_cred = build_cred()
6812 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6813
6814def test_wps_ext_cred_proto_zero_padding(dev, apdev):
6815 """WPS and Credential: zeropadded attributes"""
6816 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6817 m8_cred = build_cred(mac_addr=mac_addr, ssid='test-wps-conf\x00',
6818 nw_key="12345678\x00")
6819 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6820
6821def test_wps_ext_cred_proto_ssid_missing(dev, apdev):
6822 """WPS and Credential: SSID missing"""
6823 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6824 m8_cred = build_cred(mac_addr=mac_addr, ssid=None)
6825 wps_run_cred_proto(dev, apdev, m8_cred)
6826
6827def test_wps_ext_cred_proto_ssid_zero_len(dev, apdev):
6828 """WPS and Credential: Zero-length SSID"""
6829 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6830 m8_cred = build_cred(mac_addr=mac_addr, ssid="")
6831 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6832
6833def test_wps_ext_cred_proto_auth_type_missing(dev, apdev):
6834 """WPS and Credential: Auth Type missing"""
6835 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6836 m8_cred = build_cred(mac_addr=mac_addr, auth_type=None)
6837 wps_run_cred_proto(dev, apdev, m8_cred)
6838
6839def test_wps_ext_cred_proto_encr_type_missing(dev, apdev):
6840 """WPS and Credential: Encr Type missing"""
6841 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6842 m8_cred = build_cred(mac_addr=mac_addr, encr_type=None)
6843 wps_run_cred_proto(dev, apdev, m8_cred)
6844
6845def test_wps_ext_cred_proto_network_key_missing(dev, apdev):
6846 """WPS and Credential: Network Key missing"""
6847 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6848 m8_cred = build_cred(mac_addr=mac_addr, nw_key=None)
6849 wps_run_cred_proto(dev, apdev, m8_cred)
6850
6851def test_wps_ext_cred_proto_network_key_missing_open(dev, apdev):
6852 """WPS and Credential: Network Key missing (open)"""
6853 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6854 m8_cred = build_cred(mac_addr=mac_addr, auth_type='\x00\x01',
6855 encr_type='\x00\x01', nw_key=None, ssid="foo")
6856 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6857
6858def test_wps_ext_cred_proto_mac_addr_missing(dev, apdev):
6859 """WPS and Credential: MAC Address missing"""
6860 m8_cred = build_cred(mac_addr=None)
6861 wps_run_cred_proto(dev, apdev, m8_cred)
6862
6863def test_wps_ext_cred_proto_invalid_encr_type(dev, apdev):
6864 """WPS and Credential: Invalid Encr Type"""
6865 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6866 m8_cred = build_cred(mac_addr=mac_addr, encr_type='\x00\x00')
6867 wps_run_cred_proto(dev, apdev, m8_cred)
6868
6869def test_wps_ext_cred_proto_missing_cred(dev, apdev):
6870 """WPS and Credential: Missing Credential"""
6871 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6872 m8_cred = ''
6873 wps_run_cred_proto(dev, apdev, m8_cred)
6874
6875def test_wps_ext_proto_m2_no_public_key(dev, apdev):
6876 """WPS and no Public Key in M2"""
6877 pin = "12345670"
6878 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6879 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6880 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6881 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6882
6883 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6884 uuid_r = 16*'\x33'
6885 r_nonce = 16*'\x44'
6886 own_private, e_pk = wsc_dh_init()
6887
6888 logger.debug("Receive M1 from STA")
6889 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6890 eap_id = (msg['eap_identifier'] + 1) % 256
6891
6892 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6893 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6894 r_nonce)
6895 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6896 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6897
6898 logger.debug("Send M2 to STA")
6899 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6900 m1_attrs[ATTR_ENROLLEE_NONCE],
6901 r_nonce, uuid_r, None)
6902 send_wsc_msg(dev[0], bssid, m2)
6903 eap_id = (eap_id + 1) % 256
6904
6905 # Verify STA NACK's the credential
6906 msg = get_wsc_msg(dev[0])
6907 if msg['wsc_opcode'] != WSC_NACK:
6908 raise Exception("Unexpected message - expected WSC_Nack")
6909 dev[0].request("WPS_CANCEL")
6910 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6911 dev[0].wait_disconnected()
6912
6913def test_wps_ext_proto_m2_invalid_public_key(dev, apdev):
6914 """WPS and invalid Public Key in M2"""
6915 pin = "12345670"
6916 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6917 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6918 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6919 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6920
6921 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6922 uuid_r = 16*'\x33'
6923 r_nonce = 16*'\x44'
6924 own_private, e_pk = wsc_dh_init()
6925
6926 logger.debug("Receive M1 from STA")
6927 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6928 eap_id = (msg['eap_identifier'] + 1) % 256
6929
6930 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6931 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6932 r_nonce)
6933 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6934 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6935
6936 logger.debug("Send M2 to STA")
6937 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6938 m1_attrs[ATTR_ENROLLEE_NONCE],
6939 r_nonce, uuid_r, 192*'\xff')
6940 send_wsc_msg(dev[0], bssid, m2)
6941 eap_id = (eap_id + 1) % 256
6942
6943 # Verify STA NACK's the credential
6944 msg = get_wsc_msg(dev[0])
6945 if msg['wsc_opcode'] != WSC_NACK:
6946 raise Exception("Unexpected message - expected WSC_Nack")
6947 dev[0].request("WPS_CANCEL")
6948 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6949 dev[0].wait_disconnected()
6950
6951def test_wps_ext_proto_m2_public_key_oom(dev, apdev):
6952 """WPS and Public Key OOM in M2"""
6953 pin = "12345670"
6954 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6955 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6956 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6957 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6958
6959 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6960 uuid_r = 16*'\x33'
6961 r_nonce = 16*'\x44'
6962 own_private, e_pk = wsc_dh_init()
6963
6964 logger.debug("Receive M1 from STA")
6965 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6966 eap_id = (msg['eap_identifier'] + 1) % 256
6967
6968 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6969 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6970 r_nonce)
6971 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6972 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6973
6974 logger.debug("Send M2 to STA")
6975 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6976 m1_attrs[ATTR_ENROLLEE_NONCE],
6977 r_nonce, uuid_r, e_pk)
6978 with alloc_fail(dev[0], 1, "wpabuf_alloc_copy;wps_process_pubkey"):
6979 send_wsc_msg(dev[0], bssid, m2)
6980 eap_id = (eap_id + 1) % 256
6981
6982 # Verify STA NACK's the credential
6983 msg = get_wsc_msg(dev[0])
6984 if msg['wsc_opcode'] != WSC_NACK:
6985 raise Exception("Unexpected message - expected WSC_Nack")
6986 dev[0].request("WPS_CANCEL")
6987 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6988 dev[0].wait_disconnected()
6989
6990def test_wps_ext_proto_nack_m3(dev, apdev):
6991 """WPS and NACK M3"""
6992 pin = "12345670"
6993 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6994 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6995 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6996 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6997
6998 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6999 uuid_r = 16*'\x33'
7000 r_nonce = 16*'\x44'
7001 own_private, e_pk = wsc_dh_init()
7002
7003 logger.debug("Receive M1 from STA")
7004 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7005 eap_id = (msg['eap_identifier'] + 1) % 256
7006
7007 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7008 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7009 r_nonce)
7010 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7011 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7012
7013 logger.debug("Send M2 to STA")
7014 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7015 m1_attrs[ATTR_ENROLLEE_NONCE],
7016 r_nonce, uuid_r, e_pk)
7017 send_wsc_msg(dev[0], bssid, m2)
7018 eap_id = (eap_id + 1) % 256
7019
7020 logger.debug("Receive M3 from STA")
7021 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7022
7023 logger.debug("Send NACK to STA")
7024 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7025 r_nonce, config_error='\x01\x23')
7026 send_wsc_msg(dev[0], bssid, msg)
7027 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7028 if ev is None:
7029 raise Exception("Failure not reported")
7030 if "msg=7 config_error=291" not in ev:
7031 raise Exception("Unexpected failure reason: " + ev)
7032
7033def test_wps_ext_proto_nack_m5(dev, apdev):
7034 """WPS and NACK M5"""
7035 pin = "12345670"
7036 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7037 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7038 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7039 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7040
7041 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7042 uuid_r = 16*'\x33'
7043 r_nonce = 16*'\x44'
7044 own_private, e_pk = wsc_dh_init()
7045
7046 logger.debug("Receive M1 from STA")
7047 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7048 eap_id = (msg['eap_identifier'] + 1) % 256
7049
7050 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7051 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7052 r_nonce)
7053 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7054 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7055
7056 logger.debug("Send M2 to STA")
7057 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7058 m1_attrs[ATTR_ENROLLEE_NONCE],
7059 r_nonce, uuid_r, e_pk)
7060 send_wsc_msg(dev[0], bssid, m2)
7061 eap_id = (eap_id + 1) % 256
7062
7063 logger.debug("Receive M3 from STA")
7064 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7065
7066 logger.debug("Send M4 to STA")
7067 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7068 attrs += build_attr_msg_type(WPS_M4)
7069 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7070 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7071 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7072 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7073 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7074 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7075 raw_m4_attrs = attrs
7076 m4 = build_eap_wsc(1, eap_id, attrs)
7077 send_wsc_msg(dev[0], bssid, m4)
7078 eap_id = (eap_id + 1) % 256
7079
7080 logger.debug("Receive M5 from STA")
7081 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7082
7083 logger.debug("Send NACK to STA")
7084 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7085 r_nonce, config_error='\x01\x24')
7086 send_wsc_msg(dev[0], bssid, msg)
7087 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7088 if ev is None:
7089 raise Exception("Failure not reported")
7090 if "msg=9 config_error=292" not in ev:
7091 raise Exception("Unexpected failure reason: " + ev)
7092
7093def wps_nack_m3(dev, apdev):
7094 pin = "00000000"
7095 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
7096 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7097 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7098 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7099
7100 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7101 uuid_r = 16*'\x33'
7102 r_nonce = 16*'\x44'
7103 own_private, e_pk = wsc_dh_init()
7104
7105 logger.debug("Receive M1 from STA")
7106 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7107 eap_id = (msg['eap_identifier'] + 1) % 256
7108
7109 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7110 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7111 r_nonce)
7112 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7113 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7114
7115 logger.debug("Send M2 to STA")
7116 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7117 m1_attrs[ATTR_ENROLLEE_NONCE],
7118 r_nonce, uuid_r, e_pk, dev_pw_id='\x00\x04')
7119 send_wsc_msg(dev[0], bssid, m2)
7120 eap_id = (eap_id + 1) % 256
7121
7122 logger.debug("Receive M3 from STA")
7123 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7124 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid
7125
7126def test_wps_ext_proto_nack_m3_no_config_error(dev, apdev):
7127 """WPS and NACK M3 missing Config Error"""
7128 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7129 logger.debug("Send NACK to STA")
7130 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, config_error=None)
7131 send_wsc_msg(dev[0], bssid, msg)
7132 dev[0].request("WPS_CANCEL")
7133 dev[0].wait_disconnected()
7134 dev[0].flush_scan_cache()
7135
7136def test_wps_ext_proto_nack_m3_no_e_nonce(dev, apdev):
7137 """WPS and NACK M3 missing E-Nonce"""
7138 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7139 logger.debug("Send NACK to STA")
7140 msg, attrs = build_nack(eap_id, None, r_nonce)
7141 send_wsc_msg(dev[0], bssid, msg)
7142 dev[0].request("WPS_CANCEL")
7143 dev[0].wait_disconnected()
7144 dev[0].flush_scan_cache()
7145
7146def test_wps_ext_proto_nack_m3_e_nonce_mismatch(dev, apdev):
7147 """WPS and NACK M3 E-Nonce mismatch"""
7148 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7149 logger.debug("Send NACK to STA")
7150 msg, attrs = build_nack(eap_id, 16*'\x00', r_nonce)
7151 send_wsc_msg(dev[0], bssid, msg)
7152 dev[0].request("WPS_CANCEL")
7153 dev[0].wait_disconnected()
7154 dev[0].flush_scan_cache()
7155
7156def test_wps_ext_proto_nack_m3_no_r_nonce(dev, apdev):
7157 """WPS and NACK M3 missing R-Nonce"""
7158 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7159 logger.debug("Send NACK to STA")
7160 msg, attrs = build_nack(eap_id, e_nonce, None)
7161 send_wsc_msg(dev[0], bssid, msg)
7162 dev[0].request("WPS_CANCEL")
7163 dev[0].wait_disconnected()
7164 dev[0].flush_scan_cache()
7165
7166def test_wps_ext_proto_nack_m3_r_nonce_mismatch(dev, apdev):
7167 """WPS and NACK M3 R-Nonce mismatch"""
7168 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7169 logger.debug("Send NACK to STA")
7170 msg, attrs = build_nack(eap_id, e_nonce, 16*'\x00')
7171 send_wsc_msg(dev[0], bssid, msg)
7172 dev[0].request("WPS_CANCEL")
7173 dev[0].wait_disconnected()
7174 dev[0].flush_scan_cache()
7175
7176def test_wps_ext_proto_nack_m3_no_msg_type(dev, apdev):
7177 """WPS and NACK M3 no Message Type"""
7178 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7179 logger.debug("Send NACK to STA")
7180 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=None)
7181 send_wsc_msg(dev[0], bssid, msg)
7182 dev[0].request("WPS_CANCEL")
7183 dev[0].wait_disconnected()
7184 dev[0].flush_scan_cache()
7185
7186def test_wps_ext_proto_nack_m3_invalid_msg_type(dev, apdev):
7187 """WPS and NACK M3 invalid Message Type"""
7188 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7189 logger.debug("Send NACK to STA")
7190 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=123)
7191 send_wsc_msg(dev[0], bssid, msg)
7192 dev[0].request("WPS_CANCEL")
7193 dev[0].wait_disconnected()
7194 dev[0].flush_scan_cache()
7195
7196def test_wps_ext_proto_nack_m3_invalid_attr(dev, apdev):
7197 """WPS and NACK M3 invalid attribute"""
7198 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7199 logger.debug("Send NACK to STA")
7200 attrs = '\x10\x10\x00'
7201 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_NACK)
7202 send_wsc_msg(dev[0], bssid, msg)
7203 dev[0].request("WPS_CANCEL")
7204 dev[0].wait_disconnected()
7205 dev[0].flush_scan_cache()
7206
7207def test_wps_ext_proto_ack_m3_no_e_nonce(dev, apdev):
7208 """WPS and ACK M3 missing E-Nonce"""
7209 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7210 logger.debug("Send NACK to STA")
7211 msg, attrs = build_ack(eap_id, None, r_nonce)
7212 send_wsc_msg(dev[0], bssid, msg)
7213 dev[0].request("WPS_CANCEL")
7214 dev[0].wait_disconnected()
7215 dev[0].flush_scan_cache()
7216
7217def test_wps_ext_proto_ack_m3_e_nonce_mismatch(dev, apdev):
7218 """WPS and ACK M3 E-Nonce mismatch"""
7219 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7220 logger.debug("Send NACK to STA")
7221 msg, attrs = build_ack(eap_id, 16*'\x00', r_nonce)
7222 send_wsc_msg(dev[0], bssid, msg)
7223 dev[0].request("WPS_CANCEL")
7224 dev[0].wait_disconnected()
7225 dev[0].flush_scan_cache()
7226
7227def test_wps_ext_proto_ack_m3_no_r_nonce(dev, apdev):
7228 """WPS and ACK M3 missing R-Nonce"""
7229 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7230 logger.debug("Send NACK to STA")
7231 msg, attrs = build_ack(eap_id, e_nonce, None)
7232 send_wsc_msg(dev[0], bssid, msg)
7233 dev[0].request("WPS_CANCEL")
7234 dev[0].wait_disconnected()
7235 dev[0].flush_scan_cache()
7236
7237def test_wps_ext_proto_ack_m3_r_nonce_mismatch(dev, apdev):
7238 """WPS and ACK M3 R-Nonce mismatch"""
7239 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7240 logger.debug("Send NACK to STA")
7241 msg, attrs = build_ack(eap_id, e_nonce, 16*'\x00')
7242 send_wsc_msg(dev[0], bssid, msg)
7243 dev[0].request("WPS_CANCEL")
7244 dev[0].wait_disconnected()
7245 dev[0].flush_scan_cache()
7246
7247def test_wps_ext_proto_ack_m3_no_msg_type(dev, apdev):
7248 """WPS and ACK M3 no Message Type"""
7249 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7250 logger.debug("Send NACK to STA")
7251 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=None)
7252 send_wsc_msg(dev[0], bssid, msg)
7253 dev[0].request("WPS_CANCEL")
7254 dev[0].wait_disconnected()
7255 dev[0].flush_scan_cache()
7256
7257def test_wps_ext_proto_ack_m3_invalid_msg_type(dev, apdev):
7258 """WPS and ACK M3 invalid Message Type"""
7259 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7260 logger.debug("Send NACK to STA")
7261 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=123)
7262 send_wsc_msg(dev[0], bssid, msg)
7263 dev[0].request("WPS_CANCEL")
7264 dev[0].wait_disconnected()
7265 dev[0].flush_scan_cache()
7266
7267def test_wps_ext_proto_ack_m3_invalid_attr(dev, apdev):
7268 """WPS and ACK M3 invalid attribute"""
7269 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7270 logger.debug("Send ACK to STA")
7271 attrs = '\x10\x10\x00'
7272 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_ACK)
7273 send_wsc_msg(dev[0], bssid, msg)
7274 dev[0].request("WPS_CANCEL")
7275 dev[0].wait_disconnected()
7276 dev[0].flush_scan_cache()
7277
7278def test_wps_ext_proto_ack_m3(dev, apdev):
7279 """WPS and ACK M3"""
7280 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7281 logger.debug("Send ACK to STA")
7282 msg, attrs = build_ack(eap_id, e_nonce, r_nonce)
7283 send_wsc_msg(dev[0], bssid, msg)
7284 dev[0].request("WPS_CANCEL")
7285 dev[0].wait_disconnected()
7286 dev[0].flush_scan_cache()
7287
7288def wps_to_m3_helper(dev, apdev):
7289 pin = "12345670"
7290 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7291 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7292 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7293 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7294
7295 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7296 uuid_r = 16*'\x33'
7297 r_nonce = 16*'\x44'
7298 own_private, e_pk = wsc_dh_init()
7299
7300 logger.debug("Receive M1 from STA")
7301 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7302 eap_id = (msg['eap_identifier'] + 1) % 256
7303
7304 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7305 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7306 r_nonce)
7307 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7308 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7309
7310 logger.debug("Send M2 to STA")
7311 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7312 m1_attrs[ATTR_ENROLLEE_NONCE],
7313 r_nonce, uuid_r, e_pk)
7314 send_wsc_msg(dev[0], bssid, m2)
7315 eap_id = (eap_id + 1) % 256
7316
7317 logger.debug("Receive M3 from STA")
7318 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7319 return eap_id, m1_attrs, r_nonce, bssid, r_hash1, r_hash2, r_s1, r_s2, raw_m3_attrs, authkey, keywrapkey
7320
7321def wps_to_m3(dev, apdev):
7322 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)
7323 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s1, raw_m3_attrs, authkey, keywrapkey
7324
7325def wps_to_m5(dev, apdev):
7326 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)
7327
7328 logger.debug("Send M4 to STA")
7329 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7330 attrs += build_attr_msg_type(WPS_M4)
7331 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7332 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7333 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7334 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7335 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7336 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7337 raw_m4_attrs = attrs
7338 m4 = build_eap_wsc(1, eap_id, attrs)
7339 send_wsc_msg(dev[0], bssid, m4)
7340 eap_id = (eap_id + 1) % 256
7341
7342 logger.debug("Receive M5 from STA")
7343 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7344
7345 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s2, raw_m5_attrs, authkey, keywrapkey
7346
7347def test_wps_ext_proto_m4_missing_r_hash1(dev, apdev):
7348 """WPS and no R-Hash1 in M4"""
7349 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7350
7351 logger.debug("Send M4 to STA")
7352 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7353 attrs += build_attr_msg_type(WPS_M4)
7354 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7355 #attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7356 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7357 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7358 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7359 attrs += build_attr_authenticator(authkey, m3, attrs)
7360 m4 = build_eap_wsc(1, eap_id, attrs)
7361 send_wsc_msg(dev[0], bssid, m4)
7362 eap_id = (eap_id + 1) % 256
7363
7364 logger.debug("Receive M5 (NACK) from STA")
7365 msg = get_wsc_msg(dev[0])
7366 if msg['wsc_opcode'] != WSC_NACK:
7367 raise Exception("Unexpected message - expected WSC_Nack")
7368
7369 dev[0].request("WPS_CANCEL")
7370 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7371 dev[0].wait_disconnected()
7372
7373def test_wps_ext_proto_m4_missing_r_hash2(dev, apdev):
7374 """WPS and no R-Hash2 in M4"""
7375 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7376
7377 logger.debug("Send M4 to STA")
7378 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7379 attrs += build_attr_msg_type(WPS_M4)
7380 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7381 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7382 #attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7383 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
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_missing_r_snonce1(dev, apdev):
7400 """WPS and no R-SNonce1 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 data = ''
7411 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7412 attrs += build_attr_authenticator(authkey, m3, attrs)
7413 m4 = build_eap_wsc(1, eap_id, attrs)
7414 send_wsc_msg(dev[0], bssid, m4)
7415 eap_id = (eap_id + 1) % 256
7416
7417 logger.debug("Receive M5 (NACK) from STA")
7418 msg = get_wsc_msg(dev[0])
7419 if msg['wsc_opcode'] != WSC_NACK:
7420 raise Exception("Unexpected message - expected WSC_Nack")
7421
7422 dev[0].request("WPS_CANCEL")
7423 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7424 dev[0].wait_disconnected()
7425
7426def test_wps_ext_proto_m4_invalid_pad_string(dev, apdev):
7427 """WPS and invalid pad string in M4"""
7428 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7429
7430 logger.debug("Send M4 to STA")
7431 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7432 attrs += build_attr_msg_type(WPS_M4)
7433 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7434 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7435 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7436 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7437
7438 m = hmac.new(authkey, data, hashlib.sha256)
7439 kwa = m.digest()[0:8]
7440 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7441 iv = 16*'\x99'
7442 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7443 pad_len = 16 - len(data) % 16
7444 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', pad_len - 1)
7445 data += ps
7446 wrapped = aes.encrypt(data)
7447 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7448
7449 attrs += build_attr_authenticator(authkey, m3, attrs)
7450 m4 = build_eap_wsc(1, eap_id, attrs)
7451 send_wsc_msg(dev[0], bssid, m4)
7452 eap_id = (eap_id + 1) % 256
7453
7454 logger.debug("Receive M5 (NACK) from STA")
7455 msg = get_wsc_msg(dev[0])
7456 if msg['wsc_opcode'] != WSC_NACK:
7457 raise Exception("Unexpected message - expected WSC_Nack")
7458
7459 dev[0].request("WPS_CANCEL")
7460 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7461 dev[0].wait_disconnected()
7462
7463def test_wps_ext_proto_m4_invalid_pad_value(dev, apdev):
7464 """WPS and invalid pad value in M4"""
7465 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7466
7467 logger.debug("Send M4 to STA")
7468 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7469 attrs += build_attr_msg_type(WPS_M4)
7470 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7471 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7472 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7473 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7474
7475 m = hmac.new(authkey, data, hashlib.sha256)
7476 kwa = m.digest()[0:8]
7477 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7478 iv = 16*'\x99'
7479 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7480 pad_len = 16 - len(data) % 16
7481 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', 255)
7482 data += ps
7483 wrapped = aes.encrypt(data)
7484 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7485
7486 attrs += build_attr_authenticator(authkey, m3, attrs)
7487 m4 = build_eap_wsc(1, eap_id, attrs)
7488 send_wsc_msg(dev[0], bssid, m4)
7489 eap_id = (eap_id + 1) % 256
7490
7491 logger.debug("Receive M5 (NACK) from STA")
7492 msg = get_wsc_msg(dev[0])
7493 if msg['wsc_opcode'] != WSC_NACK:
7494 raise Exception("Unexpected message - expected WSC_Nack")
7495
7496 dev[0].request("WPS_CANCEL")
7497 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7498 dev[0].wait_disconnected()
7499
7500def test_wps_ext_proto_m4_no_encr_settings(dev, apdev):
7501 """WPS and no Encr Settings in M4"""
7502 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7503
7504 logger.debug("Send M4 to STA")
7505 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7506 attrs += build_attr_msg_type(WPS_M4)
7507 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7508 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7509 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7510 attrs += build_attr_authenticator(authkey, m3, attrs)
7511 m4 = build_eap_wsc(1, eap_id, attrs)
7512 send_wsc_msg(dev[0], bssid, m4)
7513 eap_id = (eap_id + 1) % 256
7514
7515 logger.debug("Receive M5 (NACK) from STA")
7516 msg = get_wsc_msg(dev[0])
7517 if msg['wsc_opcode'] != WSC_NACK:
7518 raise Exception("Unexpected message - expected WSC_Nack")
7519
7520 dev[0].request("WPS_CANCEL")
7521 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7522 dev[0].wait_disconnected()
7523
7524def test_wps_ext_proto_m6_missing_r_snonce2(dev, apdev):
7525 """WPS and no R-SNonce2 in M6"""
7526 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7527
7528 logger.debug("Send M6 to STA")
7529 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7530 attrs += build_attr_msg_type(WPS_M6)
7531 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7532 #data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7533 data = ''
7534 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7535 attrs += build_attr_authenticator(authkey, m5, attrs)
7536 m6 = build_eap_wsc(1, eap_id, attrs)
7537 send_wsc_msg(dev[0], bssid, m6)
7538 eap_id = (eap_id + 1) % 256
7539
7540 logger.debug("Receive M7 (NACK) from STA")
7541 msg = get_wsc_msg(dev[0])
7542 if msg['wsc_opcode'] != WSC_NACK:
7543 raise Exception("Unexpected message - expected WSC_Nack")
7544
7545 dev[0].request("WPS_CANCEL")
7546 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7547 dev[0].wait_disconnected()
7548
7549def test_wps_ext_proto_m6_no_encr_settings(dev, apdev):
7550 """WPS and no Encr Settings in M6"""
7551 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7552
7553 logger.debug("Send M6 to STA")
7554 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7555 attrs += build_attr_msg_type(WPS_M6)
7556 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7557 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7558 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7559 attrs += build_attr_authenticator(authkey, m5, attrs)
7560 m6 = build_eap_wsc(1, eap_id, attrs)
7561 send_wsc_msg(dev[0], bssid, m6)
7562 eap_id = (eap_id + 1) % 256
7563
7564 logger.debug("Receive M7 (NACK) from STA")
7565 msg = get_wsc_msg(dev[0])
7566 if msg['wsc_opcode'] != WSC_NACK:
7567 raise Exception("Unexpected message - expected WSC_Nack")
7568
7569 dev[0].request("WPS_CANCEL")
7570 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7571 dev[0].wait_disconnected()
7572
7573def test_wps_ext_proto_m8_no_encr_settings(dev, apdev):
7574 """WPS and no Encr Settings in M6"""
7575 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7576
7577 logger.debug("Send M6 to STA")
7578 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7579 attrs += build_attr_msg_type(WPS_M6)
7580 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7581 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7582 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7583 attrs += build_attr_authenticator(authkey, m5, attrs)
7584 raw_m6_attrs = attrs
7585 m6 = build_eap_wsc(1, eap_id, attrs)
7586 send_wsc_msg(dev[0], bssid, m6)
7587 eap_id = (eap_id + 1) % 256
7588
7589 logger.debug("Receive M7 from STA")
7590 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
7591
7592 logger.debug("Send M8 to STA")
7593 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7594 attrs += build_attr_msg_type(WPS_M8)
7595 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7596 #attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
7597 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7598 raw_m8_attrs = attrs
7599 m8 = build_eap_wsc(1, eap_id, attrs)
7600 send_wsc_msg(dev[0], bssid, m8)
7601
7602 logger.debug("Receive WSC_Done (NACK) from STA")
7603 msg = get_wsc_msg(dev[0])
7604 if msg['wsc_opcode'] != WSC_NACK:
7605 raise Exception("Unexpected message - expected WSC_Nack")
7606
7607 dev[0].request("WPS_CANCEL")
7608 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7609 dev[0].wait_disconnected()
7610
7611def wps_start_ext_reg(apdev, dev):
7612 addr = dev.own_addr()
7613 bssid = apdev['bssid']
7614 ssid = "test-wps-conf"
7615 appin = "12345670"
7616 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
7617 "wpa_passphrase": "12345678", "wpa": "2",
7618 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
7619 "ap_pin": appin }
afc26df2 7620 hapd = hostapd.add_ap(apdev, params)
7511ead0
JM
7621
7622 dev.scan_for_bss(bssid, freq="2412")
7623 hapd.request("SET ext_eapol_frame_io 1")
7624 dev.request("SET ext_eapol_frame_io 1")
7625
7626 dev.request("WPS_REG " + bssid + " " + appin)
7627
7628 return addr,bssid,hapd
7629
7630def wps_run_ap_settings_proto(dev, apdev, ap_settings, success):
7631 addr,bssid,hapd = wps_start_ext_reg(apdev[0], dev[0])
7632 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7633 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7634
7635 logger.debug("Receive M1 from AP")
7636 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7637 mac_addr = m1_attrs[ATTR_MAC_ADDR]
7638 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7639 e_pk = m1_attrs[ATTR_PUBLIC_KEY]
7640
7641 appin = '12345670'
7642 uuid_r = 16*'\x33'
7643 r_nonce = 16*'\x44'
7644 own_private, r_pk = wsc_dh_init()
7645 authkey,keywrapkey = wsc_dh_kdf(e_pk, own_private, mac_addr, e_nonce,
7646 r_nonce)
7647 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, appin, e_pk, r_pk)
7648
7649 logger.debug("Send M2 to AP")
7650 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, msg['eap_identifier'],
7651 e_nonce, r_nonce, uuid_r, r_pk, eap_code=2)
7652 send_wsc_msg(hapd, addr, m2)
7653
7654 logger.debug("Receive M3 from AP")
7655 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M3)
7656
7657 logger.debug("Send M4 to AP")
7658 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7659 attrs += build_attr_msg_type(WPS_M4)
7660 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7661 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7662 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7663 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7664 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7665 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7666 raw_m4_attrs = attrs
7667 m4 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7668 send_wsc_msg(hapd, addr, m4)
7669
7670 logger.debug("Receive M5 from AP")
7671 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M5)
7672
7673 logger.debug("Send M6 to STA")
7674 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7675 attrs += build_attr_msg_type(WPS_M6)
7676 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7677 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7678 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7679 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
7680 raw_m6_attrs = attrs
7681 m6 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7682 send_wsc_msg(hapd, addr, m6)
7683
7684 logger.debug("Receive M7 from AP")
7685 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M7)
7686
7687 logger.debug("Send M8 to STA")
7688 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7689 attrs += build_attr_msg_type(WPS_M8)
7690 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7691 if ap_settings:
7692 attrs += build_attr_encr_settings(authkey, keywrapkey, ap_settings)
7693 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7694 raw_m8_attrs = attrs
7695 m8 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7696 send_wsc_msg(hapd, addr, m8)
7697
7698 if success:
7699 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
7700 if ev is None:
7701 raise Exception("New AP settings not reported")
7702 logger.debug("Receive WSC_Done from AP")
7703 msg = get_wsc_msg(hapd)
7704 if msg['wsc_opcode'] != WSC_Done:
7705 raise Exception("Unexpected message - expected WSC_Done")
7706
7707 logger.debug("Send WSC_ACK to AP")
7708 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
7709 eap_code=2)
7710 send_wsc_msg(hapd, addr, ack)
7711 dev[0].wait_disconnected()
7712 else:
7713 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
7714 if ev is None:
7715 raise Exception("WPS failure not reported")
7716 logger.debug("Receive WSC_NACK from AP")
7717 msg = get_wsc_msg(hapd)
7718 if msg['wsc_opcode'] != WSC_NACK:
7719 raise Exception("Unexpected message - expected WSC_NACK")
7720
7721 logger.debug("Send WSC_NACK to AP")
7722 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7723 eap_code=2)
7724 send_wsc_msg(hapd, addr, nack)
7725 dev[0].wait_disconnected()
7726
7727def test_wps_ext_ap_settings_success(dev, apdev):
7728 """WPS and AP Settings: success"""
7729 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7730 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7731 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7732 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7733 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7734 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7735 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7736
7737def test_wps_ext_ap_settings_missing(dev, apdev):
7738 """WPS and AP Settings: missing"""
7739 wps_run_ap_settings_proto(dev, apdev, None, False)
7740
7741def test_wps_ext_ap_settings_mac_addr_mismatch(dev, apdev):
7742 """WPS and AP Settings: MAC Address mismatch"""
7743 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7744 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7745 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7746 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7747 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7748 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, '\x00\x00\x00\x00\x00\x00')
7749 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7750
7751def test_wps_ext_ap_settings_mac_addr_missing(dev, apdev):
7752 """WPS and AP Settings: missing MAC Address"""
7753 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7754 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7755 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7756 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7757 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7758 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7759
7760def test_wps_ext_ap_settings_reject_encr_type(dev, apdev):
7761 """WPS and AP Settings: reject Encr Type"""
7762 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7763 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7764 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7765 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x00')
7766 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7767 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7768 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7769
7770def test_wps_ext_ap_settings_m2d(dev, apdev):
7771 """WPS and AP Settings: M2D"""
7772 addr,bssid,hapd = wps_start_ext_reg(apdev[0], dev[0])
7773 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7774 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7775
7776 logger.debug("Receive M1 from AP")
7777 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7778 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7779
7780 r_nonce = 16*'\x44'
7781 uuid_r = 16*'\x33'
7782
7783 logger.debug("Send M2D to AP")
7784 m2d, raw_m2d_attrs = build_m2d(raw_m1_attrs, msg['eap_identifier'],
7785 e_nonce, r_nonce, uuid_r,
7786 dev_pw_id='\x00\x00', eap_code=2)
7787 send_wsc_msg(hapd, addr, m2d)
7788
7789 ev = hapd.wait_event(["WPS-M2D"], timeout=5)
7790 if ev is None:
7791 raise Exception("M2D not reported")
7792
7793 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7794
7795def wps_wait_ap_nack(hapd, dev, e_nonce, r_nonce):
7796 logger.debug("Receive WSC_NACK from AP")
7797 msg = get_wsc_msg(hapd)
7798 if msg['wsc_opcode'] != WSC_NACK:
7799 raise Exception("Unexpected message - expected WSC_NACK")
7800
7801 logger.debug("Send WSC_NACK to AP")
7802 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7803 eap_code=2)
7804 send_wsc_msg(hapd, dev.own_addr(), nack)
7805 dev.wait_disconnected()
7806
7807def test_wps_ext_m3_missing_e_hash1(dev, apdev):
7808 """WPS proto: M3 missing E-Hash1"""
7809 pin = "12345670"
7810 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7811 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7812 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7813
7814 logger.debug("Receive WSC/Start from AP")
7815 msg = get_wsc_msg(hapd)
7816 if msg['wsc_opcode'] != WSC_Start:
7817 raise Exception("Unexpected Op-Code for WSC/Start")
7818
7819 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7820 uuid_e = 16*'\x11'
7821 e_nonce = 16*'\x22'
7822 own_private, e_pk = wsc_dh_init()
7823
7824 logger.debug("Send M1 to AP")
7825 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7826 e_nonce, e_pk)
7827 send_wsc_msg(hapd, addr, m1)
7828
7829 logger.debug("Receive M2 from AP")
7830 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7831 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7832 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7833
7834 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7835 r_nonce)
7836 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7837
7838 logger.debug("Send M3 to AP")
7839 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7840 attrs += build_attr_msg_type(WPS_M3)
7841 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7842 #attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7843 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7844 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7845 raw_m3_attrs = attrs
7846 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7847 send_wsc_msg(hapd, addr, m3)
7848
7849 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7850
7851def test_wps_ext_m3_missing_e_hash2(dev, apdev):
7852 """WPS proto: M3 missing E-Hash2"""
7853 pin = "12345670"
7854 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7855 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7856 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7857
7858 logger.debug("Receive WSC/Start from AP")
7859 msg = get_wsc_msg(hapd)
7860 if msg['wsc_opcode'] != WSC_Start:
7861 raise Exception("Unexpected Op-Code for WSC/Start")
7862
7863 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7864 uuid_e = 16*'\x11'
7865 e_nonce = 16*'\x22'
7866 own_private, e_pk = wsc_dh_init()
7867
7868 logger.debug("Send M1 to AP")
7869 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7870 e_nonce, e_pk)
7871 send_wsc_msg(hapd, addr, m1)
7872
7873 logger.debug("Receive M2 from AP")
7874 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7875 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7876 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7877
7878 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7879 r_nonce)
7880 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7881
7882 logger.debug("Send M3 to AP")
7883 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7884 attrs += build_attr_msg_type(WPS_M3)
7885 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7886 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7887 #attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7888 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7889 raw_m3_attrs = attrs
7890 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7891 send_wsc_msg(hapd, addr, m3)
7892
7893 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7894
7895def test_wps_ext_m5_missing_e_snonce1(dev, apdev):
7896 """WPS proto: M5 missing E-SNonce1"""
7897 pin = "12345670"
7898 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7899 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7900 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7901
7902 logger.debug("Receive WSC/Start from AP")
7903 msg = get_wsc_msg(hapd)
7904 if msg['wsc_opcode'] != WSC_Start:
7905 raise Exception("Unexpected Op-Code for WSC/Start")
7906
7907 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7908 uuid_e = 16*'\x11'
7909 e_nonce = 16*'\x22'
7910 own_private, e_pk = wsc_dh_init()
7911
7912 logger.debug("Send M1 to AP")
7913 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7914 e_nonce, e_pk)
7915 send_wsc_msg(hapd, addr, m1)
7916
7917 logger.debug("Receive M2 from AP")
7918 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7919 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7920 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7921
7922 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7923 r_nonce)
7924 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7925
7926 logger.debug("Send M3 to AP")
7927 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7928 attrs += build_attr_msg_type(WPS_M3)
7929 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7930 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7931 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7932 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7933 raw_m3_attrs = attrs
7934 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7935 send_wsc_msg(hapd, addr, m3)
7936
7937 logger.debug("Receive M4 from AP")
7938 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
7939
7940 logger.debug("Send M5 to AP")
7941 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7942 attrs += build_attr_msg_type(WPS_M5)
7943 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7944 #data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
7945 data = ''
7946 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7947 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
7948 raw_m5_attrs = attrs
7949 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7950 send_wsc_msg(hapd, addr, m5)
7951
7952 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7953
7954def test_wps_ext_m5_e_snonce1_mismatch(dev, apdev):
7955 """WPS proto: M5 E-SNonce1 mismatch"""
7956 pin = "12345670"
7957 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7958 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7959 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7960
7961 logger.debug("Receive WSC/Start from AP")
7962 msg = get_wsc_msg(hapd)
7963 if msg['wsc_opcode'] != WSC_Start:
7964 raise Exception("Unexpected Op-Code for WSC/Start")
7965
7966 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7967 uuid_e = 16*'\x11'
7968 e_nonce = 16*'\x22'
7969 own_private, e_pk = wsc_dh_init()
7970
7971 logger.debug("Send M1 to AP")
7972 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7973 e_nonce, e_pk)
7974 send_wsc_msg(hapd, addr, m1)
7975
7976 logger.debug("Receive M2 from AP")
7977 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7978 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7979 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7980
7981 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7982 r_nonce)
7983 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7984
7985 logger.debug("Send M3 to AP")
7986 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7987 attrs += build_attr_msg_type(WPS_M3)
7988 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7989 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7990 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7991 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7992 raw_m3_attrs = attrs
7993 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7994 send_wsc_msg(hapd, addr, m3)
7995
7996 logger.debug("Receive M4 from AP")
7997 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
7998
7999 logger.debug("Send M5 to AP")
8000 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8001 attrs += build_attr_msg_type(WPS_M5)
8002 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8003 data = build_wsc_attr(ATTR_E_SNONCE1, 16*'\x00')
8004 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8005 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8006 raw_m5_attrs = attrs
8007 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8008 send_wsc_msg(hapd, addr, m5)
8009
8010 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8011
8012def test_wps_ext_m7_missing_e_snonce2(dev, apdev):
8013 """WPS proto: M7 missing E-SNonce2"""
8014 pin = "12345670"
8015 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8016 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8017 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8018
8019 logger.debug("Receive WSC/Start from AP")
8020 msg = get_wsc_msg(hapd)
8021 if msg['wsc_opcode'] != WSC_Start:
8022 raise Exception("Unexpected Op-Code for WSC/Start")
8023
8024 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8025 uuid_e = 16*'\x11'
8026 e_nonce = 16*'\x22'
8027 own_private, e_pk = wsc_dh_init()
8028
8029 logger.debug("Send M1 to AP")
8030 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8031 e_nonce, e_pk)
8032 send_wsc_msg(hapd, addr, m1)
8033
8034 logger.debug("Receive M2 from AP")
8035 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8036 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8037 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8038
8039 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8040 r_nonce)
8041 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8042
8043 logger.debug("Send M3 to AP")
8044 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8045 attrs += build_attr_msg_type(WPS_M3)
8046 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8047 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8048 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8049 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8050 raw_m3_attrs = attrs
8051 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8052 send_wsc_msg(hapd, addr, m3)
8053
8054 logger.debug("Receive M4 from AP")
8055 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8056
8057 logger.debug("Send M5 to AP")
8058 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8059 attrs += build_attr_msg_type(WPS_M5)
8060 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8061 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8062 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8063 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8064 raw_m5_attrs = attrs
8065 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8066 send_wsc_msg(hapd, addr, m5)
8067
8068 logger.debug("Receive M6 from AP")
8069 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8070
8071 logger.debug("Send M7 to AP")
8072 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8073 attrs += build_attr_msg_type(WPS_M7)
8074 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8075 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
8076 data = ''
8077 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8078 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8079 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8080 raw_m7_attrs = attrs
8081 send_wsc_msg(hapd, addr, m7)
8082
8083 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8084
8085def test_wps_ext_m7_e_snonce2_mismatch(dev, apdev):
8086 """WPS proto: M7 E-SNonce2 mismatch"""
8087 pin = "12345670"
8088 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8089 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8090 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8091
8092 logger.debug("Receive WSC/Start from AP")
8093 msg = get_wsc_msg(hapd)
8094 if msg['wsc_opcode'] != WSC_Start:
8095 raise Exception("Unexpected Op-Code for WSC/Start")
8096
8097 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8098 uuid_e = 16*'\x11'
8099 e_nonce = 16*'\x22'
8100 own_private, e_pk = wsc_dh_init()
8101
8102 logger.debug("Send M1 to AP")
8103 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8104 e_nonce, e_pk)
8105 send_wsc_msg(hapd, addr, m1)
8106
8107 logger.debug("Receive M2 from AP")
8108 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8109 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8110 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8111
8112 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8113 r_nonce)
8114 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8115
8116 logger.debug("Send M3 to AP")
8117 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8118 attrs += build_attr_msg_type(WPS_M3)
8119 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8120 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8121 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8122 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8123 raw_m3_attrs = attrs
8124 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8125 send_wsc_msg(hapd, addr, m3)
8126
8127 logger.debug("Receive M4 from AP")
8128 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8129
8130 logger.debug("Send M5 to AP")
8131 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8132 attrs += build_attr_msg_type(WPS_M5)
8133 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8134 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8135 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8136 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8137 raw_m5_attrs = attrs
8138 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8139 send_wsc_msg(hapd, addr, m5)
8140
8141 logger.debug("Receive M6 from AP")
8142 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8143
8144 logger.debug("Send M7 to AP")
8145 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8146 attrs += build_attr_msg_type(WPS_M7)
8147 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8148 data = build_wsc_attr(ATTR_E_SNONCE2, 16*'\x00')
8149 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8150 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8151 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8152 raw_m7_attrs = attrs
8153 send_wsc_msg(hapd, addr, m7)
8154
8155 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8156
8157def test_wps_ext_m1_pubkey_oom(dev, apdev):
8158 """WPS proto: M1 PubKey OOM"""
8159 pin = "12345670"
8160 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8161 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8162 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8163
8164 logger.debug("Receive WSC/Start from AP")
8165 msg = get_wsc_msg(hapd)
8166 if msg['wsc_opcode'] != WSC_Start:
8167 raise Exception("Unexpected Op-Code for WSC/Start")
8168
8169 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8170 uuid_e = 16*'\x11'
8171 e_nonce = 16*'\x22'
8172 own_private, e_pk = wsc_dh_init()
8173
8174 logger.debug("Send M1 to AP")
8175 with alloc_fail(hapd, 1, "wpabuf_alloc_copy;wps_process_pubkey"):
8176 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8177 e_nonce, e_pk)
8178 send_wsc_msg(hapd, addr, m1)
8179 wps_wait_eap_failure(hapd, dev[0])
8180
8181def wps_wait_eap_failure(hapd, dev):
8182 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
8183 if ev is None:
8184 raise Exception("EAP-Failure not reported")
8185 dev.wait_disconnected()
8186
8187def test_wps_ext_m3_m1(dev, apdev):
8188 """WPS proto: M3 replaced with M1"""
8189 pin = "12345670"
8190 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8191 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8192 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8193
8194 logger.debug("Receive WSC/Start from AP")
8195 msg = get_wsc_msg(hapd)
8196 if msg['wsc_opcode'] != WSC_Start:
8197 raise Exception("Unexpected Op-Code for WSC/Start")
8198
8199 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8200 uuid_e = 16*'\x11'
8201 e_nonce = 16*'\x22'
8202 own_private, e_pk = wsc_dh_init()
8203
8204 logger.debug("Send M1 to AP")
8205 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8206 e_nonce, e_pk)
8207 send_wsc_msg(hapd, addr, m1)
8208
8209 logger.debug("Receive M2 from AP")
8210 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8211 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8212 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8213
8214 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8215 r_nonce)
8216 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8217
8218 logger.debug("Send M3(M1) to AP")
8219 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8220 attrs += build_attr_msg_type(WPS_M1)
8221 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8222 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8223 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8224 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8225 raw_m3_attrs = attrs
8226 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8227 send_wsc_msg(hapd, addr, m3)
8228
8229 wps_wait_eap_failure(hapd, dev[0])
8230
8231def test_wps_ext_m5_m3(dev, apdev):
8232 """WPS proto: M5 replaced with M3"""
8233 pin = "12345670"
8234 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8235 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8236 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8237
8238 logger.debug("Receive WSC/Start from AP")
8239 msg = get_wsc_msg(hapd)
8240 if msg['wsc_opcode'] != WSC_Start:
8241 raise Exception("Unexpected Op-Code for WSC/Start")
8242
8243 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8244 uuid_e = 16*'\x11'
8245 e_nonce = 16*'\x22'
8246 own_private, e_pk = wsc_dh_init()
8247
8248 logger.debug("Send M1 to AP")
8249 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8250 e_nonce, e_pk)
8251 send_wsc_msg(hapd, addr, m1)
8252
8253 logger.debug("Receive M2 from AP")
8254 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8255 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8256 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8257
8258 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8259 r_nonce)
8260 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8261
8262 logger.debug("Send M3 to AP")
8263 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8264 attrs += build_attr_msg_type(WPS_M3)
8265 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8266 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8267 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8268 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8269 raw_m3_attrs = attrs
8270 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8271 send_wsc_msg(hapd, addr, m3)
8272
8273 logger.debug("Receive M4 from AP")
8274 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8275
8276 logger.debug("Send M5(M3) to AP")
8277 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8278 attrs += build_attr_msg_type(WPS_M3)
8279 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8280 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8281 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8282 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8283 raw_m5_attrs = attrs
8284 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8285 send_wsc_msg(hapd, addr, m5)
8286
8287 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8288
8289def test_wps_ext_m3_m2(dev, apdev):
8290 """WPS proto: M3 replaced with M2"""
8291 pin = "12345670"
8292 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8293 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8294 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8295
8296 logger.debug("Receive WSC/Start from AP")
8297 msg = get_wsc_msg(hapd)
8298 if msg['wsc_opcode'] != WSC_Start:
8299 raise Exception("Unexpected Op-Code for WSC/Start")
8300
8301 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8302 uuid_e = 16*'\x11'
8303 e_nonce = 16*'\x22'
8304 own_private, e_pk = wsc_dh_init()
8305
8306 logger.debug("Send M1 to AP")
8307 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8308 e_nonce, e_pk)
8309 send_wsc_msg(hapd, addr, m1)
8310
8311 logger.debug("Receive M2 from AP")
8312 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8313 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8314 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8315
8316 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8317 r_nonce)
8318 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8319
8320 logger.debug("Send M3(M2) to AP")
8321 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8322 attrs += build_attr_msg_type(WPS_M2)
8323 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8324 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8325 raw_m3_attrs = attrs
8326 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8327 send_wsc_msg(hapd, addr, m3)
8328
8329 wps_wait_eap_failure(hapd, dev[0])
8330
8331def test_wps_ext_m3_m5(dev, apdev):
8332 """WPS proto: M3 replaced with M5"""
8333 pin = "12345670"
8334 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8335 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8336 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8337
8338 logger.debug("Receive WSC/Start from AP")
8339 msg = get_wsc_msg(hapd)
8340 if msg['wsc_opcode'] != WSC_Start:
8341 raise Exception("Unexpected Op-Code for WSC/Start")
8342
8343 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8344 uuid_e = 16*'\x11'
8345 e_nonce = 16*'\x22'
8346 own_private, e_pk = wsc_dh_init()
8347
8348 logger.debug("Send M1 to AP")
8349 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8350 e_nonce, e_pk)
8351 send_wsc_msg(hapd, addr, m1)
8352
8353 logger.debug("Receive M2 from AP")
8354 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8355 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8356 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8357
8358 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8359 r_nonce)
8360 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8361
8362 logger.debug("Send M3(M5) to AP")
8363 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8364 attrs += build_attr_msg_type(WPS_M5)
8365 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8366 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8367 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8368 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8369 raw_m3_attrs = attrs
8370 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8371 send_wsc_msg(hapd, addr, m3)
8372
8373 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8374
8375def test_wps_ext_m3_m7(dev, apdev):
8376 """WPS proto: M3 replaced with M7"""
8377 pin = "12345670"
8378 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8379 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8380 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8381
8382 logger.debug("Receive WSC/Start from AP")
8383 msg = get_wsc_msg(hapd)
8384 if msg['wsc_opcode'] != WSC_Start:
8385 raise Exception("Unexpected Op-Code for WSC/Start")
8386
8387 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8388 uuid_e = 16*'\x11'
8389 e_nonce = 16*'\x22'
8390 own_private, e_pk = wsc_dh_init()
8391
8392 logger.debug("Send M1 to AP")
8393 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8394 e_nonce, e_pk)
8395 send_wsc_msg(hapd, addr, m1)
8396
8397 logger.debug("Receive M2 from AP")
8398 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8399 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8400 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8401
8402 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8403 r_nonce)
8404 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8405
8406 logger.debug("Send M3(M7) to AP")
8407 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8408 attrs += build_attr_msg_type(WPS_M7)
8409 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8410 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8411 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8412 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8413 raw_m3_attrs = attrs
8414 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8415 send_wsc_msg(hapd, addr, m3)
8416
8417 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8418
8419def test_wps_ext_m3_done(dev, apdev):
8420 """WPS proto: M3 replaced with WSC_Done"""
8421 pin = "12345670"
8422 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8423 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8424 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8425
8426 logger.debug("Receive WSC/Start from AP")
8427 msg = get_wsc_msg(hapd)
8428 if msg['wsc_opcode'] != WSC_Start:
8429 raise Exception("Unexpected Op-Code for WSC/Start")
8430
8431 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8432 uuid_e = 16*'\x11'
8433 e_nonce = 16*'\x22'
8434 own_private, e_pk = wsc_dh_init()
8435
8436 logger.debug("Send M1 to AP")
8437 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8438 e_nonce, e_pk)
8439 send_wsc_msg(hapd, addr, m1)
8440
8441 logger.debug("Receive M2 from AP")
8442 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8443 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8444 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8445
8446 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8447 r_nonce)
8448 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8449
8450 logger.debug("Send M3(WSC_Done) to AP")
8451 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8452 attrs += build_attr_msg_type(WPS_WSC_DONE)
8453 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8454 raw_m3_attrs = attrs
8455 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8456 send_wsc_msg(hapd, addr, m3)
8457
8458 wps_wait_eap_failure(hapd, dev[0])
8459
8460def test_wps_ext_m2_nack_invalid(dev, apdev):
8461 """WPS proto: M2 followed by invalid NACK"""
8462 pin = "12345670"
8463 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8464 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8465 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8466
8467 logger.debug("Receive WSC/Start from AP")
8468 msg = get_wsc_msg(hapd)
8469 if msg['wsc_opcode'] != WSC_Start:
8470 raise Exception("Unexpected Op-Code for WSC/Start")
8471
8472 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8473 uuid_e = 16*'\x11'
8474 e_nonce = 16*'\x22'
8475 own_private, e_pk = wsc_dh_init()
8476
8477 logger.debug("Send M1 to AP")
8478 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8479 e_nonce, e_pk)
8480 send_wsc_msg(hapd, addr, m1)
8481
8482 logger.debug("Receive M2 from AP")
8483 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8484 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8485 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8486
8487 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8488 r_nonce)
8489 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8490
8491 logger.debug("Send WSC_NACK to AP")
8492 attrs = '\x10\x00\x00'
8493 nack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_NACK)
8494 send_wsc_msg(hapd, addr, nack)
8495
8496 wps_wait_eap_failure(hapd, dev[0])
8497
8498def test_wps_ext_m2_nack_no_msg_type(dev, apdev):
8499 """WPS proto: M2 followed by NACK without Msg Type"""
8500 pin = "12345670"
8501 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8502 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8503 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8504
8505 logger.debug("Receive WSC/Start from AP")
8506 msg = get_wsc_msg(hapd)
8507 if msg['wsc_opcode'] != WSC_Start:
8508 raise Exception("Unexpected Op-Code for WSC/Start")
8509
8510 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8511 uuid_e = 16*'\x11'
8512 e_nonce = 16*'\x22'
8513 own_private, e_pk = wsc_dh_init()
8514
8515 logger.debug("Send M1 to AP")
8516 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8517 e_nonce, e_pk)
8518 send_wsc_msg(hapd, addr, m1)
8519
8520 logger.debug("Receive M2 from AP")
8521 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8522 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8523 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8524
8525 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8526 r_nonce)
8527 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8528
8529 logger.debug("Send WSC_NACK to AP")
8530 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8531 msg_type=None, eap_code=2)
8532 send_wsc_msg(hapd, addr, nack)
8533
8534 wps_wait_eap_failure(hapd, dev[0])
8535
8536def test_wps_ext_m2_nack_invalid_msg_type(dev, apdev):
8537 """WPS proto: M2 followed by NACK with invalid Msg Type"""
8538 pin = "12345670"
8539 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8540 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8541 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8542
8543 logger.debug("Receive WSC/Start from AP")
8544 msg = get_wsc_msg(hapd)
8545 if msg['wsc_opcode'] != WSC_Start:
8546 raise Exception("Unexpected Op-Code for WSC/Start")
8547
8548 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8549 uuid_e = 16*'\x11'
8550 e_nonce = 16*'\x22'
8551 own_private, e_pk = wsc_dh_init()
8552
8553 logger.debug("Send M1 to AP")
8554 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8555 e_nonce, e_pk)
8556 send_wsc_msg(hapd, addr, m1)
8557
8558 logger.debug("Receive M2 from AP")
8559 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8560 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8561 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8562
8563 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8564 r_nonce)
8565 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8566
8567 logger.debug("Send WSC_NACK to AP")
8568 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8569 msg_type=WPS_WSC_ACK, eap_code=2)
8570 send_wsc_msg(hapd, addr, nack)
8571
8572 wps_wait_eap_failure(hapd, dev[0])
8573
8574def test_wps_ext_m2_nack_e_nonce_mismatch(dev, apdev):
8575 """WPS proto: M2 followed by NACK with e-nonce mismatch"""
8576 pin = "12345670"
8577 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8578 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8579 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8580
8581 logger.debug("Receive WSC/Start from AP")
8582 msg = get_wsc_msg(hapd)
8583 if msg['wsc_opcode'] != WSC_Start:
8584 raise Exception("Unexpected Op-Code for WSC/Start")
8585
8586 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8587 uuid_e = 16*'\x11'
8588 e_nonce = 16*'\x22'
8589 own_private, e_pk = wsc_dh_init()
8590
8591 logger.debug("Send M1 to AP")
8592 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8593 e_nonce, e_pk)
8594 send_wsc_msg(hapd, addr, m1)
8595
8596 logger.debug("Receive M2 from AP")
8597 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8598 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8599 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8600
8601 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8602 r_nonce)
8603 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8604
8605 logger.debug("Send WSC_NACK to AP")
8606 nack,attrs = build_nack(msg['eap_identifier'], 16*'\x00', r_nonce,
8607 eap_code=2)
8608 send_wsc_msg(hapd, addr, nack)
8609
8610 wps_wait_eap_failure(hapd, dev[0])
8611
8612def test_wps_ext_m2_nack_no_config_error(dev, apdev):
8613 """WPS proto: M2 followed by NACK without Config Error"""
8614 pin = "12345670"
8615 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8616 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8617 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8618
8619 logger.debug("Receive WSC/Start from AP")
8620 msg = get_wsc_msg(hapd)
8621 if msg['wsc_opcode'] != WSC_Start:
8622 raise Exception("Unexpected Op-Code for WSC/Start")
8623
8624 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8625 uuid_e = 16*'\x11'
8626 e_nonce = 16*'\x22'
8627 own_private, e_pk = wsc_dh_init()
8628
8629 logger.debug("Send M1 to AP")
8630 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8631 e_nonce, e_pk)
8632 send_wsc_msg(hapd, addr, m1)
8633
8634 logger.debug("Receive M2 from AP")
8635 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8636 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8637 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8638
8639 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8640 r_nonce)
8641 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8642
8643 logger.debug("Send WSC_NACK to AP")
8644 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8645 config_error=None, eap_code=2)
8646 send_wsc_msg(hapd, addr, nack)
8647
8648 wps_wait_eap_failure(hapd, dev[0])
8649
8650def test_wps_ext_m2_ack_invalid(dev, apdev):
8651 """WPS proto: M2 followed by invalid ACK"""
8652 pin = "12345670"
8653 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8654 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8655 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8656
8657 logger.debug("Receive WSC/Start from AP")
8658 msg = get_wsc_msg(hapd)
8659 if msg['wsc_opcode'] != WSC_Start:
8660 raise Exception("Unexpected Op-Code for WSC/Start")
8661
8662 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8663 uuid_e = 16*'\x11'
8664 e_nonce = 16*'\x22'
8665 own_private, e_pk = wsc_dh_init()
8666
8667 logger.debug("Send M1 to AP")
8668 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8669 e_nonce, e_pk)
8670 send_wsc_msg(hapd, addr, m1)
8671
8672 logger.debug("Receive M2 from AP")
8673 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8674 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8675 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8676
8677 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8678 r_nonce)
8679 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8680
8681 logger.debug("Send WSC_ACK to AP")
8682 attrs = '\x10\x00\x00'
8683 ack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_ACK)
8684 send_wsc_msg(hapd, addr, ack)
8685
8686 wps_wait_eap_failure(hapd, dev[0])
8687
8688def test_wps_ext_m2_ack(dev, apdev):
8689 """WPS proto: M2 followed by ACK"""
8690 pin = "12345670"
8691 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8692 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8693 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8694
8695 logger.debug("Receive WSC/Start from AP")
8696 msg = get_wsc_msg(hapd)
8697 if msg['wsc_opcode'] != WSC_Start:
8698 raise Exception("Unexpected Op-Code for WSC/Start")
8699
8700 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8701 uuid_e = 16*'\x11'
8702 e_nonce = 16*'\x22'
8703 own_private, e_pk = wsc_dh_init()
8704
8705 logger.debug("Send M1 to AP")
8706 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8707 e_nonce, e_pk)
8708 send_wsc_msg(hapd, addr, m1)
8709
8710 logger.debug("Receive M2 from AP")
8711 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8712 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8713 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8714
8715 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8716 r_nonce)
8717 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8718
8719 logger.debug("Send WSC_ACK to AP")
8720 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce, eap_code=2)
8721 send_wsc_msg(hapd, addr, ack)
8722
8723 wps_wait_eap_failure(hapd, dev[0])
8724
8725def test_wps_ext_m2_ack_no_msg_type(dev, apdev):
8726 """WPS proto: M2 followed by ACK missing Msg Type"""
8727 pin = "12345670"
8728 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8729 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8730 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8731
8732 logger.debug("Receive WSC/Start from AP")
8733 msg = get_wsc_msg(hapd)
8734 if msg['wsc_opcode'] != WSC_Start:
8735 raise Exception("Unexpected Op-Code for WSC/Start")
8736
8737 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8738 uuid_e = 16*'\x11'
8739 e_nonce = 16*'\x22'
8740 own_private, e_pk = wsc_dh_init()
8741
8742 logger.debug("Send M1 to AP")
8743 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8744 e_nonce, e_pk)
8745 send_wsc_msg(hapd, addr, m1)
8746
8747 logger.debug("Receive M2 from AP")
8748 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8749 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8750 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8751
8752 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8753 r_nonce)
8754 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8755
8756 logger.debug("Send WSC_ACK to AP")
8757 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8758 msg_type=None, eap_code=2)
8759 send_wsc_msg(hapd, addr, ack)
8760
8761 wps_wait_eap_failure(hapd, dev[0])
8762
8763def test_wps_ext_m2_ack_invalid_msg_type(dev, apdev):
8764 """WPS proto: M2 followed by ACK with invalid Msg Type"""
8765 pin = "12345670"
8766 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8767 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8768 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8769
8770 logger.debug("Receive WSC/Start from AP")
8771 msg = get_wsc_msg(hapd)
8772 if msg['wsc_opcode'] != WSC_Start:
8773 raise Exception("Unexpected Op-Code for WSC/Start")
8774
8775 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8776 uuid_e = 16*'\x11'
8777 e_nonce = 16*'\x22'
8778 own_private, e_pk = wsc_dh_init()
8779
8780 logger.debug("Send M1 to AP")
8781 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8782 e_nonce, e_pk)
8783 send_wsc_msg(hapd, addr, m1)
8784
8785 logger.debug("Receive M2 from AP")
8786 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8787 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8788 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8789
8790 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8791 r_nonce)
8792 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8793
8794 logger.debug("Send WSC_ACK to AP")
8795 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8796 msg_type=WPS_WSC_NACK, eap_code=2)
8797 send_wsc_msg(hapd, addr, ack)
8798
8799 wps_wait_eap_failure(hapd, dev[0])
8800
8801def test_wps_ext_m2_ack_e_nonce_mismatch(dev, apdev):
8802 """WPS proto: M2 followed by ACK with e-nonce mismatch"""
8803 pin = "12345670"
8804 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8805 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8806 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8807
8808 logger.debug("Receive WSC/Start from AP")
8809 msg = get_wsc_msg(hapd)
8810 if msg['wsc_opcode'] != WSC_Start:
8811 raise Exception("Unexpected Op-Code for WSC/Start")
8812
8813 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8814 uuid_e = 16*'\x11'
8815 e_nonce = 16*'\x22'
8816 own_private, e_pk = wsc_dh_init()
8817
8818 logger.debug("Send M1 to AP")
8819 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8820 e_nonce, e_pk)
8821 send_wsc_msg(hapd, addr, m1)
8822
8823 logger.debug("Receive M2 from AP")
8824 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8825 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8826 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8827
8828 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8829 r_nonce)
8830 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8831
8832 logger.debug("Send WSC_ACK to AP")
8833 ack,attrs = build_ack(msg['eap_identifier'], 16*'\x00', r_nonce,
8834 eap_code=2)
8835 send_wsc_msg(hapd, addr, ack)
8836
8837 wps_wait_eap_failure(hapd, dev[0])
8838
8839def test_wps_ext_m1_invalid(dev, apdev):
8840 """WPS proto: M1 failing parsing"""
8841 pin = "12345670"
8842 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8843 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8844 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8845
8846 logger.debug("Receive WSC/Start from AP")
8847 msg = get_wsc_msg(hapd)
8848 if msg['wsc_opcode'] != WSC_Start:
8849 raise Exception("Unexpected Op-Code for WSC/Start")
8850
8851 logger.debug("Send M1 to AP")
8852 attrs = '\x10\x00\x00'
8853 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8854 send_wsc_msg(hapd, addr, m1)
8855
8856 wps_wait_eap_failure(hapd, dev[0])
8857
8858def test_wps_ext_m1_missing_msg_type(dev, apdev):
8859 """WPS proto: M1 missing Msg Type"""
8860 pin = "12345670"
8861 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8862 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8863 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8864
8865 logger.debug("Receive WSC/Start from AP")
8866 msg = get_wsc_msg(hapd)
8867 if msg['wsc_opcode'] != WSC_Start:
8868 raise Exception("Unexpected Op-Code for WSC/Start")
8869
8870 logger.debug("Send M1 to AP")
8871 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8872 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8873 send_wsc_msg(hapd, addr, m1)
8874
8875 wps_wait_ap_nack(hapd, dev[0], 16*'\x00', 16*'\x00')
8876
8877def wps_ext_wsc_done(dev, apdev):
8878 pin = "12345670"
8879 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8880 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8881 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8882
8883 logger.debug("Receive WSC/Start from AP")
8884 msg = get_wsc_msg(hapd)
8885 if msg['wsc_opcode'] != WSC_Start:
8886 raise Exception("Unexpected Op-Code for WSC/Start")
8887
8888 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8889 uuid_e = 16*'\x11'
8890 e_nonce = 16*'\x22'
8891 own_private, e_pk = wsc_dh_init()
8892
8893 logger.debug("Send M1 to AP")
8894 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8895 e_nonce, e_pk)
8896 send_wsc_msg(hapd, addr, m1)
8897
8898 logger.debug("Receive M2 from AP")
8899 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8900 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8901 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8902
8903 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8904 r_nonce)
8905 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8906
8907 logger.debug("Send M3 to AP")
8908 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8909 attrs += build_attr_msg_type(WPS_M3)
8910 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8911 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8912 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8913 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8914 raw_m3_attrs = attrs
8915 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8916 send_wsc_msg(hapd, addr, m3)
8917
8918 logger.debug("Receive M4 from AP")
8919 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8920
8921 logger.debug("Send M5 to AP")
8922 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8923 attrs += build_attr_msg_type(WPS_M5)
8924 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8925 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8926 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8927 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8928 raw_m5_attrs = attrs
8929 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8930 send_wsc_msg(hapd, addr, m5)
8931
8932 logger.debug("Receive M6 from AP")
8933 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8934
8935 logger.debug("Send M7 to AP")
8936 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8937 attrs += build_attr_msg_type(WPS_M7)
8938 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8939 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
8940 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8941 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8942 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8943 raw_m7_attrs = attrs
8944 send_wsc_msg(hapd, addr, m7)
8945
8946 logger.debug("Receive M8 from AP")
8947 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
8948 return hapd, msg, e_nonce, r_nonce
8949
8950def test_wps_ext_wsc_done_invalid(dev, apdev):
8951 """WPS proto: invalid WSC_Done"""
8952 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
8953
8954 logger.debug("Send WSC_Done to AP")
8955 attrs = '\x10\x00\x00'
8956 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8957 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
8958
8959 wps_wait_eap_failure(hapd, dev[0])
8960
8961def test_wps_ext_wsc_done_no_msg_type(dev, apdev):
8962 """WPS proto: invalid WSC_Done"""
8963 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
8964
8965 logger.debug("Send WSC_Done to AP")
8966 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8967 #attrs += build_attr_msg_type(WPS_WSC_DONE)
8968 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
8969 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8970 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8971 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
8972
8973 wps_wait_eap_failure(hapd, dev[0])
8974
8975def test_wps_ext_wsc_done_wrong_msg_type(dev, apdev):
8976 """WPS proto: WSC_Done with wrong Msg Type"""
8977 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
8978
8979 logger.debug("Send WSC_Done to AP")
8980 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8981 attrs += build_attr_msg_type(WPS_WSC_ACK)
8982 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
8983 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8984 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8985 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
8986
8987 wps_wait_eap_failure(hapd, dev[0])
8988
8989def test_wps_ext_wsc_done_no_e_nonce(dev, apdev):
8990 """WPS proto: WSC_Done without e_nonce"""
8991 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
8992
8993 logger.debug("Send WSC_Done to AP")
8994 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8995 attrs += build_attr_msg_type(WPS_WSC_DONE)
8996 #attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
8997 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8998 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8999 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9000
9001 wps_wait_eap_failure(hapd, dev[0])
9002
9003def test_wps_ext_wsc_done_no_r_nonce(dev, apdev):
9004 """WPS proto: WSC_Done without r_nonce"""
9005 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9006
9007 logger.debug("Send WSC_Done to AP")
9008 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9009 attrs += build_attr_msg_type(WPS_WSC_DONE)
9010 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9011 #attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9012 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9013 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9014
9015 wps_wait_eap_failure(hapd, dev[0])
9016
9017def test_wps_ext_m7_no_encr_settings(dev, apdev):
9018 """WPS proto: M7 without Encr Settings"""
9019 pin = "12345670"
9020 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9021 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9022 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9023
9024 logger.debug("Receive WSC/Start from AP")
9025 msg = get_wsc_msg(hapd)
9026 if msg['wsc_opcode'] != WSC_Start:
9027 raise Exception("Unexpected Op-Code for WSC/Start")
9028
9029 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9030 uuid_e = 16*'\x11'
9031 e_nonce = 16*'\x22'
9032 own_private, e_pk = wsc_dh_init()
9033
9034 logger.debug("Send M1 to AP")
9035 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9036 e_nonce, e_pk)
9037 send_wsc_msg(hapd, addr, m1)
9038
9039 logger.debug("Receive M2 from AP")
9040 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9041 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9042 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9043
9044 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9045 r_nonce)
9046 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9047
9048 logger.debug("Send M3 to AP")
9049 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9050 attrs += build_attr_msg_type(WPS_M3)
9051 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9052 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9053 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9054 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9055 raw_m3_attrs = attrs
9056 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9057 send_wsc_msg(hapd, addr, m3)
9058
9059 logger.debug("Receive M4 from AP")
9060 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9061
9062 logger.debug("Send M5 to AP")
9063 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9064 attrs += build_attr_msg_type(WPS_M5)
9065 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9066 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9067 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9068 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9069 raw_m5_attrs = attrs
9070 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9071 send_wsc_msg(hapd, addr, m5)
9072
9073 logger.debug("Receive M6 from AP")
9074 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9075
9076 logger.debug("Send M7 to AP")
9077 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9078 attrs += build_attr_msg_type(WPS_M7)
9079 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9080 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9081 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9082 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9083 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9084 raw_m7_attrs = attrs
9085 send_wsc_msg(hapd, addr, m7)
9086
9087 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
9088
9089def test_wps_ext_m1_workaround(dev, apdev):
9090 """WPS proto: M1 Manufacturer/Model workaround"""
9091 pin = "12345670"
9092 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9093 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9094 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9095
9096 logger.debug("Receive WSC/Start from AP")
9097 msg = get_wsc_msg(hapd)
9098 if msg['wsc_opcode'] != WSC_Start:
9099 raise Exception("Unexpected Op-Code for WSC/Start")
9100
9101 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9102 uuid_e = 16*'\x11'
9103 e_nonce = 16*'\x22'
9104 own_private, e_pk = wsc_dh_init()
9105
9106 logger.debug("Send M1 to AP")
9107 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9108 e_nonce, e_pk, manufacturer='Apple TEST',
9109 model_name='AirPort', config_methods='\xff\xff')
9110 send_wsc_msg(hapd, addr, m1)
9111
9112 logger.debug("Receive M2 from AP")
9113 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
53bd8653
JM
9114
9115def test_ap_wps_disable_enable(dev, apdev):
9116 """WPS and DISABLE/ENABLE AP"""
9117 hapd = wps_start_ap(apdev[0])
9118 hapd.disable()
9119 hapd.enable()
9120 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
dd124ee8
JM
9121
9122def test_ap_wps_upnp_web_oom(dev, apdev, params):
9123 """hostapd WPS UPnP web OOM"""
9124 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 9125 hapd = add_ssdp_ap(apdev[0], ap_uuid)
dd124ee8
JM
9126
9127 location = ssdp_get_location(ap_uuid)
9128 url = urlparse.urlparse(location)
9129 urls = upnp_get_urls(location)
9130 eventurl = urlparse.urlparse(urls['event_sub_url'])
9131 ctrlurl = urlparse.urlparse(urls['control_url'])
9132
9133 conn = httplib.HTTPConnection(url.netloc)
9134 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9135 conn.request("GET", "/wps_device.xml")
9136 try:
9137 resp = conn.getresponse()
9138 except:
9139 pass
9140
9141 conn = httplib.HTTPConnection(url.netloc)
9142 conn.request("GET", "/unknown")
9143 resp = conn.getresponse()
9144 if resp.status != 404:
9145 raise Exception("Unexpected HTTP result for unknown URL: %d" + resp.status)
9146
9147 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9148 conn.request("GET", "/unknown")
9149 try:
9150 resp = conn.getresponse()
9151 print resp.status
9152 except:
9153 pass
9154
9155 conn = httplib.HTTPConnection(url.netloc)
9156 conn.request("GET", "/wps_device.xml")
9157 resp = conn.getresponse()
9158 if resp.status != 200:
9159 raise Exception("GET /wps_device.xml failed")
9160
9161 conn = httplib.HTTPConnection(url.netloc)
9162 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9163 if resp.status != 200:
9164 raise Exception("GetDeviceInfo failed")
9165
9166 with alloc_fail(hapd, 1, "web_process_get_device_info"):
9167 conn = httplib.HTTPConnection(url.netloc)
9168 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9169 if resp.status != 500:
9170 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9171
9172 with alloc_fail(hapd, 1, "wps_build_m1;web_process_get_device_info"):
9173 conn = httplib.HTTPConnection(url.netloc)
9174 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9175 if resp.status != 500:
9176 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9177
9178 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_send_reply"):
9179 conn = httplib.HTTPConnection(url.netloc)
9180 try:
9181 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9182 except:
9183 pass
9184
9185 conn = httplib.HTTPConnection(url.netloc)
9186 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9187 if resp.status != 200:
9188 raise Exception("GetDeviceInfo failed")
9189
9190 # No NewWLANEventType in PutWLANResponse NewMessage
9191 conn = httplib.HTTPConnection(url.netloc)
9192 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse", newmsg="foo")
9193 if resp.status != 600:
9194 raise Exception("Unexpected HTTP response: %d" % resp.status)
9195
9196 # No NewWLANEventMAC in PutWLANResponse NewMessage
9197 conn = httplib.HTTPConnection(url.netloc)
9198 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9199 newmsg="foo", neweventtype="1")
9200 if resp.status != 600:
9201 raise Exception("Unexpected HTTP response: %d" % resp.status)
9202
9203 # Invalid NewWLANEventMAC in PutWLANResponse NewMessage
9204 conn = httplib.HTTPConnection(url.netloc)
9205 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9206 newmsg="foo", neweventtype="1",
9207 neweventmac="foo")
9208 if resp.status != 600:
9209 raise Exception("Unexpected HTTP response: %d" % resp.status)
9210
9211 # Workaround for NewWLANEventMAC in PutWLANResponse NewMessage
9212 # Ignored unexpected PutWLANResponse WLANEventType 1
9213 conn = httplib.HTTPConnection(url.netloc)
9214 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9215 newmsg="foo", neweventtype="1",
9216 neweventmac="00.11.22.33.44.55")
9217 if resp.status != 500:
9218 raise Exception("Unexpected HTTP response: %d" % resp.status)
9219
9220 # PutWLANResponse NewMessage with invalid EAP message
9221 conn = httplib.HTTPConnection(url.netloc)
9222 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9223 newmsg="foo", neweventtype="2",
9224 neweventmac="00:11:22:33:44:55")
9225 if resp.status != 200:
9226 raise Exception("Unexpected HTTP response: %d" % resp.status)
9227
9228 with alloc_fail(hapd, 1, "web_connection_parse_subscribe"):
9229 conn = httplib.HTTPConnection(url.netloc)
9230 headers = { "callback": '<http://127.0.0.1:12345/event>',
9231 "NT": "upnp:event",
9232 "timeout": "Second-1234" }
9233 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9234 try:
9235 resp = conn.getresponse()
9236 except:
9237 pass
9238
9239 with alloc_fail(hapd, 1, "dup_binstr;web_connection_parse_subscribe"):
9240 conn = httplib.HTTPConnection(url.netloc)
9241 headers = { "callback": '<http://127.0.0.1:12345/event>',
9242 "NT": "upnp:event",
9243 "timeout": "Second-1234" }
9244 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9245 resp = conn.getresponse()
9246 if resp.status != 500:
9247 raise Exception("Unexpected HTTP response: %d" % resp.status)
9248
9249 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_parse_unsubscribe"):
9250 conn = httplib.HTTPConnection(url.netloc)
9251 headers = { "callback": '<http://127.0.0.1:12345/event>',
9252 "NT": "upnp:event",
9253 "timeout": "Second-1234" }
9254 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9255 try:
9256 resp = conn.getresponse()
9257 except:
9258 pass
9259
9260 with alloc_fail(hapd, 1, "web_connection_unimplemented"):
9261 conn = httplib.HTTPConnection(url.netloc)
9262 conn.request("HEAD", "/wps_device.xml")
9263 try:
9264 resp = conn.getresponse()
9265 except:
9266 pass
d1341917
JM
9267
9268def test_ap_wps_frag_ack_oom(dev, apdev):
9269 """WPS and fragment ack OOM"""
9270 dev[0].request("SET wps_fragment_size 50")
9271 hapd = wps_start_ap(apdev[0])
9272 with alloc_fail(hapd, 1, "eap_wsc_build_frag_ack"):
9273 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
1e35aa15
JM
9274
9275def wait_scan_stopped(dev):
9276 dev.request("ABORT_SCAN")
9277 for i in range(50):
9278 res = dev.get_driver_status_field("scan_state")
9279 if "SCAN_STARTED" not in res and "SCAN_REQUESTED" not in res:
9280 break
9281 logger.debug("Waiting for scan to complete")
9282 time.sleep(0.1)
9283
9284def test_ap_wps_eap_wsc_errors(dev, apdev):
9285 """WPS and EAP-WSC error cases"""
9286 ssid = "test-wps-conf-pin"
9287 appin = "12345670"
9288 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9289 "wpa_passphrase": "12345678", "wpa": "2",
9290 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9291 "fragment_size": "300", "ap_pin": appin }
8b8a1864 9292 hapd = hostapd.add_ap(apdev[0], params)
1e35aa15
JM
9293 bssid = apdev[0]['bssid']
9294
9295 pin = dev[0].wps_read_pin()
9296 hapd.request("WPS_PIN any " + pin)
9297 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9298 dev[0].dump_monitor()
9299
9300 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK", "CCMP",
9301 "new passphrase", no_wait=True)
9302 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9303 if ev is None:
9304 raise Exception("WPS-FAIL not reported")
9305 dev[0].request("WPS_CANCEL")
9306 dev[0].wait_disconnected()
9307 wait_scan_stopped(dev[0])
9308 dev[0].dump_monitor()
9309
9310 dev[0].wps_reg(bssid, appin, "new ssid", "FOO", "CCMP",
9311 "new passphrase", no_wait=True)
9312 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9313 if ev is None:
9314 raise Exception("WPS-FAIL not reported")
9315 dev[0].request("WPS_CANCEL")
9316 dev[0].wait_disconnected()
9317 wait_scan_stopped(dev[0])
9318 dev[0].dump_monitor()
9319
9320 dev[0].wps_reg(bssid, appin, "new ssid", "WPA2PSK", "FOO",
9321 "new passphrase", no_wait=True)
9322 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9323 if ev is None:
9324 raise Exception("WPS-FAIL not reported")
9325 dev[0].request("WPS_CANCEL")
9326 dev[0].wait_disconnected()
9327 wait_scan_stopped(dev[0])
9328 dev[0].dump_monitor()
9329
9330 dev[0].wps_reg(bssid, appin + "new_key=a", "new ssid", "WPA2PSK", "CCMP",
9331 "new passphrase", no_wait=True)
9332 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9333 if ev is None:
9334 raise Exception("WPS-FAIL not reported")
9335 dev[0].request("WPS_CANCEL")
9336 dev[0].wait_disconnected()
9337 wait_scan_stopped(dev[0])
9338 dev[0].dump_monitor()
9339
9340 tests = [ "eap_wsc_init",
9341 "eap_msg_alloc;eap_wsc_build_msg",
9342 "wpabuf_alloc;eap_wsc_process_fragment" ]
9343 for func in tests:
9344 with alloc_fail(dev[0], 1, func):
9345 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
9346 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9347 dev[0].request("WPS_CANCEL")
9348 dev[0].wait_disconnected()
9349 wait_scan_stopped(dev[0])
9350 dev[0].dump_monitor()
d8e5a55f 9351
bd3948c0
JM
9352 with alloc_fail(dev[0], 1, "eap_msg_alloc;eap_sm_build_expanded_nak"):
9353 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK",
9354 "CCMP", "new passphrase", no_wait=True)
9355 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9356 dev[0].request("WPS_CANCEL")
9357 dev[0].wait_disconnected()
9358 wait_scan_stopped(dev[0])
9359 dev[0].dump_monitor()
9360
d8e5a55f
JM
9361def test_ap_wps_eap_wsc(dev, apdev):
9362 """WPS and EAP-WSC in network profile"""
9363 params = int_eap_server_params()
9364 params["wps_state"] = "2"
8b8a1864 9365 hapd = hostapd.add_ap(apdev[0], params)
d8e5a55f
JM
9366 bssid = apdev[0]['bssid']
9367
9368 logger.info("Unexpected identity")
9369 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9370 eap="WSC", identity="WFA-SimpleConfig-Enrollee-unexpected",
9371 wait_connect=False)
9372 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9373 if ev is None:
9374 raise Exception("No EAP-Failure seen")
9375 dev[0].request("REMOVE_NETWORK all")
9376 dev[0].wait_disconnected()
9377
9378 logger.info("No phase1 parameter")
9379 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9380 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9381 wait_connect=False)
9382 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9383 if ev is None:
9384 raise Exception("Timeout on EAP method start")
9385 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9386 if ev is None:
9387 raise Exception("No EAP-Failure seen")
9388 dev[0].request("REMOVE_NETWORK all")
9389 dev[0].wait_disconnected()
9390
9391 logger.info("No PIN/PBC in phase1")
9392 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9393 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9394 phase1="foo", wait_connect=False)
9395 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9396 if ev is None:
9397 raise Exception("Timeout on EAP method start")
9398 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9399 if ev is None:
9400 raise Exception("No EAP-Failure seen")
9401 dev[0].request("REMOVE_NETWORK all")
9402 dev[0].wait_disconnected()
9403
9404 logger.info("Invalid pkhash in phase1")
9405 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9406 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9407 phase1="foo pkhash=q pbc=1", wait_connect=False)
9408 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9409 if ev is None:
9410 raise Exception("Timeout on EAP method start")
9411 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9412 if ev is None:
9413 raise Exception("No EAP-Failure seen")
9414 dev[0].request("REMOVE_NETWORK all")
9415 dev[0].wait_disconnected()
9416
9417 logger.info("Zero fragment_size")
9418 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9419 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9420 fragment_size="0", phase1="pin=12345670", wait_connect=False)
9421 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9422 if ev is None:
9423 raise Exception("Timeout on EAP method start")
9424 ev = dev[0].wait_event(["WPS-M2D"], timeout=5)
9425 if ev is None:
9426 raise Exception("No M2D seen")
9427 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9428 if ev is None:
9429 raise Exception("No EAP-Failure seen")
9430 dev[0].request("REMOVE_NETWORK all")
9431 dev[0].wait_disconnected()
9432
9433 logger.info("Missing new_auth")
9434 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9435 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9436 phase1="pin=12345670 new_ssid=aa", wait_connect=False)
9437 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9438 if ev is None:
9439 raise Exception("Timeout on EAP method start")
9440 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9441 if ev is None:
9442 raise Exception("No EAP-Failure seen")
9443 dev[0].request("REMOVE_NETWORK all")
9444 dev[0].wait_disconnected()
9445
9446 logger.info("Missing new_encr")
9447 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9448 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9449 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa", wait_connect=False)
9450 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9451 if ev is None:
9452 raise Exception("Timeout on EAP method start")
9453 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9454 if ev is None:
9455 raise Exception("No EAP-Failure seen")
9456 dev[0].request("REMOVE_NETWORK all")
9457 dev[0].wait_disconnected()
9458
9459 logger.info("Missing new_key")
9460 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9461 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9462 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa new_encr=CCMP",
9463 wait_connect=False)
9464 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9465 if ev is None:
9466 raise Exception("Timeout on EAP method start")
9467 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9468 if ev is None:
9469 raise Exception("No EAP-Failure seen")
9470 dev[0].request("REMOVE_NETWORK all")
9471 dev[0].wait_disconnected()