]> git.ipfire.org Git - thirdparty/hostap.git/blame - tests/hwsim/test_ap_wps.py
tests: Convert kernel-config to defconfig
[thirdparty/hostap.git] / tests / hwsim / test_ap_wps.py
CommitLineData
302b7a1b 1# WPS tests
3381d324 2# Copyright (c) 2013-2017, 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
9fd6804d 7from remotehost import remote_compatible
97d2d7ac 8from tshark import run_tshark
6aaa661a 9import base64
476daa05 10import binascii
7511ead0
JM
11from Crypto.Cipher import AES
12import hashlib
13import hmac
2035b170 14import os
302b7a1b 15import time
308ecbc1 16import sys
2602a2ff 17import stat
302b7a1b
JM
18import subprocess
19import logging
c9aa4308 20logger = logging.getLogger()
1013a576 21import re
44ff0400 22import socket
7511ead0 23import struct
9c06eda0
MH
24try:
25 from http.client import HTTPConnection
26 from urllib.request import urlopen
27 from urllib.parse import urlparse, urljoin
28 from urllib.error import HTTPError
29 from io import StringIO
30 from socketserver import StreamRequestHandler, TCPServer
31except ImportError:
32 from httplib import HTTPConnection
33 from urllib import urlopen
34 from urlparse import urlparse, urljoin
35 from urllib2 import build_opener, ProxyHandler, HTTPError
36 from StringIO import StringIO
37 from SocketServer import StreamRequestHandler, TCPServer
47c549fd
JM
38import urllib
39import xml.etree.ElementTree as ET
302b7a1b
JM
40
41import hwsim_utils
42import hostapd
1531402e 43from wpasupplicant import WpaSupplicant
c965ae03 44from utils import HwsimSkip, alloc_fail, fail_test, skip_with_fips
207fe29d 45from utils import wait_fail_trigger, clear_regdom
d8e5a55f 46from test_ap_eap import int_eap_server_params
4c0af8ad 47from test_sae import check_sae_capab
200c7693 48from test_wep import check_wep_capa
302b7a1b 49
24b7f282 50def wps_start_ap(apdev, ssid="test-wps-conf"):
fab49f61
JM
51 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
52 "wpa_passphrase": "12345678", "wpa": "2",
53 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
afc26df2 54 return hostapd.add_ap(apdev, params)
24b7f282 55
9fd6804d 56@remote_compatible
ae3ad328 57def test_ap_wps_init(dev, apdev):
302b7a1b
JM
58 """Initial AP configuration with first WPS Enrollee"""
59 ssid = "test-wps"
6f334bf7 60 hapd = hostapd.add_ap(apdev[0],
fab49f61 61 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
302b7a1b
JM
62 logger.info("WPS provisioning step")
63 hapd.request("WPS_PBC")
d671a420
JM
64 if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
65 raise Exception("PBC status not shown correctly")
b9018833
JM
66
67 id = dev[0].add_network()
68 dev[0].set_network_quoted(id, "ssid", "home")
69 dev[0].set_network_quoted(id, "psk", "12345678")
70 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
71
72 id = dev[0].add_network()
73 dev[0].set_network_quoted(id, "ssid", "home2")
74 dev[0].set_network(id, "bssid", "00:11:22:33:44:55")
75 dev[0].set_network(id, "key_mgmt", "NONE")
76 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
77
302b7a1b 78 dev[0].request("WPS_PBC")
5f35a5e2 79 dev[0].wait_connected(timeout=30)
302b7a1b 80 status = dev[0].get_status()
ae3ad328 81 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
82 raise Exception("Not fully connected")
83 if status['ssid'] != ssid:
84 raise Exception("Unexpected SSID")
85 if status['pairwise_cipher'] != 'CCMP':
86 raise Exception("Unexpected encryption configuration")
87 if status['key_mgmt'] != 'WPA2-PSK':
88 raise Exception("Unexpected key_mgmt")
89
d671a420
JM
90 status = hapd.request("WPS_GET_STATUS")
91 if "PBC Status: Disabled" not in status:
92 raise Exception("PBC status not shown correctly")
93 if "Last WPS result: Success" not in status:
94 raise Exception("Last WPS result not shown correctly")
95 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
96 raise Exception("Peer address not shown correctly")
75b25ece
JM
97 conf = hapd.request("GET_CONFIG")
98 if "wps_state=configured" not in conf:
99 raise Exception("AP not in WPS configured state")
742408af
JM
100 if "wpa=3" not in conf:
101 raise Exception("AP not in WPA+WPA2 configuration")
75b25ece
JM
102 if "rsn_pairwise_cipher=CCMP TKIP" not in conf:
103 raise Exception("Unexpected rsn_pairwise_cipher")
104 if "wpa_pairwise_cipher=CCMP TKIP" not in conf:
105 raise Exception("Unexpected wpa_pairwise_cipher")
106 if "group_cipher=TKIP" not in conf:
107 raise Exception("Unexpected group_cipher")
d671a420 108
b9018833
JM
109 if len(dev[0].list_networks()) != 3:
110 raise Exception("Unexpected number of network blocks")
111
18030dc0
JM
112def test_ap_wps_init_2ap_pbc(dev, apdev):
113 """Initial two-radio AP configuration with first WPS PBC Enrollee"""
114 ssid = "test-wps"
fab49f61 115 params = {"ssid": ssid, "eap_server": "1", "wps_state": "1"}
6f334bf7 116 hapd = hostapd.add_ap(apdev[0], params)
8b8a1864 117 hostapd.add_ap(apdev[1], params)
18030dc0
JM
118 logger.info("WPS provisioning step")
119 hapd.request("WPS_PBC")
84a40841
JM
120 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
121 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
122 bss = dev[0].get_bss(apdev[0]['bssid'])
123 if "[WPS-PBC]" not in bss['flags']:
124 raise Exception("WPS-PBC flag missing from AP1")
125 bss = dev[0].get_bss(apdev[1]['bssid'])
126 if "[WPS-PBC]" not in bss['flags']:
127 raise Exception("WPS-PBC flag missing from AP2")
128 dev[0].dump_monitor()
f19d87f1 129 dev[0].request("SET wps_cred_processing 2")
18030dc0 130 dev[0].request("WPS_PBC")
f19d87f1
JM
131 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=30)
132 dev[0].request("SET wps_cred_processing 0")
133 if ev is None:
134 raise Exception("WPS cred event not seen")
135 if "100e" not in ev:
136 raise Exception("WPS attributes not included in the cred event")
5f35a5e2 137 dev[0].wait_connected(timeout=30)
18030dc0 138
84a40841
JM
139 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
140 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
141 bss = dev[1].get_bss(apdev[0]['bssid'])
142 if "[WPS-PBC]" in bss['flags']:
143 raise Exception("WPS-PBC flag not cleared from AP1")
144 bss = dev[1].get_bss(apdev[1]['bssid'])
145 if "[WPS-PBC]" in bss['flags']:
0bde923c 146 raise Exception("WPS-PBC flag not cleared from AP2")
18030dc0
JM
147
148def test_ap_wps_init_2ap_pin(dev, apdev):
149 """Initial two-radio AP configuration with first WPS PIN Enrollee"""
150 ssid = "test-wps"
fab49f61 151 params = {"ssid": ssid, "eap_server": "1", "wps_state": "1"}
6f334bf7 152 hapd = hostapd.add_ap(apdev[0], params)
8b8a1864 153 hostapd.add_ap(apdev[1], params)
18030dc0
JM
154 logger.info("WPS provisioning step")
155 pin = dev[0].wps_read_pin()
156 hapd.request("WPS_PIN any " + pin)
84a40841
JM
157 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
158 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
159 bss = dev[0].get_bss(apdev[0]['bssid'])
160 if "[WPS-AUTH]" not in bss['flags']:
161 raise Exception("WPS-AUTH flag missing from AP1")
162 bss = dev[0].get_bss(apdev[1]['bssid'])
163 if "[WPS-AUTH]" not in bss['flags']:
164 raise Exception("WPS-AUTH flag missing from AP2")
165 dev[0].dump_monitor()
166 dev[0].request("WPS_PIN any " + pin)
5f35a5e2 167 dev[0].wait_connected(timeout=30)
18030dc0 168
84a40841
JM
169 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
170 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
171 bss = dev[1].get_bss(apdev[0]['bssid'])
172 if "[WPS-AUTH]" in bss['flags']:
173 raise Exception("WPS-AUTH flag not cleared from AP1")
174 bss = dev[1].get_bss(apdev[1]['bssid'])
175 if "[WPS-AUTH]" in bss['flags']:
0bde923c 176 raise Exception("WPS-AUTH flag not cleared from AP2")
18030dc0 177
9fd6804d 178@remote_compatible
35831e94
JM
179def test_ap_wps_init_through_wps_config(dev, apdev):
180 """Initial AP configuration using wps_config command"""
181 ssid = "test-wps-init-config"
6f334bf7 182 hapd = hostapd.add_ap(apdev[0],
fab49f61 183 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
54c58f29 184 if "FAIL" in hapd.request("WPS_CONFIG " + binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(b"12345678").decode()):
35831e94 185 raise Exception("WPS_CONFIG command failed")
180cd73d
JM
186 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
187 if ev is None:
188 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
189 # It takes some time for the AP to update Beacon and Probe Response frames,
190 # so wait here before requesting the scan to be started to avoid adding
191 # extra five second wait to the test due to fetching obsolete scan results.
192 hapd.ping()
193 time.sleep(0.2)
35831e94
JM
194 dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
195 pairwise="CCMP", group="CCMP")
196
82358a2a
JM
197 if "FAIL" not in hapd.request("WPS_CONFIG foo"):
198 raise Exception("Invalid WPS_CONFIG accepted")
199
9fd6804d 200@remote_compatible
fbf6b717
JM
201def test_ap_wps_init_through_wps_config_2(dev, apdev):
202 """AP configuration using wps_config and wps_cred_processing=2"""
203 ssid = "test-wps-init-config"
6f334bf7 204 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
205 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
206 "wps_cred_processing": "2"})
54c58f29 207 if "FAIL" in hapd.request("WPS_CONFIG " + binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(b"12345678").decode()):
fbf6b717
JM
208 raise Exception("WPS_CONFIG command failed")
209 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
210 if ev is None:
211 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
212 if "100e" not in ev:
213 raise Exception("WPS-NEW-AP-SETTINGS did not include Credential")
214
9fd6804d 215@remote_compatible
e1eb0e9e
JM
216def test_ap_wps_invalid_wps_config_passphrase(dev, apdev):
217 """AP configuration using wps_config command with invalid passphrase"""
218 ssid = "test-wps-init-config"
6f334bf7 219 hapd = hostapd.add_ap(apdev[0],
fab49f61 220 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
54c58f29 221 if "FAIL" not in hapd.request("WPS_CONFIG " + binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(b"1234567").decode()):
e1eb0e9e
JM
222 raise Exception("Invalid WPS_CONFIG command accepted")
223
ae3ad328 224def test_ap_wps_conf(dev, apdev):
302b7a1b
JM
225 """WPS PBC provisioning with configured AP"""
226 ssid = "test-wps-conf"
6f334bf7 227 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
228 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
229 "wpa_passphrase": "12345678", "wpa": "2",
230 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
302b7a1b
JM
231 logger.info("WPS provisioning step")
232 hapd.request("WPS_PBC")
60b06d87 233 dev[0].set("device_name", "Device A")
33d0b157 234 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 235 dev[0].dump_monitor()
33d0b157 236 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 237 dev[0].wait_connected(timeout=30)
302b7a1b 238 status = dev[0].get_status()
ae3ad328 239 if status['wpa_state'] != 'COMPLETED':
302b7a1b 240 raise Exception("Not fully connected")
ae3ad328
JM
241 if status['bssid'] != apdev[0]['bssid']:
242 raise Exception("Unexpected BSSID")
302b7a1b
JM
243 if status['ssid'] != ssid:
244 raise Exception("Unexpected SSID")
245 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
246 raise Exception("Unexpected encryption configuration")
247 if status['key_mgmt'] != 'WPA2-PSK':
248 raise Exception("Unexpected key_mgmt")
249
097cd9cd
JM
250 sta = hapd.get_sta(dev[0].p2p_interface_addr())
251 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
252 raise Exception("Device name not available in STA command")
253
daad14cc
JM
254def test_ap_wps_conf_5ghz(dev, apdev):
255 """WPS PBC provisioning with configured AP on 5 GHz band"""
256 try:
9d7fdac5 257 hapd = None
daad14cc 258 ssid = "test-wps-conf"
fab49f61
JM
259 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
260 "wpa_passphrase": "12345678", "wpa": "2",
261 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
262 "country_code": "FI", "hw_mode": "a", "channel": "36"}
8b8a1864 263 hapd = hostapd.add_ap(apdev[0], params)
daad14cc
JM
264 logger.info("WPS provisioning step")
265 hapd.request("WPS_PBC")
60b06d87 266 dev[0].set("device_name", "Device A")
33d0b157
JM
267 dev[0].scan_for_bss(apdev[0]['bssid'], freq="5180")
268 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 269 dev[0].wait_connected(timeout=30)
daad14cc
JM
270
271 sta = hapd.get_sta(dev[0].p2p_interface_addr())
272 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
273 raise Exception("Device name not available in STA command")
274 finally:
9d7fdac5 275 dev[0].request("DISCONNECT")
cb5f7f55 276 clear_regdom(hapd, dev)
daad14cc
JM
277
278def test_ap_wps_conf_chan14(dev, apdev):
279 """WPS PBC provisioning with configured AP on channel 14"""
280 try:
9d7fdac5 281 hapd = None
daad14cc 282 ssid = "test-wps-conf"
fab49f61
JM
283 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
284 "wpa_passphrase": "12345678", "wpa": "2",
285 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
286 "country_code": "JP", "hw_mode": "b", "channel": "14"}
8b8a1864 287 hapd = hostapd.add_ap(apdev[0], params)
daad14cc
JM
288 logger.info("WPS provisioning step")
289 hapd.request("WPS_PBC")
60b06d87 290 dev[0].set("device_name", "Device A")
daad14cc 291 dev[0].request("WPS_PBC")
5f35a5e2 292 dev[0].wait_connected(timeout=30)
daad14cc
JM
293
294 sta = hapd.get_sta(dev[0].p2p_interface_addr())
295 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
296 raise Exception("Device name not available in STA command")
297 finally:
9d7fdac5 298 dev[0].request("DISCONNECT")
207fe29d 299 clear_regdom(hapd, dev)
daad14cc 300
9fd6804d 301@remote_compatible
04e62788
JM
302def test_ap_wps_twice(dev, apdev):
303 """WPS provisioning with twice to change passphrase"""
304 ssid = "test-wps-twice"
fab49f61
JM
305 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
306 "wpa_passphrase": "12345678", "wpa": "2",
307 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
01703a9f 308 hapd = hostapd.add_ap(apdev[0], params)
04e62788
JM
309 logger.info("WPS provisioning step")
310 hapd.request("WPS_PBC")
33d0b157 311 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
04e62788 312 dev[0].dump_monitor()
33d0b157 313 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 314 dev[0].wait_connected(timeout=30)
04e62788
JM
315 dev[0].request("DISCONNECT")
316
317 logger.info("Restart AP with different passphrase and re-run WPS")
01703a9f 318 hostapd.remove_bss(apdev[0])
04e62788 319 params['wpa_passphrase'] = 'another passphrase'
01703a9f 320 hapd = hostapd.add_ap(apdev[0], params)
04e62788
JM
321 logger.info("WPS provisioning step")
322 hapd.request("WPS_PBC")
323 dev[0].dump_monitor()
33d0b157 324 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 325 dev[0].wait_connected(timeout=30)
04e62788
JM
326 networks = dev[0].list_networks()
327 if len(networks) > 1:
328 raise Exception("Unexpected duplicated network block present")
329
9fd6804d 330@remote_compatible
d658205a
JM
331def test_ap_wps_incorrect_pin(dev, apdev):
332 """WPS PIN provisioning with incorrect PIN"""
333 ssid = "test-wps-incorrect-pin"
6f334bf7 334 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
335 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
336 "wpa_passphrase": "12345678", "wpa": "2",
337 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
d658205a
JM
338
339 logger.info("WPS provisioning attempt 1")
340 hapd.request("WPS_PIN any 12345670")
33d0b157 341 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
d658205a 342 dev[0].dump_monitor()
33d0b157 343 dev[0].request("WPS_PIN %s 55554444" % apdev[0]['bssid'])
d658205a
JM
344 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
345 if ev is None:
346 raise Exception("WPS operation timed out")
347 if "config_error=18" not in ev:
348 raise Exception("Incorrect config_error reported")
349 if "msg=8" not in ev:
350 raise Exception("PIN error detected on incorrect message")
5f35a5e2 351 dev[0].wait_disconnected(timeout=10)
d658205a
JM
352 dev[0].request("WPS_CANCEL")
353 # if a scan was in progress, wait for it to complete before trying WPS again
354 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
355
d671a420
JM
356 status = hapd.request("WPS_GET_STATUS")
357 if "Last WPS result: Failed" not in status:
358 raise Exception("WPS failure result not shown correctly")
359
d658205a
JM
360 logger.info("WPS provisioning attempt 2")
361 hapd.request("WPS_PIN any 12345670")
362 dev[0].dump_monitor()
33d0b157 363 dev[0].request("WPS_PIN %s 12344444" % apdev[0]['bssid'])
d658205a
JM
364 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
365 if ev is None:
366 raise Exception("WPS operation timed out")
367 if "config_error=18" not in ev:
368 raise Exception("Incorrect config_error reported")
369 if "msg=10" not in ev:
370 raise Exception("PIN error detected on incorrect message")
5f35a5e2 371 dev[0].wait_disconnected(timeout=10)
d658205a 372
9fd6804d 373@remote_compatible
ae3ad328 374def test_ap_wps_conf_pin(dev, apdev):
302b7a1b
JM
375 """WPS PIN provisioning with configured AP"""
376 ssid = "test-wps-conf-pin"
6f334bf7 377 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
378 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
379 "wpa_passphrase": "12345678", "wpa": "2",
380 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
302b7a1b
JM
381 logger.info("WPS provisioning step")
382 pin = dev[0].wps_read_pin()
383 hapd.request("WPS_PIN any " + pin)
33d0b157 384 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 385 dev[0].dump_monitor()
33d0b157 386 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 387 dev[0].wait_connected(timeout=30)
302b7a1b 388 status = dev[0].get_status()
ae3ad328 389 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
390 raise Exception("Not fully connected")
391 if status['ssid'] != ssid:
392 raise Exception("Unexpected SSID")
393 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
394 raise Exception("Unexpected encryption configuration")
395 if status['key_mgmt'] != 'WPA2-PSK':
396 raise Exception("Unexpected key_mgmt")
397
84a40841 398 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
362ba6de
JM
399 bss = dev[1].get_bss(apdev[0]['bssid'])
400 if "[WPS-AUTH]" in bss['flags']:
401 raise Exception("WPS-AUTH flag not cleared")
a60a6d6b 402 logger.info("Try to connect from another station using the same PIN")
33d0b157 403 pin = dev[1].request("WPS_PIN " + apdev[0]['bssid'])
fab49f61 404 ev = dev[1].wait_event(["WPS-M2D", "CTRL-EVENT-CONNECTED"], timeout=30)
a60a6d6b
JM
405 if ev is None:
406 raise Exception("Operation timed out")
407 if "WPS-M2D" not in ev:
408 raise Exception("Unexpected WPS operation started")
6e12eaa4 409 hapd.request("WPS_PIN any " + pin)
5f35a5e2 410 dev[1].wait_connected(timeout=30)
362ba6de 411
ff518fbd
JM
412def test_ap_wps_conf_pin_mixed_mode(dev, apdev):
413 """WPS PIN provisioning with configured AP (WPA+WPA2)"""
414 ssid = "test-wps-conf-pin-mixed"
6f334bf7 415 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
416 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
417 "wpa_passphrase": "12345678", "wpa": "3",
418 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
419 "wpa_pairwise": "TKIP"})
ff518fbd
JM
420
421 logger.info("WPS provisioning step")
422 pin = dev[0].wps_read_pin()
423 hapd.request("WPS_PIN any " + pin)
424 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
425 dev[0].dump_monitor()
426 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
427 dev[0].wait_connected(timeout=30)
428 status = dev[0].get_status()
429 dev[0].request("REMOVE_NETWORK all")
430 dev[0].wait_disconnected()
431 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
432 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
433
434 logger.info("WPS provisioning step (auth_types=0x1b)")
435 if "OK" not in dev[0].request("SET wps_force_auth_types 0x1b"):
436 raise Exception("Failed to set wps_force_auth_types 0x1b")
437 pin = dev[0].wps_read_pin()
438 hapd.request("WPS_PIN any " + pin)
439 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
440 dev[0].dump_monitor()
441 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
442 dev[0].wait_connected(timeout=30)
443 status = dev[0].get_status()
444 dev[0].request("REMOVE_NETWORK all")
445 dev[0].wait_disconnected()
446 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
447 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
448
449 logger.info("WPS provisioning step (auth_types=0 encr_types=0)")
450 if "OK" not in dev[0].request("SET wps_force_auth_types 0"):
451 raise Exception("Failed to set wps_force_auth_types 0")
452 if "OK" not in dev[0].request("SET wps_force_encr_types 0"):
453 raise Exception("Failed to set wps_force_encr_types 0")
454 pin = dev[0].wps_read_pin()
455 hapd.request("WPS_PIN any " + pin)
456 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
457 dev[0].dump_monitor()
458 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
459 dev[0].wait_connected(timeout=30)
460 status = dev[0].get_status()
461 dev[0].request("REMOVE_NETWORK all")
462 dev[0].wait_disconnected()
463 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
464 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
465
466 dev[0].request("SET wps_force_auth_types ")
467 dev[0].request("SET wps_force_encr_types ")
468
9fd6804d 469@remote_compatible
6257f9c0
JM
470def test_ap_wps_conf_pin_v1(dev, apdev):
471 """WPS PIN provisioning with configured WPS v1.0 AP"""
472 ssid = "test-wps-conf-pin-v1"
6f334bf7 473 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
474 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
475 "wpa_passphrase": "12345678", "wpa": "2",
476 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
6257f9c0
JM
477 logger.info("WPS provisioning step")
478 pin = dev[0].wps_read_pin()
479 hapd.request("SET wps_version_number 0x10")
480 hapd.request("WPS_PIN any " + pin)
481 found = False
482 for i in range(0, 10):
483 dev[0].scan(freq="2412")
484 if "[WPS-PIN]" in dev[0].request("SCAN_RESULTS"):
485 found = True
486 break
487 if not found:
488 hapd.request("SET wps_version_number 0x20")
489 raise Exception("WPS-PIN flag not seen in scan results")
490 dev[0].dump_monitor()
33d0b157 491 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 492 dev[0].wait_connected(timeout=30)
6257f9c0 493 hapd.request("SET wps_version_number 0x20")
6257f9c0 494
9fd6804d 495@remote_compatible
e9129860
JM
496def test_ap_wps_conf_pin_2sta(dev, apdev):
497 """Two stations trying to use WPS PIN at the same time"""
498 ssid = "test-wps-conf-pin2"
6f334bf7 499 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
500 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
501 "wpa_passphrase": "12345678", "wpa": "2",
502 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e9129860
JM
503 logger.info("WPS provisioning step")
504 pin = "12345670"
505 pin2 = "55554444"
506 hapd.request("WPS_PIN " + dev[0].get_status_field("uuid") + " " + pin)
507 hapd.request("WPS_PIN " + dev[1].get_status_field("uuid") + " " + pin)
e9129860 508 dev[0].dump_monitor()
e9129860 509 dev[1].dump_monitor()
33d0b157
JM
510 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
511 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
512 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
513 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2
JM
514 dev[0].wait_connected(timeout=30)
515 dev[1].wait_connected(timeout=30)
0489e880 516
9fd6804d 517@remote_compatible
0489e880
JM
518def test_ap_wps_conf_pin_timeout(dev, apdev):
519 """WPS PIN provisioning with configured AP timing out PIN"""
520 ssid = "test-wps-conf-pin"
6f334bf7 521 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
522 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
523 "wpa_passphrase": "12345678", "wpa": "2",
524 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
0489e880
JM
525 addr = dev[0].p2p_interface_addr()
526 pin = dev[0].wps_read_pin()
527 if "FAIL" not in hapd.request("WPS_PIN "):
528 raise Exception("Unexpected success on invalid WPS_PIN")
529 hapd.request("WPS_PIN any " + pin + " 1")
33d0b157 530 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
0489e880 531 time.sleep(1.1)
33d0b157 532 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
0489e880
JM
533 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=20)
534 if ev is None:
535 raise Exception("WPS-PIN-NEEDED event timed out")
536 ev = dev[0].wait_event(["WPS-M2D"])
537 if ev is None:
538 raise Exception("M2D not reported")
539 dev[0].request("WPS_CANCEL")
540
541 hapd.request("WPS_PIN any " + pin + " 20 " + addr)
33d0b157 542 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 543 dev[0].wait_connected(timeout=30)
e9129860 544
ae3ad328 545def test_ap_wps_reg_connect(dev, apdev):
302b7a1b 546 """WPS registrar using AP PIN to connect"""
803edd1c 547 ssid = "test-wps-reg-ap-pin"
302b7a1b 548 appin = "12345670"
8b8a1864 549 hostapd.add_ap(apdev[0],
fab49f61
JM
550 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
551 "wpa_passphrase": "12345678", "wpa": "2",
552 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
553 "ap_pin": appin})
302b7a1b 554 logger.info("WPS provisioning step")
302b7a1b 555 dev[0].dump_monitor()
41532439 556 dev[0].flush_scan_cache()
33d0b157 557 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 558 dev[0].wps_reg(apdev[0]['bssid'], appin)
302b7a1b 559 status = dev[0].get_status()
ae3ad328 560 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
561 raise Exception("Not fully connected")
562 if status['ssid'] != ssid:
563 raise Exception("Unexpected SSID")
564 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
565 raise Exception("Unexpected encryption configuration")
566 if status['key_mgmt'] != 'WPA2-PSK':
567 raise Exception("Unexpected key_mgmt")
568
d33222d1
JM
569def test_ap_wps_reg_connect_zero_len_ap_pin(dev, apdev):
570 """hostapd with zero length ap_pin parameter"""
571 ssid = "test-wps-reg-ap-pin"
572 appin = ""
573 hostapd.add_ap(apdev[0],
fab49f61
JM
574 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
575 "wpa_passphrase": "12345678", "wpa": "2",
576 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
577 "ap_pin": appin})
d33222d1
JM
578 logger.info("WPS provisioning step")
579 dev[0].dump_monitor()
41532439 580 dev[0].flush_scan_cache()
d33222d1
JM
581 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
582 dev[0].wps_reg(apdev[0]['bssid'], appin, no_wait=True)
583 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
584 if ev is None:
585 raise Exception("No WPS-FAIL reported")
586 if "msg=5 config_error=15" not in ev:
587 raise Exception("Unexpected WPS-FAIL: " + ev)
588
e60be3b3
JM
589def test_ap_wps_reg_connect_mixed_mode(dev, apdev):
590 """WPS registrar using AP PIN to connect (WPA+WPA2)"""
591 ssid = "test-wps-reg-ap-pin"
592 appin = "12345670"
8b8a1864 593 hostapd.add_ap(apdev[0],
fab49f61
JM
594 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
595 "wpa_passphrase": "12345678", "wpa": "3",
596 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
597 "wpa_pairwise": "TKIP", "ap_pin": appin})
41532439 598 dev[0].flush_scan_cache()
e60be3b3
JM
599 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
600 dev[0].wps_reg(apdev[0]['bssid'], appin)
601 status = dev[0].get_status()
602 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
603 raise Exception("Not fully connected")
604 if status['ssid'] != ssid:
605 raise Exception("Unexpected SSID")
606 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
607 raise Exception("Unexpected encryption configuration")
608 if status['key_mgmt'] != 'WPA2-PSK':
609 raise Exception("Unexpected key_mgmt")
610
7511ead0
JM
611def test_ap_wps_reg_override_ap_settings(dev, apdev):
612 """WPS registrar and ap_settings override"""
613 ap_settings = "/tmp/ap_wps_reg_override_ap_settings"
614 try:
615 os.remove(ap_settings)
616 except:
617 pass
618 # Override AP Settings with values that point to another AP
15dfcb69
MH
619 data = build_wsc_attr(ATTR_NETWORK_INDEX, b'\x01')
620 data += build_wsc_attr(ATTR_SSID, b"test")
621 data += build_wsc_attr(ATTR_AUTH_TYPE, b'\x00\x01')
622 data += build_wsc_attr(ATTR_ENCR_TYPE, b'\x00\x01')
623 data += build_wsc_attr(ATTR_NETWORK_KEY, b'')
7511ead0 624 data += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[1]['bssid'].replace(':', '')))
4aa2336e 625 with open(ap_settings, "wb") as f:
7511ead0
JM
626 f.write(data)
627 ssid = "test-wps-reg-ap-pin"
628 appin = "12345670"
8b8a1864 629 hostapd.add_ap(apdev[0],
fab49f61
JM
630 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
631 "wpa_passphrase": "12345678", "wpa": "2",
632 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
633 "ap_pin": appin, "ap_settings": ap_settings})
634 hapd2 = hostapd.add_ap(apdev[1], {"ssid": "test"})
41532439 635 dev[0].flush_scan_cache()
7511ead0
JM
636 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
637 dev[0].scan_for_bss(apdev[1]['bssid'], freq=2412)
638 dev[0].wps_reg(apdev[0]['bssid'], appin)
639 ev = hapd2.wait_event(['AP-STA-CONNECTED'], timeout=10)
640 os.remove(ap_settings)
641 if ev is None:
642 raise Exception("No connection with the other AP")
643
9488858f
JM
644def check_wps_reg_failure(dev, ap, appin):
645 dev.request("WPS_REG " + ap['bssid'] + " " + appin)
646 ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
647 if ev is None:
648 raise Exception("WPS operation timed out")
649 if "WPS-SUCCESS" in ev:
650 raise Exception("WPS operation succeeded unexpectedly")
651 if "config_error=15" not in ev:
652 raise Exception("WPS setup locked state was not reported correctly")
653
e4357b19
JM
654def test_ap_wps_random_ap_pin(dev, apdev):
655 """WPS registrar using random AP PIN"""
656 ssid = "test-wps-reg-random-ap-pin"
657 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
fab49f61
JM
658 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
659 "wpa_passphrase": "12345678", "wpa": "2",
660 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
661 "device_name": "Wireless AP", "manufacturer": "Company",
662 "model_name": "WAP", "model_number": "123",
663 "serial_number": "12345", "device_type": "6-0050F204-1",
664 "os_version": "01020300",
665 "config_methods": "label push_button",
666 "uuid": ap_uuid, "upnp_iface": "lo"}
6f334bf7 667 hapd = hostapd.add_ap(apdev[0], params)
e4357b19
JM
668 appin = hapd.request("WPS_AP_PIN random")
669 if "FAIL" in appin:
670 raise Exception("Could not generate random AP PIN")
671 if appin not in hapd.request("WPS_AP_PIN get"):
672 raise Exception("Could not fetch current AP PIN")
673 logger.info("WPS provisioning step")
41532439 674 dev[0].flush_scan_cache()
33d0b157 675 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
e4357b19
JM
676 dev[0].wps_reg(apdev[0]['bssid'], appin)
677
678 hapd.request("WPS_AP_PIN disable")
679 logger.info("WPS provisioning step with AP PIN disabled")
33d0b157 680 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
9488858f
JM
681 check_wps_reg_failure(dev[1], apdev[0], appin)
682
683 logger.info("WPS provisioning step with AP PIN reset")
684 appin = "12345670"
685 hapd.request("WPS_AP_PIN set " + appin)
686 dev[1].wps_reg(apdev[0]['bssid'], appin)
687 dev[0].request("REMOVE_NETWORK all")
688 dev[1].request("REMOVE_NETWORK all")
5f35a5e2
JM
689 dev[0].wait_disconnected(timeout=10)
690 dev[1].wait_disconnected(timeout=10)
9488858f
JM
691
692 logger.info("WPS provisioning step after AP PIN timeout")
693 hapd.request("WPS_AP_PIN disable")
694 appin = hapd.request("WPS_AP_PIN random 1")
695 time.sleep(1.1)
696 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
697 raise Exception("AP PIN unexpectedly still enabled")
698 check_wps_reg_failure(dev[0], apdev[0], appin)
699
700 logger.info("WPS provisioning step after AP PIN timeout(2)")
701 hapd.request("WPS_AP_PIN disable")
702 appin = "12345670"
703 hapd.request("WPS_AP_PIN set " + appin + " 1")
704 time.sleep(1.1)
705 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
706 raise Exception("AP PIN unexpectedly still enabled")
707 check_wps_reg_failure(dev[1], apdev[0], appin)
e4357b19 708
24b7f282 709 with fail_test(hapd, 1, "os_get_random;wps_generate_pin"):
20c48fd9 710 hapd.request("WPS_AP_PIN random 1")
24b7f282
JM
711 hapd.request("WPS_AP_PIN disable")
712
713 with alloc_fail(hapd, 1, "upnp_wps_set_ap_pin"):
714 hapd.request("WPS_AP_PIN set 12345670")
715 hapd.request("WPS_AP_PIN disable")
716
82358a2a
JM
717 if "FAIL" not in hapd.request("WPS_AP_PIN set"):
718 raise Exception("Invalid WPS_AP_PIN accepted")
719 if "FAIL" not in hapd.request("WPS_AP_PIN foo"):
720 raise Exception("Invalid WPS_AP_PIN accepted")
721
ae3ad328 722def test_ap_wps_reg_config(dev, apdev):
4b727c5c 723 """WPS registrar configuring an AP using AP PIN"""
302b7a1b
JM
724 ssid = "test-wps-init-ap-pin"
725 appin = "12345670"
8b8a1864 726 hostapd.add_ap(apdev[0],
fab49f61
JM
727 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
728 "ap_pin": appin})
302b7a1b 729 logger.info("WPS configuration step")
41532439 730 dev[0].flush_scan_cache()
33d0b157 731 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
302b7a1b
JM
732 dev[0].dump_monitor()
733 new_ssid = "wps-new-ssid"
734 new_passphrase = "1234567890"
6edaee9c
JM
735 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
736 new_passphrase)
302b7a1b 737 status = dev[0].get_status()
ae3ad328 738 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
739 raise Exception("Not fully connected")
740 if status['ssid'] != new_ssid:
741 raise Exception("Unexpected SSID")
742 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
743 raise Exception("Unexpected encryption configuration")
744 if status['key_mgmt'] != 'WPA2-PSK':
745 raise Exception("Unexpected key_mgmt")
746
375afd7c
JM
747 logger.info("Re-configure back to open")
748 dev[0].request("REMOVE_NETWORK all")
243dcc4a 749 dev[0].flush_scan_cache()
375afd7c
JM
750 dev[0].dump_monitor()
751 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-open", "OPEN", "NONE", "")
752 status = dev[0].get_status()
753 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
754 raise Exception("Not fully connected")
755 if status['ssid'] != "wps-open":
756 raise Exception("Unexpected SSID")
757 if status['key_mgmt'] != 'NONE':
758 raise Exception("Unexpected key_mgmt")
759
4b727c5c
JM
760def test_ap_wps_reg_config_ext_processing(dev, apdev):
761 """WPS registrar configuring an AP with external config processing"""
762 ssid = "test-wps-init-ap-pin"
763 appin = "12345670"
fab49f61
JM
764 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
765 "wps_cred_processing": "1", "ap_pin": appin}
8b8a1864 766 hapd = hostapd.add_ap(apdev[0], params)
41532439 767 dev[0].flush_scan_cache()
33d0b157 768 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
4b727c5c
JM
769 new_ssid = "wps-new-ssid"
770 new_passphrase = "1234567890"
771 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
772 new_passphrase, no_wait=True)
773 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
774 if ev is None:
775 raise Exception("WPS registrar operation timed out")
776 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=15)
777 if ev is None:
778 raise Exception("WPS configuration timed out")
779 if "1026" not in ev:
780 raise Exception("AP Settings missing from event")
781 hapd.request("SET wps_cred_processing 0")
54c58f29 782 if "FAIL" in hapd.request("WPS_CONFIG " + binascii.hexlify(new_ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(new_passphrase.encode()).decode()):
4b727c5c 783 raise Exception("WPS_CONFIG command failed")
5f35a5e2 784 dev[0].wait_connected(timeout=15)
4b727c5c 785
eeefe187
JM
786def test_ap_wps_reg_config_tkip(dev, apdev):
787 """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
a1eabc74 788 skip_with_fips(dev[0])
eeefe187
JM
789 ssid = "test-wps-init-ap"
790 appin = "12345670"
8b8a1864 791 hostapd.add_ap(apdev[0],
fab49f61
JM
792 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
793 "ap_pin": appin})
eeefe187 794 logger.info("WPS configuration step")
41532439 795 dev[0].flush_scan_cache()
eeefe187 796 dev[0].request("SET wps_version_number 0x10")
33d0b157 797 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
eeefe187
JM
798 dev[0].dump_monitor()
799 new_ssid = "wps-new-ssid-with-tkip"
800 new_passphrase = "1234567890"
801 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
802 new_passphrase)
803 logger.info("Re-connect to verify WPA2 mixed mode")
804 dev[0].request("DISCONNECT")
805 id = 0
806 dev[0].set_network(id, "pairwise", "CCMP")
807 dev[0].set_network(id, "proto", "RSN")
808 dev[0].connect_network(id)
809 status = dev[0].get_status()
810 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
3c086180 811 raise Exception("Not fully connected: wpa_state={} bssid={}".format(status['wpa_state'], status['bssid']))
eeefe187
JM
812 if status['ssid'] != new_ssid:
813 raise Exception("Unexpected SSID")
814 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
815 raise Exception("Unexpected encryption configuration")
816 if status['key_mgmt'] != 'WPA2-PSK':
817 raise Exception("Unexpected key_mgmt")
818
6645ff50
JM
819def test_ap_wps_setup_locked(dev, apdev):
820 """WPS registrar locking up AP setup on AP PIN failures"""
821 ssid = "test-wps-incorrect-ap-pin"
822 appin = "12345670"
6f334bf7 823 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
824 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
825 "wpa_passphrase": "12345678", "wpa": "2",
826 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
827 "ap_pin": appin})
6645ff50
JM
828 new_ssid = "wps-new-ssid-test"
829 new_passphrase = "1234567890"
830
41532439 831 dev[0].flush_scan_cache()
33d0b157 832 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
fab49f61 833 ap_setup_locked = False
6645ff50
JM
834 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
835 dev[0].dump_monitor()
836 logger.info("Try incorrect AP PIN - attempt " + pin)
837 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
838 "CCMP", new_passphrase, no_wait=True)
839 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
840 if ev is None:
841 raise Exception("Timeout on receiving WPS operation failure event")
842 if "CTRL-EVENT-CONNECTED" in ev:
843 raise Exception("Unexpected connection")
844 if "config_error=15" in ev:
845 logger.info("AP Setup Locked")
fab49f61 846 ap_setup_locked = True
6645ff50
JM
847 elif "config_error=18" not in ev:
848 raise Exception("config_error=18 not reported")
5f35a5e2 849 dev[0].wait_disconnected(timeout=10)
6645ff50
JM
850 time.sleep(0.1)
851 if not ap_setup_locked:
852 raise Exception("AP setup was not locked")
24b7f282
JM
853 dev[0].request("WPS_CANCEL")
854 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True,
855 only_new=True)
856 bss = dev[0].get_bss(apdev[0]['bssid'])
857 if 'wps_ap_setup_locked' not in bss or bss['wps_ap_setup_locked'] != '1':
858 logger.info("BSS: " + str(bss))
859 raise Exception("AP Setup Locked not indicated in scan results")
6645ff50 860
d671a420
JM
861 status = hapd.request("WPS_GET_STATUS")
862 if "Last WPS result: Failed" not in status:
863 raise Exception("WPS failure result not shown correctly")
864 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
865 raise Exception("Peer address not shown correctly")
866
6645ff50
JM
867 time.sleep(0.5)
868 dev[0].dump_monitor()
869 logger.info("WPS provisioning step")
870 pin = dev[0].wps_read_pin()
6645ff50 871 hapd.request("WPS_PIN any " + pin)
33d0b157 872 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
6645ff50
JM
873 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
874 if ev is None:
875 raise Exception("WPS success was not reported")
5f35a5e2 876 dev[0].wait_connected(timeout=30)
6645ff50 877
c1cec68b
JM
878 appin = hapd.request("WPS_AP_PIN random")
879 if "FAIL" in appin:
880 raise Exception("Could not generate random AP PIN")
881 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=10)
882 if ev is None:
883 raise Exception("Failed to unlock AP PIN")
884
33c9b8d8
JM
885def test_ap_wps_setup_locked_timeout(dev, apdev):
886 """WPS re-enabling AP PIN after timeout"""
887 ssid = "test-wps-incorrect-ap-pin"
888 appin = "12345670"
6f334bf7 889 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
890 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
891 "wpa_passphrase": "12345678", "wpa": "2",
892 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
893 "ap_pin": appin})
33c9b8d8
JM
894 new_ssid = "wps-new-ssid-test"
895 new_passphrase = "1234567890"
896
41532439 897 dev[0].flush_scan_cache()
33d0b157 898 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
fab49f61 899 ap_setup_locked = False
33c9b8d8
JM
900 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
901 dev[0].dump_monitor()
902 logger.info("Try incorrect AP PIN - attempt " + pin)
903 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
904 "CCMP", new_passphrase, no_wait=True)
9ed53f5e 905 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"], timeout=15)
33c9b8d8
JM
906 if ev is None:
907 raise Exception("Timeout on receiving WPS operation failure event")
908 if "CTRL-EVENT-CONNECTED" in ev:
909 raise Exception("Unexpected connection")
910 if "config_error=15" in ev:
911 logger.info("AP Setup Locked")
fab49f61 912 ap_setup_locked = True
33c9b8d8
JM
913 break
914 elif "config_error=18" not in ev:
915 raise Exception("config_error=18 not reported")
5f35a5e2 916 dev[0].wait_disconnected(timeout=10)
33c9b8d8
JM
917 time.sleep(0.1)
918 if not ap_setup_locked:
919 raise Exception("AP setup was not locked")
33c9b8d8
JM
920 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=80)
921 if ev is None:
922 raise Exception("AP PIN did not get unlocked on 60 second timeout")
923
4c355e3e
JM
924def test_ap_wps_setup_locked_2(dev, apdev):
925 """WPS AP configured for special ap_setup_locked=2 mode"""
926 ssid = "test-wps-ap-pin"
927 appin = "12345670"
fab49f61
JM
928 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
929 "wpa_passphrase": "12345678", "wpa": "2",
930 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
931 "ap_pin": appin, "ap_setup_locked": "2"}
8b8a1864 932 hapd = hostapd.add_ap(apdev[0], params)
4c355e3e
JM
933 new_ssid = "wps-new-ssid-test"
934 new_passphrase = "1234567890"
935
41532439 936 dev[0].flush_scan_cache()
4c355e3e
JM
937 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
938 dev[0].wps_reg(apdev[0]['bssid'], appin)
939 dev[0].request("REMOVE_NETWORK all")
940 dev[0].wait_disconnected()
941
942 hapd.dump_monitor()
943 dev[0].dump_monitor()
944 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK",
945 "CCMP", new_passphrase, no_wait=True)
946
947 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
948 if ev is None:
949 raise Exception("hostapd did not report WPS failure")
950 if "msg=12 config_error=15" not in ev:
951 raise Exception("Unexpected failure reason (AP): " + ev)
952
953 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
954 if ev is None:
955 raise Exception("Timeout on receiving WPS operation failure event")
956 if "CTRL-EVENT-CONNECTED" in ev:
957 raise Exception("Unexpected connection")
958 if "config_error=15" not in ev:
959 raise Exception("Unexpected failure reason (STA): " + ev)
960 dev[0].request("WPS_CANCEL")
961 dev[0].wait_disconnected()
962
ae750570 963def setup_ap_wps_pbc_overlap_2ap(apdev):
fab49f61
JM
964 params = {"ssid": "wps1", "eap_server": "1", "wps_state": "2",
965 "wpa_passphrase": "12345678", "wpa": "2",
966 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
967 "wps_independent": "1"}
6f334bf7 968 hapd = hostapd.add_ap(apdev[0], params)
fab49f61
JM
969 params = {"ssid": "wps2", "eap_server": "1", "wps_state": "2",
970 "wpa_passphrase": "123456789", "wpa": "2",
971 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
972 "wps_independent": "1"}
6f334bf7 973 hapd2 = hostapd.add_ap(apdev[1], params)
302b7a1b 974 hapd.request("WPS_PBC")
302b7a1b 975 hapd2.request("WPS_PBC")
ae750570
JM
976 return hapd, hapd2
977
978@remote_compatible
979def test_ap_wps_pbc_overlap_2ap(dev, apdev):
980 """WPS PBC session overlap with two active APs"""
981 hapd, hapd2 = setup_ap_wps_pbc_overlap_2ap(apdev)
302b7a1b 982 logger.info("WPS provisioning step")
84a40841
JM
983 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
984 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
302b7a1b
JM
985 dev[0].request("WPS_PBC")
986 ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
ae750570
JM
987 hapd.request("DISABLE")
988 hapd2.request("DISABLE")
989 dev[0].flush_scan_cache()
302b7a1b
JM
990 if ev is None:
991 raise Exception("PBC session overlap not detected")
ae750570
JM
992
993@remote_compatible
994def test_ap_wps_pbc_overlap_2ap_specific_bssid(dev, apdev):
995 """WPS PBC session overlap with two active APs (specific BSSID selected)"""
996 hapd, hapd2 = setup_ap_wps_pbc_overlap_2ap(apdev)
997 logger.info("WPS provisioning step")
998 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
999 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
1000 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1001 ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED",
1002 "CTRL-EVENT-CONNECTED"], timeout=15)
1003 dev[0].request("DISCONNECT")
492c3a91
JM
1004 hapd.request("DISABLE")
1005 hapd2.request("DISABLE")
1006 dev[0].flush_scan_cache()
ae750570
JM
1007 if ev is None:
1008 raise Exception("PBC session overlap result not reported")
1009 if "CTRL-EVENT-CONNECTED" not in ev:
1010 raise Exception("Connection did not complete")
302b7a1b 1011
9fd6804d 1012@remote_compatible
ae3ad328 1013def test_ap_wps_pbc_overlap_2sta(dev, apdev):
302b7a1b
JM
1014 """WPS PBC session overlap with two active STAs"""
1015 ssid = "test-wps-pbc-overlap"
6f334bf7 1016 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
1017 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1018 "wpa_passphrase": "12345678", "wpa": "2",
1019 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
302b7a1b
JM
1020 logger.info("WPS provisioning step")
1021 hapd.request("WPS_PBC")
33d0b157 1022 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 1023 dev[0].dump_monitor()
33d0b157 1024 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 1025 dev[1].dump_monitor()
33d0b157
JM
1026 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1027 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
302b7a1b
JM
1028 ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
1029 if ev is None:
1030 raise Exception("PBC session overlap not detected (dev0)")
1031 if "config_error=12" not in ev:
1032 raise Exception("PBC session overlap not correctly reported (dev0)")
492c3a91
JM
1033 dev[0].request("WPS_CANCEL")
1034 dev[0].request("DISCONNECT")
302b7a1b
JM
1035 ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
1036 if ev is None:
1037 raise Exception("PBC session overlap not detected (dev1)")
1038 if "config_error=12" not in ev:
1039 raise Exception("PBC session overlap not correctly reported (dev1)")
492c3a91
JM
1040 dev[1].request("WPS_CANCEL")
1041 dev[1].request("DISCONNECT")
11e7eeba
JM
1042 hapd.request("WPS_CANCEL")
1043 ret = hapd.request("WPS_PBC")
1044 if "FAIL" not in ret:
1045 raise Exception("PBC mode allowed to be started while PBC overlap still active")
492c3a91
JM
1046 hapd.request("DISABLE")
1047 dev[0].flush_scan_cache()
1048 dev[1].flush_scan_cache()
6edaee9c 1049
9fd6804d 1050@remote_compatible
71afe834
JM
1051def test_ap_wps_cancel(dev, apdev):
1052 """WPS AP cancelling enabled config method"""
1053 ssid = "test-wps-ap-cancel"
6f334bf7 1054 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
1055 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1056 "wpa_passphrase": "12345678", "wpa": "2",
1057 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
71afe834 1058 bssid = apdev[0]['bssid']
71afe834
JM
1059
1060 logger.info("Verify PBC enable/cancel")
1061 hapd.request("WPS_PBC")
71afe834 1062 dev[0].scan(freq="2412")
84a40841 1063 dev[0].scan(freq="2412")
71afe834
JM
1064 bss = dev[0].get_bss(apdev[0]['bssid'])
1065 if "[WPS-PBC]" not in bss['flags']:
1066 raise Exception("WPS-PBC flag missing")
1067 if "FAIL" in hapd.request("WPS_CANCEL"):
1068 raise Exception("WPS_CANCEL failed")
1069 dev[0].scan(freq="2412")
84a40841 1070 dev[0].scan(freq="2412")
71afe834
JM
1071 bss = dev[0].get_bss(apdev[0]['bssid'])
1072 if "[WPS-PBC]" in bss['flags']:
1073 raise Exception("WPS-PBC flag not cleared")
1074
1075 logger.info("Verify PIN enable/cancel")
1076 hapd.request("WPS_PIN any 12345670")
1077 dev[0].scan(freq="2412")
84a40841 1078 dev[0].scan(freq="2412")
71afe834
JM
1079 bss = dev[0].get_bss(apdev[0]['bssid'])
1080 if "[WPS-AUTH]" not in bss['flags']:
1081 raise Exception("WPS-AUTH flag missing")
1082 if "FAIL" in hapd.request("WPS_CANCEL"):
1083 raise Exception("WPS_CANCEL failed")
1084 dev[0].scan(freq="2412")
84a40841 1085 dev[0].scan(freq="2412")
71afe834
JM
1086 bss = dev[0].get_bss(apdev[0]['bssid'])
1087 if "[WPS-AUTH]" in bss['flags']:
1088 raise Exception("WPS-AUTH flag not cleared")
1089
6edaee9c
JM
1090def test_ap_wps_er_add_enrollee(dev, apdev):
1091 """WPS ER configuring AP and adding a new enrollee using PIN"""
be9f1562
JM
1092 try:
1093 _test_ap_wps_er_add_enrollee(dev, apdev)
1094 finally:
1095 dev[0].request("WPS_ER_STOP")
1096
1097def _test_ap_wps_er_add_enrollee(dev, apdev):
6edaee9c
JM
1098 ssid = "wps-er-add-enrollee"
1099 ap_pin = "12345670"
1100 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1101 hostapd.add_ap(apdev[0],
fab49f61
JM
1102 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
1103 "device_name": "Wireless AP", "manufacturer": "Company",
1104 "model_name": "WAP", "model_number": "123",
1105 "serial_number": "12345", "device_type": "6-0050F204-1",
1106 "os_version": "01020300",
1107 'friendly_name': "WPS AP - <>&'\" - TEST",
1108 "config_methods": "label push_button",
1109 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
6edaee9c
JM
1110 logger.info("WPS configuration step")
1111 new_passphrase = "1234567890"
1112 dev[0].dump_monitor()
41532439 1113 dev[0].flush_scan_cache()
33d0b157 1114 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c
JM
1115 dev[0].wps_reg(apdev[0]['bssid'], ap_pin, ssid, "WPA2PSK", "CCMP",
1116 new_passphrase)
1117 status = dev[0].get_status()
1118 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1119 raise Exception("Not fully connected")
1120 if status['ssid'] != ssid:
1121 raise Exception("Unexpected SSID")
1122 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
1123 raise Exception("Unexpected encryption configuration")
1124 if status['key_mgmt'] != 'WPA2-PSK':
1125 raise Exception("Unexpected key_mgmt")
1126
1127 logger.info("Start ER")
1128 dev[0].request("WPS_ER_START ifname=lo")
1129 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1130 if ev is None:
1131 raise Exception("AP discovery timed out")
1132 if ap_uuid not in ev:
1133 raise Exception("Expected AP UUID not found")
24b7f282
JM
1134 if "|WPS AP - &lt;&gt;&amp;&apos;&quot; - TEST|Company|" not in ev:
1135 raise Exception("Expected friendly name not found")
6edaee9c
JM
1136
1137 logger.info("Learn AP configuration through UPnP")
1138 dev[0].dump_monitor()
1139 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1140 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1141 if ev is None:
1142 raise Exception("AP learn timed out")
1143 if ap_uuid not in ev:
1144 raise Exception("Expected AP UUID not in settings")
1145 if "ssid=" + ssid not in ev:
1146 raise Exception("Expected SSID not in settings")
1147 if "key=" + new_passphrase not in ev:
1148 raise Exception("Expected passphrase not in settings")
33d0b157
JM
1149 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1150 if ev is None:
1151 raise Exception("WPS-FAIL after AP learn timed out")
1152 time.sleep(0.1)
6edaee9c
JM
1153
1154 logger.info("Add Enrollee using ER")
1155 pin = dev[1].wps_read_pin()
1156 dev[0].dump_monitor()
1157 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
33d0b157 1158 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 1159 dev[1].dump_monitor()
33d0b157 1160 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
846be889 1161 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
6edaee9c
JM
1162 if ev is None:
1163 raise Exception("Enrollee did not report success")
5f35a5e2 1164 dev[1].wait_connected(timeout=15)
6edaee9c
JM
1165 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1166 if ev is None:
1167 raise Exception("WPS ER did not report success")
1168 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1169
11c26f1b
JM
1170 logger.info("Add a specific Enrollee using ER")
1171 pin = dev[2].wps_read_pin()
1172 addr2 = dev[2].p2p_interface_addr()
1173 dev[0].dump_monitor()
33d0b157 1174 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
11c26f1b 1175 dev[2].dump_monitor()
33d0b157 1176 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
11c26f1b
JM
1177 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1178 if ev is None:
1179 raise Exception("Enrollee not seen")
1180 if addr2 not in ev:
1181 raise Exception("Unexpected Enrollee MAC address")
1182 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
5f35a5e2 1183 dev[2].wait_connected(timeout=30)
11c26f1b
JM
1184 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1185 if ev is None:
1186 raise Exception("WPS ER did not report success")
1187
38ae43de
JM
1188 logger.info("Verify registrar selection behavior")
1189 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1190 dev[1].request("DISCONNECT")
5f35a5e2 1191 dev[1].wait_disconnected(timeout=10)
84a40841 1192 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
38ae43de
JM
1193 dev[1].scan(freq="2412")
1194 bss = dev[1].get_bss(apdev[0]['bssid'])
1195 if "[WPS-AUTH]" not in bss['flags']:
321c7f60
JM
1196 # It is possible for scan to miss an update especially when running
1197 # tests under load with multiple VMs, so allow another attempt.
1198 dev[1].scan(freq="2412")
1199 bss = dev[1].get_bss(apdev[0]['bssid'])
1200 if "[WPS-AUTH]" not in bss['flags']:
1201 raise Exception("WPS-AUTH flag missing")
38ae43de
JM
1202
1203 logger.info("Stop ER")
1204 dev[0].dump_monitor()
1205 dev[0].request("WPS_ER_STOP")
1206 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
1207 if ev is None:
1208 raise Exception("WPS ER unsubscription timed out")
8697cbc0 1209 # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
befd671c 1210 # a bit before verifying that the scan results have changed.
8697cbc0 1211 time.sleep(0.2)
38ae43de 1212
befd671c
JM
1213 for i in range(0, 10):
1214 dev[1].request("BSS_FLUSH 0")
1215 dev[1].scan(freq="2412", only_new=True)
1216 bss = dev[1].get_bss(apdev[0]['bssid'])
1217 if bss and 'flags' in bss and "[WPS-AUTH]" not in bss['flags']:
1218 break
1219 logger.debug("WPS-AUTH flag was still in place - wait a bit longer")
1220 time.sleep(0.1)
38ae43de
JM
1221 if "[WPS-AUTH]" in bss['flags']:
1222 raise Exception("WPS-AUTH flag not removed")
1223
c965ae03
JM
1224def test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1225 """WPS ER adding a new enrollee identified by UUID"""
1226 try:
1227 _test_ap_wps_er_add_enrollee_uuid(dev, apdev)
1228 finally:
1229 dev[0].request("WPS_ER_STOP")
1230
1231def _test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1232 ssid = "wps-er-add-enrollee"
1233 ap_pin = "12345670"
1234 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1235 hostapd.add_ap(apdev[0],
fab49f61
JM
1236 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1237 "wpa_passphrase": "12345678", "wpa": "2",
1238 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1239 "device_name": "Wireless AP", "manufacturer": "Company",
1240 "model_name": "WAP", "model_number": "123",
1241 "serial_number": "12345", "device_type": "6-0050F204-1",
1242 "os_version": "01020300",
1243 "config_methods": "label push_button",
1244 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
c965ae03 1245 logger.info("WPS configuration step")
41532439 1246 dev[0].flush_scan_cache()
c965ae03
JM
1247 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1248 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1249
1250 logger.info("Start ER")
1251 dev[0].request("WPS_ER_START ifname=lo")
1252 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1253 if ev is None:
1254 raise Exception("AP discovery timed out")
1255 if ap_uuid not in ev:
1256 raise Exception("Expected AP UUID not found")
1257
1258 logger.info("Learn AP configuration through UPnP")
1259 dev[0].dump_monitor()
1260 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1261 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1262 if ev is None:
1263 raise Exception("AP learn timed out")
1264 if ap_uuid not in ev:
1265 raise Exception("Expected AP UUID not in settings")
1266 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1267 if ev is None:
1268 raise Exception("WPS-FAIL after AP learn timed out")
1269 time.sleep(0.1)
1270
1271 logger.info("Add a specific Enrollee using ER (PBC/UUID)")
1272 addr1 = dev[1].p2p_interface_addr()
1273 dev[0].dump_monitor()
1274 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1275 dev[1].dump_monitor()
1276 dev[1].request("WPS_PBC %s" % apdev[0]['bssid'])
1277 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1278 if ev is None:
1279 raise Exception("Enrollee not seen")
1280 if addr1 not in ev:
1281 raise Exception("Unexpected Enrollee MAC address")
1282 uuid = ev.split(' ')[1]
1283 dev[0].request("WPS_ER_PBC " + uuid)
1284 dev[1].wait_connected(timeout=30)
1285 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1286 if ev is None:
1287 raise Exception("WPS ER did not report success")
1288
1289 logger.info("Add a specific Enrollee using ER (PIN/UUID)")
1290 pin = dev[2].wps_read_pin()
1291 addr2 = dev[2].p2p_interface_addr()
1292 dev[0].dump_monitor()
1293 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1294 dev[2].dump_monitor()
1295 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1296 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1297 if ev is None:
1298 raise Exception("Enrollee not seen")
1299 if addr2 not in ev:
1300 raise Exception("Unexpected Enrollee MAC address")
1301 uuid = ev.split(' ')[1]
1302 dev[0].request("WPS_ER_PIN " + uuid + " " + pin)
1303 dev[2].wait_connected(timeout=30)
1304 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1305 if ev is None:
1306 raise Exception("WPS ER did not report success")
1307
ea982de1
JM
1308 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-REMOVE"], timeout=15)
1309 if ev is None:
1310 raise Exception("No Enrollee STA entry timeout seen")
1311
c965ae03
JM
1312 logger.info("Stop ER")
1313 dev[0].dump_monitor()
1314 dev[0].request("WPS_ER_STOP")
1315
61c3d464
JM
1316def test_ap_wps_er_multi_add_enrollee(dev, apdev):
1317 """Multiple WPS ERs adding a new enrollee using PIN"""
1318 try:
1319 _test_ap_wps_er_multi_add_enrollee(dev, apdev)
1320 finally:
d887ed3f
JM
1321 for i in range(2):
1322 dev[i].request("WPS_ER_STOP")
61c3d464
JM
1323
1324def _test_ap_wps_er_multi_add_enrollee(dev, apdev):
1325 ssid = "wps-er-add-enrollee"
1326 ap_pin = "12345670"
1327 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1328 hostapd.add_ap(apdev[0],
fab49f61
JM
1329 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1330 "wpa_passphrase": "12345678", "wpa": "2",
1331 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1332 "device_name": "Wireless AP", "manufacturer": "Company",
1333 "model_name": "WAP", "model_number": "123",
1334 "serial_number": "12345", "device_type": "6-0050F204-1",
1335 "os_version": "01020300",
1336 'friendly_name': "WPS AP",
1337 "config_methods": "label push_button",
1338 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
61c3d464
JM
1339
1340 for i in range(2):
41532439 1341 dev[i].flush_scan_cache()
61c3d464
JM
1342 dev[i].scan_for_bss(apdev[0]['bssid'], freq=2412)
1343 dev[i].wps_reg(apdev[0]['bssid'], ap_pin)
6a5f578c 1344 for i in range(2):
61c3d464
JM
1345 dev[i].request("WPS_ER_START ifname=lo")
1346 for i in range(2):
1347 ev = dev[i].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1348 if ev is None:
1349 raise Exception("AP discovery timed out")
1350 dev[i].dump_monitor()
6a5f578c 1351 for i in range(2):
61c3d464 1352 dev[i].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
6a5f578c 1353 for i in range(2):
61c3d464
JM
1354 ev = dev[i].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1355 if ev is None:
1356 raise Exception("AP learn timed out")
1357 ev = dev[i].wait_event(["WPS-FAIL"], timeout=15)
1358 if ev is None:
1359 raise Exception("WPS-FAIL after AP learn timed out")
1360
1361 time.sleep(0.1)
1362
1363 pin = dev[2].wps_read_pin()
1364 addr = dev[2].own_addr()
1365 dev[0].dump_monitor()
1366 dev[0].request("WPS_ER_PIN any " + pin + " " + addr)
1367 dev[1].dump_monitor()
1368 dev[1].request("WPS_ER_PIN any " + pin + " " + addr)
1369
1370 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1371 dev[2].dump_monitor()
1372 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1373 ev = dev[2].wait_event(["WPS-SUCCESS"], timeout=30)
1374 if ev is None:
1375 raise Exception("Enrollee did not report success")
1376 dev[2].wait_connected(timeout=15)
1377
6edaee9c
JM
1378def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1379 """WPS ER connected to AP and adding a new enrollee using PBC"""
be9f1562
JM
1380 try:
1381 _test_ap_wps_er_add_enrollee_pbc(dev, apdev)
1382 finally:
1383 dev[0].request("WPS_ER_STOP")
1384
1385def _test_ap_wps_er_add_enrollee_pbc(dev, apdev):
6edaee9c
JM
1386 ssid = "wps-er-add-enrollee-pbc"
1387 ap_pin = "12345670"
1388 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1389 hostapd.add_ap(apdev[0],
fab49f61
JM
1390 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1391 "wpa_passphrase": "12345678", "wpa": "2",
1392 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1393 "device_name": "Wireless AP", "manufacturer": "Company",
1394 "model_name": "WAP", "model_number": "123",
1395 "serial_number": "12345", "device_type": "6-0050F204-1",
1396 "os_version": "01020300",
1397 "config_methods": "label push_button",
1398 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
6edaee9c 1399 logger.info("Learn AP configuration")
41532439 1400 dev[0].flush_scan_cache()
33d0b157 1401 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 1402 dev[0].dump_monitor()
6edaee9c
JM
1403 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1404 status = dev[0].get_status()
1405 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1406 raise Exception("Not fully connected")
1407
1408 logger.info("Start ER")
1409 dev[0].request("WPS_ER_START ifname=lo")
1410 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1411 if ev is None:
1412 raise Exception("AP discovery timed out")
1413 if ap_uuid not in ev:
1414 raise Exception("Expected AP UUID not found")
1415
d6b916c9
JM
1416 enrollee = dev[1].p2p_interface_addr()
1417
1418 if "FAIL-UNKNOWN-UUID" not in dev[0].request("WPS_ER_PBC " + enrollee):
1419 raise Exception("Unknown UUID not reported")
6edaee9c
JM
1420
1421 logger.info("Add Enrollee using ER and PBC")
1422 dev[0].dump_monitor()
6edaee9c
JM
1423 dev[1].dump_monitor()
1424 dev[1].request("WPS_PBC")
1425
8674c022
JM
1426 for i in range(0, 2):
1427 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1428 if ev is None:
1429 raise Exception("Enrollee discovery timed out")
1430 if enrollee in ev:
1431 break
1432 if i == 1:
1433 raise Exception("Expected Enrollee not found")
d6b916c9
JM
1434 if "FAIL-NO-AP-SETTINGS" not in dev[0].request("WPS_ER_PBC " + enrollee):
1435 raise Exception("Unknown UUID not reported")
1436 logger.info("Use learned network configuration on ER")
1437 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1438 if "OK" not in dev[0].request("WPS_ER_PBC " + enrollee):
1439 raise Exception("WPS_ER_PBC failed")
6edaee9c
JM
1440
1441 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
1442 if ev is None:
1443 raise Exception("Enrollee did not report success")
5f35a5e2 1444 dev[1].wait_connected(timeout=15)
6edaee9c
JM
1445 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1446 if ev is None:
1447 raise Exception("WPS ER did not report success")
1448 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
bff3ac5b 1449
d6b916c9
JM
1450def test_ap_wps_er_pbc_overlap(dev, apdev):
1451 """WPS ER connected to AP and PBC session overlap"""
be9f1562
JM
1452 try:
1453 _test_ap_wps_er_pbc_overlap(dev, apdev)
1454 finally:
1455 dev[0].request("WPS_ER_STOP")
1456
1457def _test_ap_wps_er_pbc_overlap(dev, apdev):
d6b916c9
JM
1458 ssid = "wps-er-add-enrollee-pbc"
1459 ap_pin = "12345670"
1460 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1461 hostapd.add_ap(apdev[0],
fab49f61
JM
1462 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1463 "wpa_passphrase": "12345678", "wpa": "2",
1464 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1465 "device_name": "Wireless AP", "manufacturer": "Company",
1466 "model_name": "WAP", "model_number": "123",
1467 "serial_number": "12345", "device_type": "6-0050F204-1",
1468 "os_version": "01020300",
1469 "config_methods": "label push_button",
1470 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
41532439 1471 dev[0].flush_scan_cache()
d6b916c9
JM
1472 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1473 dev[0].dump_monitor()
1474 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1475
fba25c99
JM
1476 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1477 dev[2].scan_for_bss(apdev[0]['bssid'], freq="2412")
1478 # avoid leaving dev 1 or 2 as the last Probe Request to the AP
1479 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True)
1480
d6b916c9
JM
1481 dev[0].dump_monitor()
1482 dev[0].request("WPS_ER_START ifname=lo")
1483
1484 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1485 if ev is None:
1486 raise Exception("AP discovery timed out")
1487 if ap_uuid not in ev:
1488 raise Exception("Expected AP UUID not found")
1489
800bcf4e
JM
1490 # verify BSSID selection of the AP instead of UUID
1491 if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
1492 raise Exception("Could not select AP based on BSSID")
1493
fba25c99 1494 dev[0].dump_monitor()
d6b916c9
JM
1495 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1496 dev[2].request("WPS_PBC " + apdev[0]['bssid'])
1497 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1498 if ev is None:
1499 raise Exception("PBC scan failed")
1500 ev = dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1501 if ev is None:
1502 raise Exception("PBC scan failed")
fba25c99
JM
1503 found1 = False
1504 found2 = False
1505 addr1 = dev[1].own_addr()
1506 addr2 = dev[2].own_addr()
1507 for i in range(3):
d6b916c9
JM
1508 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1509 if ev is None:
1510 raise Exception("Enrollee discovery timed out")
fba25c99
JM
1511 if addr1 in ev:
1512 found1 = True
1513 if found2:
1514 break
1515 if addr2 in ev:
1516 found2 = True
1517 if found1:
1518 break
d6b916c9
JM
1519 if dev[0].request("WPS_ER_PBC " + ap_uuid) != "FAIL-PBC-OVERLAP\n":
1520 raise Exception("PBC overlap not reported")
1521 dev[1].request("WPS_CANCEL")
1522 dev[2].request("WPS_CANCEL")
1523 if dev[0].request("WPS_ER_PBC foo") != "FAIL\n":
1524 raise Exception("Invalid WPS_ER_PBC accepted")
1525
1f020f5e
JM
1526def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1527 """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
be9f1562
JM
1528 try:
1529 _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev)
1530 finally:
1531 dev[0].request("WPS_ER_STOP")
1532
1533def _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1f020f5e
JM
1534 ssid = "wps-er-add-enrollee-pbc"
1535 ap_pin = "12345670"
1536 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1537 hostapd.add_ap(apdev[0],
fab49f61
JM
1538 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1539 "wpa_passphrase": "12345678", "wpa": "2",
1540 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1541 "device_name": "Wireless AP", "manufacturer": "Company",
1542 "model_name": "WAP", "model_number": "123",
1543 "serial_number": "12345", "device_type": "6-0050F204-1",
1544 "os_version": "01020300",
1545 "config_methods": "label push_button",
1546 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1f020f5e
JM
1547 logger.info("Learn AP configuration")
1548 dev[0].request("SET wps_version_number 0x10")
41532439 1549 dev[0].flush_scan_cache()
33d0b157 1550 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1f020f5e
JM
1551 dev[0].dump_monitor()
1552 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1553 status = dev[0].get_status()
1554 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1555 raise Exception("Not fully connected")
1556
1557 logger.info("Start ER")
1558 dev[0].request("WPS_ER_START ifname=lo")
1559 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1560 if ev is None:
1561 raise Exception("AP discovery timed out")
1562 if ap_uuid not in ev:
1563 raise Exception("Expected AP UUID not found")
1564
1565 logger.info("Use learned network configuration on ER")
1566 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1567
1568 logger.info("Add Enrollee using ER and PIN")
1569 enrollee = dev[1].p2p_interface_addr()
1570 pin = dev[1].wps_read_pin()
1571 dev[0].dump_monitor()
1572 dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
33d0b157 1573 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1f020f5e 1574 dev[1].dump_monitor()
33d0b157 1575 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 1576 dev[1].wait_connected(timeout=30)
1f020f5e
JM
1577 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1578 if ev is None:
1579 raise Exception("WPS ER did not report success")
1580
9fd6804d 1581@remote_compatible
be923570
JM
1582def test_ap_wps_er_config_ap(dev, apdev):
1583 """WPS ER configuring AP over UPnP"""
be9f1562
JM
1584 try:
1585 _test_ap_wps_er_config_ap(dev, apdev)
1586 finally:
1587 dev[0].request("WPS_ER_STOP")
1588
1589def _test_ap_wps_er_config_ap(dev, apdev):
be923570
JM
1590 ssid = "wps-er-ap-config"
1591 ap_pin = "12345670"
1592 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1593 hostapd.add_ap(apdev[0],
fab49f61
JM
1594 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1595 "wpa_passphrase": "12345678", "wpa": "2",
1596 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1597 "device_name": "Wireless AP", "manufacturer": "Company",
1598 "model_name": "WAP", "model_number": "123",
1599 "serial_number": "12345", "device_type": "6-0050F204-1",
1600 "os_version": "01020300",
1601 "config_methods": "label push_button",
1602 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
be923570
JM
1603
1604 logger.info("Connect ER to the AP")
1605 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
1606
1607 logger.info("WPS configuration step")
1608 dev[0].request("WPS_ER_START ifname=lo")
1609 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1610 if ev is None:
1611 raise Exception("AP discovery timed out")
1612 if ap_uuid not in ev:
1613 raise Exception("Expected AP UUID not found")
1614 new_passphrase = "1234567890"
1615 dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
54c58f29
MH
1616 binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " +
1617 binascii.hexlify(new_passphrase.encode()).decode())
be923570
JM
1618 ev = dev[0].wait_event(["WPS-SUCCESS"])
1619 if ev is None:
1620 raise Exception("WPS ER configuration operation timed out")
5f35a5e2 1621 dev[0].wait_disconnected(timeout=10)
be923570
JM
1622 dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
1623
8f8c2fe8
JM
1624 logger.info("WPS ER restart")
1625 dev[0].request("WPS_ER_START")
1626 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1627 if ev is None:
1628 raise Exception("AP discovery timed out on ER restart")
1629 if ap_uuid not in ev:
1630 raise Exception("Expected AP UUID not found on ER restart")
1631 if "OK" not in dev[0].request("WPS_ER_STOP"):
1632 raise Exception("WPS_ER_STOP failed")
1633 if "OK" not in dev[0].request("WPS_ER_STOP"):
1634 raise Exception("WPS_ER_STOP failed")
1635
9fd6804d 1636@remote_compatible
6aaa661a
JM
1637def test_ap_wps_er_cache_ap_settings(dev, apdev):
1638 """WPS ER caching AP settings"""
1639 try:
1640 _test_ap_wps_er_cache_ap_settings(dev, apdev)
1641 finally:
1642 dev[0].request("WPS_ER_STOP")
1643
1644def _test_ap_wps_er_cache_ap_settings(dev, apdev):
1645 ssid = "wps-er-add-enrollee"
1646 ap_pin = "12345670"
1647 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
fab49f61
JM
1648 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1649 "wpa_passphrase": "12345678", "wpa": "2",
1650 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1651 "device_name": "Wireless AP", "manufacturer": "Company",
1652 "model_name": "WAP", "model_number": "123",
1653 "serial_number": "12345", "device_type": "6-0050F204-1",
1654 "os_version": "01020300",
1655 "config_methods": "label push_button",
1656 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
8b8a1864 1657 hapd = hostapd.add_ap(apdev[0], params)
41532439 1658 dev[0].flush_scan_cache()
6aaa661a
JM
1659 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1660 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1661 id = int(dev[0].list_networks()[0]['id'])
1662 dev[0].set_network(id, "scan_freq", "2412")
1663
1664 dev[0].request("WPS_ER_START ifname=lo")
1665 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1666 if ev is None:
1667 raise Exception("AP discovery timed out")
1668 if ap_uuid not in ev:
1669 raise Exception("Expected AP UUID not found")
1670
1671 dev[0].dump_monitor()
1672 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1673 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1674 if ev is None:
1675 raise Exception("AP learn timed out")
1676 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1677 if ev is None:
1678 raise Exception("WPS-FAIL after AP learn timed out")
1679 time.sleep(0.1)
1680
1681 hapd.disable()
1682
1683 for i in range(2):
fab49f61 1684 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE", "CTRL-EVENT-DISCONNECTED"],
6aaa661a
JM
1685 timeout=15)
1686 if ev is None:
1687 raise Exception("AP removal or disconnection timed out")
1688
8b8a1864 1689 hapd = hostapd.add_ap(apdev[0], params)
6aaa661a 1690 for i in range(2):
fab49f61 1691 ev = dev[0].wait_event(["WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED"],
6aaa661a
JM
1692 timeout=15)
1693 if ev is None:
1694 raise Exception("AP discovery or connection timed out")
1695
1696 pin = dev[1].wps_read_pin()
1697 dev[0].dump_monitor()
1698 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1699
1700 time.sleep(0.2)
1701
1702 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1703 dev[1].dump_monitor()
1704 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1705 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
1706 if ev is None:
1707 raise Exception("Enrollee did not report success")
1708 dev[1].wait_connected(timeout=15)
1709 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1710 if ev is None:
1711 raise Exception("WPS ER did not report success")
1712
1713 dev[0].dump_monitor()
1714 dev[0].request("WPS_ER_STOP")
1715
d840350a
JM
1716def test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1717 """WPS ER caching AP settings (OOM)"""
1718 try:
1719 _test_ap_wps_er_cache_ap_settings_oom(dev, apdev)
1720 finally:
1721 dev[0].request("WPS_ER_STOP")
1722
1723def _test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1724 ssid = "wps-er-add-enrollee"
1725 ap_pin = "12345670"
1726 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
fab49f61
JM
1727 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1728 "wpa_passphrase": "12345678", "wpa": "2",
1729 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1730 "device_name": "Wireless AP", "manufacturer": "Company",
1731 "model_name": "WAP", "model_number": "123",
1732 "serial_number": "12345", "device_type": "6-0050F204-1",
1733 "os_version": "01020300",
1734 "config_methods": "label push_button",
1735 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
8b8a1864 1736 hapd = hostapd.add_ap(apdev[0], params)
41532439 1737 dev[0].flush_scan_cache()
d840350a
JM
1738 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1739 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1740 id = int(dev[0].list_networks()[0]['id'])
1741 dev[0].set_network(id, "scan_freq", "2412")
1742
1743 dev[0].request("WPS_ER_START ifname=lo")
1744 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1745 if ev is None:
1746 raise Exception("AP discovery timed out")
1747 if ap_uuid not in ev:
1748 raise Exception("Expected AP UUID not found")
1749
1750 dev[0].dump_monitor()
1751 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1752 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1753 if ev is None:
1754 raise Exception("AP learn timed out")
1755 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1756 if ev is None:
1757 raise Exception("WPS-FAIL after AP learn timed out")
1758 time.sleep(0.1)
1759
1760 with alloc_fail(dev[0], 1, "=wps_er_ap_use_cached_settings"):
1761 hapd.disable()
1762
1763 for i in range(2):
fab49f61
JM
1764 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE",
1765 "CTRL-EVENT-DISCONNECTED"],
d840350a
JM
1766 timeout=15)
1767 if ev is None:
1768 raise Exception("AP removal or disconnection timed out")
1769
8b8a1864 1770 hapd = hostapd.add_ap(apdev[0], params)
d840350a 1771 for i in range(2):
fab49f61 1772 ev = dev[0].wait_event(["WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED"],
d840350a
JM
1773 timeout=15)
1774 if ev is None:
1775 raise Exception("AP discovery or connection timed out")
1776
1777 dev[0].request("WPS_ER_STOP")
1778
1779def test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1780 """WPS ER caching AP settings (OOM 2)"""
1781 try:
1782 _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev)
1783 finally:
1784 dev[0].request("WPS_ER_STOP")
1785
1786def _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1787 ssid = "wps-er-add-enrollee"
1788 ap_pin = "12345670"
1789 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
fab49f61
JM
1790 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1791 "wpa_passphrase": "12345678", "wpa": "2",
1792 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1793 "device_name": "Wireless AP", "manufacturer": "Company",
1794 "model_name": "WAP", "model_number": "123",
1795 "serial_number": "12345", "device_type": "6-0050F204-1",
1796 "os_version": "01020300",
1797 "config_methods": "label push_button",
1798 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
8b8a1864 1799 hapd = hostapd.add_ap(apdev[0], params)
41532439 1800 dev[0].flush_scan_cache()
d840350a
JM
1801 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1802 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1803 id = int(dev[0].list_networks()[0]['id'])
1804 dev[0].set_network(id, "scan_freq", "2412")
1805
1806 dev[0].request("WPS_ER_START ifname=lo")
1807 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1808 if ev is None:
1809 raise Exception("AP discovery timed out")
1810 if ap_uuid not in ev:
1811 raise Exception("Expected AP UUID not found")
1812
1813 dev[0].dump_monitor()
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 after AP learn timed out")
1821 time.sleep(0.1)
1822
1823 with alloc_fail(dev[0], 1, "=wps_er_ap_cache_settings"):
1824 hapd.disable()
1825
1826 for i in range(2):
fab49f61
JM
1827 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE",
1828 "CTRL-EVENT-DISCONNECTED"],
d840350a
JM
1829 timeout=15)
1830 if ev is None:
1831 raise Exception("AP removal or disconnection timed out")
1832
8b8a1864 1833 hapd = hostapd.add_ap(apdev[0], params)
d840350a 1834 for i in range(2):
fab49f61 1835 ev = dev[0].wait_event(["WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED"],
d840350a
JM
1836 timeout=15)
1837 if ev is None:
1838 raise Exception("AP discovery or connection timed out")
1839
1840 dev[0].request("WPS_ER_STOP")
1841
eb95ced2
JM
1842def test_ap_wps_er_subscribe_oom(dev, apdev):
1843 """WPS ER subscribe OOM"""
1844 try:
1845 _test_ap_wps_er_subscribe_oom(dev, apdev)
1846 finally:
1847 dev[0].request("WPS_ER_STOP")
1848
1849def _test_ap_wps_er_subscribe_oom(dev, apdev):
1850 ssid = "wps-er-add-enrollee"
1851 ap_pin = "12345670"
1852 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
fab49f61
JM
1853 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1854 "wpa_passphrase": "12345678", "wpa": "2",
1855 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1856 "device_name": "Wireless AP", "manufacturer": "Company",
1857 "model_name": "WAP", "model_number": "123",
1858 "serial_number": "12345", "device_type": "6-0050F204-1",
1859 "os_version": "01020300",
1860 "config_methods": "label push_button",
1861 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
8b8a1864 1862 hapd = hostapd.add_ap(apdev[0], params)
41532439 1863 dev[0].flush_scan_cache()
eb95ced2
JM
1864 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1865 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1866 id = int(dev[0].list_networks()[0]['id'])
1867 dev[0].set_network(id, "scan_freq", "2412")
1868
1869 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_subscribe"):
1870 dev[0].request("WPS_ER_START ifname=lo")
1871 for i in range(50):
1872 res = dev[0].request("GET_ALLOC_FAIL")
1873 if res.startswith("0:"):
1874 break
1875 time.sleep(0.1)
1876 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=0)
1877 if ev:
1878 raise Exception("Unexpected AP discovery during OOM")
1879
1880 dev[0].request("WPS_ER_STOP")
1881
db9c88eb
JM
1882def test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1883 """WPS ER SetSelectedRegistrar OOM"""
1884 try:
1885 _test_ap_wps_er_set_sel_reg_oom(dev, apdev)
1886 finally:
1887 dev[0].request("WPS_ER_STOP")
1888
1889def _test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1890 ssid = "wps-er-add-enrollee"
1891 ap_pin = "12345670"
1892 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
fab49f61
JM
1893 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1894 "wpa_passphrase": "12345678", "wpa": "2",
1895 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1896 "device_name": "Wireless AP", "manufacturer": "Company",
1897 "model_name": "WAP", "model_number": "123",
1898 "serial_number": "12345", "device_type": "6-0050F204-1",
1899 "os_version": "01020300",
1900 "config_methods": "label push_button",
1901 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
8b8a1864 1902 hapd = hostapd.add_ap(apdev[0], params)
41532439 1903 dev[0].flush_scan_cache()
db9c88eb
JM
1904 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1905 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1906
1907 dev[0].request("WPS_ER_START ifname=lo")
1908 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1909 if ev is None:
1910 raise Exception("AP not discovered")
1911
1912 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1913 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1914 if ev is None:
1915 raise Exception("AP learn timed out")
1916 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1917 if ev is None:
1918 raise Exception("WPS-FAIL timed out")
1919 time.sleep(0.1)
1920
fab49f61
JM
1921 for func in ["http_client_url_parse;wps_er_send_set_sel_reg",
1922 "wps_er_soap_hdr;wps_er_send_set_sel_reg",
1923 "http_client_addr;wps_er_send_set_sel_reg",
1924 "wpabuf_alloc;wps_er_set_sel_reg"]:
db9c88eb
JM
1925 with alloc_fail(dev[0], 1, func):
1926 if "OK" not in dev[0].request("WPS_ER_PBC " + ap_uuid):
1927 raise Exception("WPS_ER_PBC failed")
1928 ev = dev[0].wait_event(["WPS-PBC-ACTIVE"], timeout=3)
1929 if ev is None:
1930 raise Exception("WPS-PBC-ACTIVE not seen")
1931
1932 dev[0].request("WPS_ER_STOP")
1933
9fd6804d 1934@remote_compatible
ae3eacf7
JM
1935def test_ap_wps_er_learn_oom(dev, apdev):
1936 """WPS ER learn OOM"""
1937 try:
1938 _test_ap_wps_er_learn_oom(dev, apdev)
1939 finally:
1940 dev[0].request("WPS_ER_STOP")
1941
1942def _test_ap_wps_er_learn_oom(dev, apdev):
1943 ssid = "wps-er-add-enrollee"
1944 ap_pin = "12345670"
1945 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
fab49f61
JM
1946 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1947 "wpa_passphrase": "12345678", "wpa": "2",
1948 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1949 "device_name": "Wireless AP", "manufacturer": "Company",
1950 "model_name": "WAP", "model_number": "123",
1951 "serial_number": "12345", "device_type": "6-0050F204-1",
1952 "os_version": "01020300",
1953 "config_methods": "label push_button",
1954 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
8b8a1864 1955 hapd = hostapd.add_ap(apdev[0], params)
41532439 1956 dev[0].flush_scan_cache()
ae3eacf7
JM
1957 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1958 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1959
1960 dev[0].request("WPS_ER_START ifname=lo")
1961 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1962 if ev is None:
1963 raise Exception("AP not discovered")
1964
fab49f61
JM
1965 for func in ["wps_er_http_put_message_cb",
1966 "xml_get_base64_item;wps_er_http_put_message_cb",
1967 "http_client_url_parse;wps_er_ap_put_message",
1968 "wps_er_soap_hdr;wps_er_ap_put_message",
1969 "http_client_addr;wps_er_ap_put_message"]:
ae3eacf7
JM
1970 with alloc_fail(dev[0], 1, func):
1971 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1972 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=1)
1973 if ev is not None:
1974 raise Exception("AP learn succeeded during OOM")
1975
1976 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1977 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=10)
1978 if ev is None:
1979 raise Exception("AP learn did not succeed")
1980
1981 if "FAIL" not in dev[0].request("WPS_ER_LEARN 00000000-9e5c-4e73-bd82-f89cbcd10d7e " + ap_pin):
1982 raise Exception("WPS_ER_LEARN for unknown AP accepted")
1983
1984 dev[0].request("WPS_ER_STOP")
1985
bff3ac5b
JM
1986def test_ap_wps_fragmentation(dev, apdev):
1987 """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
1988 ssid = "test-wps-fragmentation"
9602b355 1989 appin = "12345670"
6f334bf7 1990 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
1991 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1992 "wpa_passphrase": "12345678", "wpa": "3",
1993 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1994 "wpa_pairwise": "TKIP", "ap_pin": appin,
1995 "fragment_size": "50"})
9602b355 1996 logger.info("WPS provisioning step (PBC)")
bff3ac5b 1997 hapd.request("WPS_PBC")
33d0b157 1998 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
bff3ac5b
JM
1999 dev[0].dump_monitor()
2000 dev[0].request("SET wps_fragment_size 50")
33d0b157 2001 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2002 dev[0].wait_connected(timeout=30)
bff3ac5b
JM
2003 status = dev[0].get_status()
2004 if status['wpa_state'] != 'COMPLETED':
9602b355
JM
2005 raise Exception("Not fully connected")
2006 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
2007 raise Exception("Unexpected encryption configuration")
2008 if status['key_mgmt'] != 'WPA2-PSK':
2009 raise Exception("Unexpected key_mgmt")
2010
2011 logger.info("WPS provisioning step (PIN)")
2012 pin = dev[1].wps_read_pin()
2013 hapd.request("WPS_PIN any " + pin)
33d0b157 2014 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
9602b355 2015 dev[1].request("SET wps_fragment_size 50")
33d0b157 2016 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 2017 dev[1].wait_connected(timeout=30)
9602b355
JM
2018 status = dev[1].get_status()
2019 if status['wpa_state'] != 'COMPLETED':
2020 raise Exception("Not fully connected")
2021 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
2022 raise Exception("Unexpected encryption configuration")
2023 if status['key_mgmt'] != 'WPA2-PSK':
2024 raise Exception("Unexpected key_mgmt")
2025
2026 logger.info("WPS connection as registrar")
33d0b157 2027 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
9602b355
JM
2028 dev[2].request("SET wps_fragment_size 50")
2029 dev[2].wps_reg(apdev[0]['bssid'], appin)
2030 status = dev[2].get_status()
2031 if status['wpa_state'] != 'COMPLETED':
bff3ac5b
JM
2032 raise Exception("Not fully connected")
2033 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
2034 raise Exception("Unexpected encryption configuration")
2035 if status['key_mgmt'] != 'WPA2-PSK':
2036 raise Exception("Unexpected key_mgmt")
10ea6848 2037
9fd6804d 2038@remote_compatible
10ea6848
JM
2039def test_ap_wps_new_version_sta(dev, apdev):
2040 """WPS compatibility with new version number on the station"""
2041 ssid = "test-wps-ver"
6f334bf7 2042 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
2043 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2044 "wpa_passphrase": "12345678", "wpa": "2",
2045 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
10ea6848
JM
2046 logger.info("WPS provisioning step")
2047 hapd.request("WPS_PBC")
33d0b157 2048 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10ea6848
JM
2049 dev[0].dump_monitor()
2050 dev[0].request("SET wps_version_number 0x43")
dccafedb 2051 dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
33d0b157 2052 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2053 dev[0].wait_connected(timeout=30)
10ea6848 2054
9fd6804d 2055@remote_compatible
10ea6848
JM
2056def test_ap_wps_new_version_ap(dev, apdev):
2057 """WPS compatibility with new version number on the AP"""
2058 ssid = "test-wps-ver"
6f334bf7 2059 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
2060 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2061 "wpa_passphrase": "12345678", "wpa": "2",
2062 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
10ea6848
JM
2063 logger.info("WPS provisioning step")
2064 if "FAIL" in hapd.request("SET wps_version_number 0x43"):
2065 raise Exception("Failed to enable test functionality")
2066 hapd.request("WPS_PBC")
33d0b157 2067 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10ea6848 2068 dev[0].dump_monitor()
33d0b157 2069 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2070 dev[0].wait_connected(timeout=30)
10ea6848 2071 hapd.request("SET wps_version_number 0x20")
3bdf7d7f 2072
9fd6804d 2073@remote_compatible
3bdf7d7f
JM
2074def test_ap_wps_check_pin(dev, apdev):
2075 """Verify PIN checking through control interface"""
6f334bf7 2076 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
2077 {"ssid": "wps", "eap_server": "1", "wps_state": "2",
2078 "wpa_passphrase": "12345678", "wpa": "2",
2079 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2080 for t in [("12345670", "12345670"),
2081 ("12345678", "FAIL-CHECKSUM"),
2082 ("12345", "FAIL"),
2083 ("123456789", "FAIL"),
2084 ("1234-5670", "12345670"),
2085 ("1234 5670", "12345670"),
2086 ("1-2.3:4 5670", "12345670")]:
3bdf7d7f
JM
2087 res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
2088 res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
2089 if res != res2:
2090 raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
2091 if res != t[1]:
2092 raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
9ba1fcb0 2093
ac786d67
JM
2094 if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
2095 raise Exception("Unexpected WPS_CHECK_PIN success")
2096 if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
2097 raise Exception("Unexpected WPS_CHECK_PIN success")
2098
acd9b45a
JM
2099 for i in range(0, 10):
2100 pin = dev[0].request("WPS_PIN get")
2101 rpin = dev[0].request("WPS_CHECK_PIN " + pin).rstrip('\n')
2102 if pin != rpin:
2103 raise Exception("Random PIN validation failed for " + pin)
2104
3381d324
JM
2105def test_ap_wps_pin_get_failure(dev, apdev):
2106 """PIN generation failure"""
2107 with fail_test(dev[0], 1,
2108 "os_get_random;wpa_supplicant_ctrl_iface_wps_pin"):
2109 if "FAIL" not in dev[0].request("WPS_PIN get"):
2110 raise Exception("WPS_PIN did not report failure")
2111
9ba1fcb0
JM
2112def test_ap_wps_wep_config(dev, apdev):
2113 """WPS 2.0 AP rejecting WEP configuration"""
2114 ssid = "test-wps-config"
2115 appin = "12345670"
6f334bf7 2116 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
2117 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2118 "ap_pin": appin})
41532439 2119 dev[0].flush_scan_cache()
33d0b157 2120 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
9ba1fcb0
JM
2121 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
2122 "hello", no_wait=True)
2123 ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
2124 if ev is None:
2125 raise Exception("WPS-FAIL timed out")
2126 if "reason=2" not in ev:
2127 raise Exception("Unexpected reason code in WPS-FAIL")
2128 status = hapd.request("WPS_GET_STATUS")
2129 if "Last WPS result: Failed" not in status:
2130 raise Exception("WPS failure result not shown correctly")
2131 if "Failure Reason: WEP Prohibited" not in status:
2132 raise Exception("Failure reason not reported correctly")
2133 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
2134 raise Exception("Peer address not shown correctly")
1013a576 2135
11d78bb1
JM
2136def test_ap_wps_wep_enroll(dev, apdev):
2137 """WPS 2.0 STA rejecting WEP configuration"""
2138 ssid = "test-wps-wep"
fab49f61
JM
2139 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2140 "skip_cred_build": "1", "extra_cred": "wps-wep-cred"}
6f334bf7 2141 hapd = hostapd.add_ap(apdev[0], params)
11d78bb1 2142 hapd.request("WPS_PBC")
33d0b157
JM
2143 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2144 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
11d78bb1
JM
2145 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
2146 if ev is None:
2147 raise Exception("WPS-FAIL event timed out")
2148 if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
2149 raise Exception("Unexpected WPS-FAIL event: " + ev)
2150
9fd6804d 2151@remote_compatible
1013a576
JM
2152def test_ap_wps_ie_fragmentation(dev, apdev):
2153 """WPS AP using fragmented WPS IE"""
2154 ssid = "test-wps-ie-fragmentation"
fab49f61
JM
2155 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2156 "wpa_passphrase": "12345678", "wpa": "2",
2157 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2158 "device_name": "1234567890abcdef1234567890abcdef",
2159 "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
2160 "model_name": "1234567890abcdef1234567890abcdef",
2161 "model_number": "1234567890abcdef1234567890abcdef",
2162 "serial_number": "1234567890abcdef1234567890abcdef"}
6f334bf7 2163 hapd = hostapd.add_ap(apdev[0], params)
1013a576 2164 hapd.request("WPS_PBC")
33d0b157
JM
2165 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2166 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2167 dev[0].wait_connected(timeout=30)
1013a576
JM
2168 bss = dev[0].get_bss(apdev[0]['bssid'])
2169 if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
cf3f0ec8 2170 logger.info("Device Name not received correctly")
d7a68ad6 2171 logger.info(bss)
cf3f0ec8
JM
2172 # This can fail if Probe Response frame is missed and Beacon frame was
2173 # used to fill in the BSS entry. This can happen, e.g., during heavy
2174 # load every now and then and is not really an error, so try to
2175 # workaround by runnign another scan.
2176 dev[0].scan(freq="2412", only_new=True)
2177 bss = dev[0].get_bss(apdev[0]['bssid'])
84a40841 2178 if not bss or "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
cf3f0ec8
JM
2179 logger.info(bss)
2180 raise Exception("Device Name not received correctly")
1013a576
JM
2181 if len(re.findall("dd..0050f204", bss['ie'])) != 2:
2182 raise Exception("Unexpected number of WPS IEs")
44ff0400 2183
2035b170
JM
2184def get_psk(pskfile):
2185 psks = {}
2186 with open(pskfile, "r") as f:
2187 lines = f.read().splitlines()
2188 for l in lines:
2189 if l == "# WPA PSKs":
2190 continue
68e9b8cb 2191 vals = l.split(' ')
afd10e88 2192 if len(vals) != 3 or vals[0] != "wps=1":
68e9b8cb 2193 continue
afd10e88
JM
2194 addr = vals[1]
2195 psk = vals[2]
2035b170
JM
2196 psks[addr] = psk
2197 return psks
2198
2199def test_ap_wps_per_station_psk(dev, apdev):
2200 """WPS PBC provisioning with per-station PSK"""
1d21a5be
B
2201 addr0 = dev[0].own_addr()
2202 addr1 = dev[1].own_addr()
2203 addr2 = dev[2].own_addr()
2035b170
JM
2204 ssid = "wps"
2205 appin = "12345670"
2206 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2207 try:
2208 os.remove(pskfile)
2209 except:
2210 pass
2211
4f524e99 2212 hapd = None
2035b170
JM
2213 try:
2214 with open(pskfile, "w") as f:
2215 f.write("# WPA PSKs\n")
2216
fab49f61
JM
2217 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2218 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2219 "rsn_pairwise": "CCMP", "ap_pin": appin,
2220 "wpa_psk_file": pskfile}
8b8a1864 2221 hapd = hostapd.add_ap(apdev[0], params)
2035b170
JM
2222
2223 logger.info("First enrollee")
2224 hapd.request("WPS_PBC")
41532439 2225 dev[0].flush_scan_cache()
33d0b157
JM
2226 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2227 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2228 dev[0].wait_connected(timeout=30)
2035b170
JM
2229
2230 logger.info("Second enrollee")
2231 hapd.request("WPS_PBC")
33d0b157
JM
2232 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2233 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2234 dev[1].wait_connected(timeout=30)
2035b170
JM
2235
2236 logger.info("External registrar")
33d0b157 2237 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2035b170
JM
2238 dev[2].wps_reg(apdev[0]['bssid'], appin)
2239
2240 logger.info("Verifying PSK results")
2241 psks = get_psk(pskfile)
2242 if addr0 not in psks:
2243 raise Exception("No PSK recorded for sta0")
2244 if addr1 not in psks:
2245 raise Exception("No PSK recorded for sta1")
2246 if addr2 not in psks:
2247 raise Exception("No PSK recorded for sta2")
2248 if psks[addr0] == psks[addr1]:
2249 raise Exception("Same PSK recorded for sta0 and sta1")
2250 if psks[addr0] == psks[addr2]:
2251 raise Exception("Same PSK recorded for sta0 and sta2")
2252 if psks[addr1] == psks[addr2]:
2253 raise Exception("Same PSK recorded for sta1 and sta2")
2254
2255 dev[0].request("REMOVE_NETWORK all")
2256 logger.info("Second external registrar")
33d0b157 2257 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2035b170
JM
2258 dev[0].wps_reg(apdev[0]['bssid'], appin)
2259 psks2 = get_psk(pskfile)
2260 if addr0 not in psks2:
2261 raise Exception("No PSK recorded for sta0(reg)")
2262 if psks[addr0] == psks2[addr0]:
2263 raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
2264 finally:
2265 os.remove(pskfile)
4f524e99
JM
2266 if hapd:
2267 dev[0].request("DISCONNECT")
2268 dev[1].request("DISCONNECT")
2269 dev[2].request("DISCONNECT")
2270 hapd.disable()
2271 dev[0].flush_scan_cache()
2272 dev[1].flush_scan_cache()
2273 dev[2].flush_scan_cache()
2035b170 2274
dd3d5da3
JM
2275def test_ap_wps_per_station_psk_preset(dev, apdev):
2276 """WPS PIN provisioning with per-station PSK preset"""
2277 addr0 = dev[0].own_addr()
2278 addr1 = dev[1].own_addr()
2279 addr2 = dev[2].own_addr()
2280 ssid = "wps"
2281 appin = "12345670"
2282 pskfile = "/tmp/ap_wps_per_enrollee_psk_preset.psk_file"
2283 try:
2284 os.remove(pskfile)
2285 except:
2286 pass
2287
2288 hapd = None
2289 try:
2290 with open(pskfile, "w") as f:
2291 f.write("# WPA PSKs\n")
2292 f.write("wps=1 " + addr0 + " preset-passphrase-0\n")
2293 f.write("wps=1 " + addr2 + " preset-passphrase-2\n")
2294
2295 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2296 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2297 "rsn_pairwise": "CCMP", "ap_pin": appin,
2298 "wpa_psk_file": pskfile}
2299 hapd = hostapd.add_ap(apdev[0], params)
2300 bssid = hapd.own_addr()
2301
2302 logger.info("First enrollee")
2303 pin = dev[0].wps_read_pin()
2304 hapd.request("WPS_PIN any " + pin)
2305 dev[0].scan_for_bss(bssid, freq=2412)
2306 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
2307 dev[0].wait_connected(timeout=30)
2308
2309 logger.info("Second enrollee")
2310 pin = dev[1].wps_read_pin()
2311 hapd.request("WPS_PIN any " + pin)
2312 dev[1].scan_for_bss(bssid, freq=2412)
2313 dev[1].request("WPS_PIN %s %s" % (bssid, pin))
2314 dev[1].wait_connected(timeout=30)
2315
2316 logger.info("External registrar")
2317 dev[2].scan_for_bss(bssid, freq=2412)
2318 dev[2].wps_reg(bssid, appin)
2319
2320 logger.info("Verifying PSK results")
2321 psks = get_psk(pskfile)
2322 if addr0 not in psks:
2323 raise Exception("No PSK recorded for sta0")
2324 if addr1 not in psks:
2325 raise Exception("No PSK recorded for sta1")
2326 if addr2 not in psks:
2327 raise Exception("No PSK recorded for sta2")
2328 logger.info("PSK[0]: " + psks[addr0])
2329 logger.info("PSK[1]: " + psks[addr1])
2330 logger.info("PSK[2]: " + psks[addr2])
2331 if psks[addr0] == psks[addr1]:
2332 raise Exception("Same PSK recorded for sta0 and sta1")
2333 if psks[addr0] == psks[addr2]:
2334 raise Exception("Same PSK recorded for sta0 and sta2")
2335 if psks[addr1] == psks[addr2]:
2336 raise Exception("Same PSK recorded for sta1 and sta2")
2337 pmk0 = hapd.request("GET_PMK " + addr0)
2338 pmk1 = hapd.request("GET_PMK " + addr1)
2339 pmk2 = hapd.request("GET_PMK " + addr2)
2340 logger.info("PMK[0]: " + pmk0)
2341 logger.info("PMK[1]: " + pmk1)
2342 logger.info("PMK[2]: " + pmk2)
2343 if pmk0 != "565faec21ff04702d9d17c464e1301efd36c8a3ea46bb866b4bec7fed4384579":
2344 raise Exception("PSK[0] mismatch")
2345 if psks[addr1] != pmk1:
2346 raise Exception("PSK[1] mismatch")
2347 if psks[addr2] != pmk2:
2348 raise Exception("PSK[2] mismatch")
2349
2350 dev[0].request("REMOVE_NETWORK all")
2351 dev[0].wait_disconnected()
2352 dev[0].dump_monitor()
2353 logger.info("First enrollee again")
2354 pin = dev[0].wps_read_pin()
2355 hapd.request("WPS_PIN any " + pin)
2356 dev[0].scan_for_bss(bssid, freq=2412)
2357 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
2358 dev[0].wait_connected(timeout=30)
2359 psks2 = get_psk(pskfile)
2360 if addr0 not in psks2:
2361 raise Exception("No PSK recorded for sta0 (2)")
2362 if psks[addr0] != psks2[addr0]:
2363 raise Exception("Different PSK recorded for sta0(enrollee) and sta0(enrollee 2)")
2364 finally:
2365 os.remove(pskfile)
2366
373cce55
JM
2367def test_ap_wps_per_station_psk_failure(dev, apdev):
2368 """WPS PBC provisioning with per-station PSK (file not writable)"""
2369 addr0 = dev[0].p2p_dev_addr()
2370 addr1 = dev[1].p2p_dev_addr()
2371 addr2 = dev[2].p2p_dev_addr()
2372 ssid = "wps"
2373 appin = "12345670"
2374 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2375 try:
2376 os.remove(pskfile)
2377 except:
2378 pass
2379
3615bde6 2380 hapd = None
373cce55
JM
2381 try:
2382 with open(pskfile, "w") as f:
2383 f.write("# WPA PSKs\n")
2384
fab49f61
JM
2385 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2386 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2387 "rsn_pairwise": "CCMP", "ap_pin": appin,
2388 "wpa_psk_file": pskfile}
8b8a1864 2389 hapd = hostapd.add_ap(apdev[0], params)
373cce55
JM
2390 if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
2391 raise Exception("Failed to set wpa_psk_file")
2392
2393 logger.info("First enrollee")
2394 hapd.request("WPS_PBC")
33d0b157
JM
2395 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2396 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2397 dev[0].wait_connected(timeout=30)
373cce55
JM
2398
2399 logger.info("Second enrollee")
2400 hapd.request("WPS_PBC")
33d0b157
JM
2401 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2402 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2403 dev[1].wait_connected(timeout=30)
373cce55
JM
2404
2405 logger.info("External registrar")
33d0b157 2406 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
373cce55
JM
2407 dev[2].wps_reg(apdev[0]['bssid'], appin)
2408
2409 logger.info("Verifying PSK results")
2410 psks = get_psk(pskfile)
2411 if len(psks) > 0:
2412 raise Exception("PSK recorded unexpectedly")
2413 finally:
3615bde6
JM
2414 if hapd:
2415 for i in range(3):
2416 dev[i].request("DISCONNECT")
2417 hapd.disable()
2418 for i in range(3):
2419 dev[i].flush_scan_cache()
373cce55
JM
2420 os.remove(pskfile)
2421
e8518757
JM
2422def test_ap_wps_pin_request_file(dev, apdev):
2423 """WPS PIN provisioning with configured AP"""
2424 ssid = "wps"
2425 pinfile = "/tmp/ap_wps_pin_request_file.log"
2426 if os.path.exists(pinfile):
b638f703 2427 os.remove(pinfile)
6f334bf7 2428 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
2429 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2430 "wps_pin_requests": pinfile,
2431 "wpa_passphrase": "12345678", "wpa": "2",
2432 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e8518757
JM
2433 uuid = dev[0].get_status_field("uuid")
2434 pin = dev[0].wps_read_pin()
2435 try:
33d0b157
JM
2436 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2437 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
e8518757
JM
2438 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
2439 if ev is None:
2440 raise Exception("PIN needed event not shown")
2441 if uuid not in ev:
2442 raise Exception("UUID mismatch")
2443 dev[0].request("WPS_CANCEL")
2444 success = False
2445 with open(pinfile, "r") as f:
2446 lines = f.readlines()
2447 for l in lines:
2448 if uuid in l:
2449 success = True
2450 break
2451 if not success:
2452 raise Exception("PIN request entry not in the log file")
2453 finally:
b638f703
JM
2454 try:
2455 os.remove(pinfile)
2456 except:
2457 pass
e8518757 2458
56887c35
JM
2459def test_ap_wps_auto_setup_with_config_file(dev, apdev):
2460 """WPS auto-setup with configuration file"""
2461 conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
2462 ifname = apdev[0]['ifname']
2463 try:
2464 with open(conffile, "w") as f:
2465 f.write("driver=nl80211\n")
2466 f.write("hw_mode=g\n")
2467 f.write("channel=1\n")
2468 f.write("ieee80211n=1\n")
2469 f.write("interface=%s\n" % ifname)
2470 f.write("ctrl_interface=/var/run/hostapd\n")
2471 f.write("ssid=wps\n")
2472 f.write("eap_server=1\n")
2473 f.write("wps_state=1\n")
5148b392 2474 hapd = hostapd.add_bss(apdev[0], ifname, conffile)
56887c35 2475 hapd.request("WPS_PBC")
33d0b157
JM
2476 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2477 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2478 dev[0].wait_connected(timeout=30)
56887c35
JM
2479 with open(conffile, "r") as f:
2480 lines = f.read().splitlines()
2481 vals = dict()
2482 for l in lines:
2483 try:
fab49f61 2484 [name, value] = l.split('=', 1)
56887c35 2485 vals[name] = value
bab493b9 2486 except ValueError as e:
56887c35
JM
2487 if "# WPS configuration" in l:
2488 pass
2489 else:
2490 raise Exception("Unexpected configuration line: " + l)
2491 if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
2492 raise Exception("Incorrect configuration: " + str(vals))
2493 finally:
b638f703
JM
2494 try:
2495 os.remove(conffile)
2496 except:
2497 pass
56887c35 2498
91f3cf69 2499def test_ap_wps_pbc_timeout(dev, apdev, params):
31e56b95 2500 """wpa_supplicant PBC walk time and WPS ER SelReg timeout [long]"""
91f3cf69 2501 if not params['long']:
81e787b7 2502 raise HwsimSkip("Skip test case with long duration due to --long not specified")
31e56b95 2503 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2504 hapd = add_ssdp_ap(apdev[0], ap_uuid)
31e56b95
JM
2505
2506 location = ssdp_get_location(ap_uuid)
2507 urls = upnp_get_urls(location)
9c06eda0
MH
2508 eventurl = urlparse(urls['event_sub_url'])
2509 ctrlurl = urlparse(urls['control_url'])
31e56b95 2510
9c06eda0
MH
2511 url = urlparse(location)
2512 conn = HTTPConnection(url.netloc)
31e56b95 2513
9c06eda0 2514 class WPSERHTTPServer(StreamRequestHandler):
31e56b95
JM
2515 def handle(self):
2516 data = self.rfile.readline().strip()
2517 logger.debug(data)
2518 self.wfile.write(gen_wps_event())
2519
2520 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
2521 server.timeout = 1
2522
fab49f61
JM
2523 headers = {"callback": '<http://127.0.0.1:12345/event>',
2524 "NT": "upnp:event",
2525 "timeout": "Second-1234"}
31e56b95
JM
2526 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2527 resp = conn.getresponse()
2528 if resp.status != 200:
2529 raise Exception("Unexpected HTTP response: %d" % resp.status)
2530 sid = resp.getheader("sid")
2531 logger.debug("Subscription SID " + sid)
2532
2533 msg = '''<?xml version="1.0"?>
2534<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
2535<s:Body>
2536<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
2537<NewMessage>EEoAARAQQQABARASAAIAABBTAAIxSBBJAA4ANyoAASABBv///////xBIABA2LbR7pTpRkYj7
2538VFi5hrLk
2539</NewMessage>
2540</u:SetSelectedRegistrar>
2541</s:Body>
2542</s:Envelope>'''
fab49f61 2543 headers = {"Content-type": 'text/xml; charset="utf-8"'}
31e56b95
JM
2544 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
2545 conn.request("POST", ctrlurl.path, msg, headers)
2546 resp = conn.getresponse()
2547 if resp.status != 200:
2548 raise Exception("Unexpected HTTP response: %d" % resp.status)
2549
2550 server.handle_request()
2551
91f3cf69
JM
2552 logger.info("Start WPS_PBC and wait for PBC walk time expiration")
2553 if "OK" not in dev[0].request("WPS_PBC"):
2554 raise Exception("WPS_PBC failed")
31e56b95
JM
2555
2556 start = os.times()[4]
2557
2558 server.handle_request()
2559 dev[1].request("BSS_FLUSH 0")
2560 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2561 only_new=True)
2562 bss = dev[1].get_bss(apdev[0]['bssid'])
2563 logger.debug("BSS: " + str(bss))
2564 if '[WPS-AUTH]' not in bss['flags']:
2565 raise Exception("WPS not indicated authorized")
2566
2567 server.handle_request()
2568
2569 wps_timeout_seen = False
2570
2571 while True:
2572 hapd.dump_monitor()
2573 dev[1].dump_monitor()
2574 if not wps_timeout_seen:
2575 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=0)
2576 if ev is not None:
2577 logger.info("PBC timeout seen")
2578 wps_timeout_seen = True
2579 else:
2580 dev[0].dump_monitor()
2581 now = os.times()[4]
2582 if now - start > 130:
2583 raise Exception("Selected registration information not removed")
2584 dev[1].request("BSS_FLUSH 0")
2585 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2586 only_new=True)
2587 bss = dev[1].get_bss(apdev[0]['bssid'])
2588 logger.debug("BSS: " + str(bss))
2589 if '[WPS-AUTH]' not in bss['flags']:
2590 break
2591 server.handle_request()
2592
2593 server.server_close()
2594
2595 if wps_timeout_seen:
2596 return
2597
2598 now = os.times()[4]
2599 if now < start + 150:
2600 dur = start + 150 - now
2601 else:
2602 dur = 1
2603 logger.info("Continue waiting for PBC timeout (%d sec)" % dur)
2604 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=dur)
91f3cf69
JM
2605 if ev is None:
2606 raise Exception("WPS-TIMEOUT not reported")
2607
21aa8b7e 2608def add_ssdp_ap(ap, ap_uuid):
44ff0400
JM
2609 ssid = "wps-ssdp"
2610 ap_pin = "12345670"
fab49f61
JM
2611 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2612 "wpa_passphrase": "12345678", "wpa": "2",
2613 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2614 "device_name": "Wireless AP", "manufacturer": "Company",
2615 "model_name": "WAP", "model_number": "123",
2616 "serial_number": "12345", "device_type": "6-0050F204-1",
2617 "os_version": "01020300",
2618 "config_methods": "label push_button",
2619 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
2620 "friendly_name": "WPS Access Point",
2621 "manufacturer_url": "http://www.example.com/",
2622 "model_description": "Wireless Access Point",
2623 "model_url": "http://www.example.com/model/",
2624 "upc": "123456789012"}
21aa8b7e 2625 return hostapd.add_ap(ap, params)
44ff0400
JM
2626
2627def ssdp_send(msg, no_recv=False):
2628 socket.setdefaulttimeout(1)
2629 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2630 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2631 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2632 sock.bind(("127.0.0.1", 0))
cc02ce96 2633 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2634 if no_recv:
2635 return None
cc02ce96 2636 return sock.recv(1000).decode()
44ff0400 2637
96038a5f 2638def ssdp_send_msearch(st, no_recv=False):
44ff0400
JM
2639 msg = '\r\n'.join([
2640 'M-SEARCH * HTTP/1.1',
2641 'HOST: 239.255.255.250:1900',
2642 'MX: 1',
2643 'MAN: "ssdp:discover"',
2644 'ST: ' + st,
2645 '', ''])
96038a5f 2646 return ssdp_send(msg, no_recv=no_recv)
44ff0400
JM
2647
2648def test_ap_wps_ssdp_msearch(dev, apdev):
2649 """WPS AP and SSDP M-SEARCH messages"""
2650 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2651 add_ssdp_ap(apdev[0], ap_uuid)
44ff0400
JM
2652
2653 msg = '\r\n'.join([
2654 'M-SEARCH * HTTP/1.1',
2655 'Host: 239.255.255.250:1900',
2656 'Mx: 1',
2657 'Man: "ssdp:discover"',
2658 'St: urn:schemas-wifialliance-org:device:WFADevice:1',
2659 '', ''])
2660 ssdp_send(msg)
2661
2662 msg = '\r\n'.join([
2663 'M-SEARCH * HTTP/1.1',
2664 'host:\t239.255.255.250:1900\t\t\t\t \t\t',
2665 'mx: \t1\t\t ',
2666 'man: \t \t "ssdp:discover" ',
2667 'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
2668 '', ''])
2669 ssdp_send(msg)
2670
2671 ssdp_send_msearch("ssdp:all")
2672 ssdp_send_msearch("upnp:rootdevice")
2673 ssdp_send_msearch("uuid:" + ap_uuid)
2674 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
bc6e3288 2675 ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1")
44ff0400
JM
2676
2677 msg = '\r\n'.join([
2678 'M-SEARCH * HTTP/1.1',
2679 'HOST:\t239.255.255.250:1900',
2680 'MAN: "ssdp:discover"',
2681 'MX: 130',
2682 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2683 '', ''])
2684 ssdp_send(msg, no_recv=True)
2685
2686def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
2687 """WPS AP and invalid SSDP M-SEARCH messages"""
2688 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2689 add_ssdp_ap(apdev[0], ap_uuid)
44ff0400
JM
2690
2691 socket.setdefaulttimeout(1)
2692 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2693 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2694 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2695 sock.bind(("127.0.0.1", 0))
2696
2697 logger.debug("Missing MX")
2698 msg = '\r\n'.join([
2699 'M-SEARCH * HTTP/1.1',
2700 'HOST: 239.255.255.250:1900',
2701 'MAN: "ssdp:discover"',
2702 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2703 '', ''])
cc02ce96 2704 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2705
2706 logger.debug("Negative MX")
2707 msg = '\r\n'.join([
2708 'M-SEARCH * HTTP/1.1',
2709 'HOST: 239.255.255.250:1900',
2710 'MX: -1',
2711 'MAN: "ssdp:discover"',
2712 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2713 '', ''])
cc02ce96 2714 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2715
2716 logger.debug("Invalid MX")
2717 msg = '\r\n'.join([
2718 'M-SEARCH * HTTP/1.1',
2719 'HOST: 239.255.255.250:1900',
2720 'MX; 1',
2721 'MAN: "ssdp:discover"',
2722 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2723 '', ''])
cc02ce96 2724 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2725
2726 logger.debug("Missing MAN")
2727 msg = '\r\n'.join([
2728 'M-SEARCH * HTTP/1.1',
2729 'HOST: 239.255.255.250:1900',
2730 'MX: 1',
2731 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2732 '', ''])
cc02ce96 2733 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2734
2735 logger.debug("Invalid MAN")
2736 msg = '\r\n'.join([
2737 'M-SEARCH * HTTP/1.1',
2738 'HOST: 239.255.255.250:1900',
2739 'MX: 1',
2740 'MAN: foo',
2741 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2742 '', ''])
cc02ce96 2743 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2744 msg = '\r\n'.join([
2745 'M-SEARCH * HTTP/1.1',
2746 'HOST: 239.255.255.250:1900',
2747 'MX: 1',
2748 'MAN; "ssdp:discover"',
2749 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2750 '', ''])
cc02ce96 2751 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2752
2753 logger.debug("Missing HOST")
2754 msg = '\r\n'.join([
2755 'M-SEARCH * HTTP/1.1',
2756 'MAN: "ssdp:discover"',
2757 'MX: 1',
2758 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2759 '', ''])
cc02ce96 2760 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2761
2762 logger.debug("Missing ST")
2763 msg = '\r\n'.join([
2764 'M-SEARCH * HTTP/1.1',
2765 'HOST: 239.255.255.250:1900',
2766 'MAN: "ssdp:discover"',
2767 'MX: 1',
2768 '', ''])
cc02ce96 2769 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2770
2771 logger.debug("Mismatching ST")
2772 msg = '\r\n'.join([
2773 'M-SEARCH * HTTP/1.1',
2774 'HOST: 239.255.255.250:1900',
2775 'MAN: "ssdp:discover"',
2776 'MX: 1',
2777 'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
2778 '', ''])
cc02ce96 2779 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2780 msg = '\r\n'.join([
2781 'M-SEARCH * HTTP/1.1',
2782 'HOST: 239.255.255.250:1900',
2783 'MAN: "ssdp:discover"',
2784 'MX: 1',
2785 'ST: foo:bar',
2786 '', ''])
cc02ce96 2787 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2788 msg = '\r\n'.join([
2789 'M-SEARCH * HTTP/1.1',
2790 'HOST: 239.255.255.250:1900',
2791 'MAN: "ssdp:discover"',
2792 'MX: 1',
2793 'ST: foobar',
2794 '', ''])
cc02ce96 2795 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2796
2797 logger.debug("Invalid ST")
2798 msg = '\r\n'.join([
2799 'M-SEARCH * HTTP/1.1',
2800 'HOST: 239.255.255.250:1900',
2801 'MAN: "ssdp:discover"',
2802 'MX: 1',
2803 'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
2804 '', ''])
cc02ce96 2805 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2806
2807 logger.debug("Invalid M-SEARCH")
2808 msg = '\r\n'.join([
2809 'M+SEARCH * HTTP/1.1',
2810 'HOST: 239.255.255.250:1900',
2811 'MAN: "ssdp:discover"',
2812 'MX: 1',
2813 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2814 '', ''])
cc02ce96 2815 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2816 msg = '\r\n'.join([
2817 'M-SEARCH-* HTTP/1.1',
2818 'HOST: 239.255.255.250:1900',
2819 'MAN: "ssdp:discover"',
2820 'MX: 1',
2821 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2822 '', ''])
cc02ce96 2823 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2824
2825 logger.debug("Invalid message format")
cc02ce96 2826 sock.sendto(b"NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
44ff0400
JM
2827 msg = '\r'.join([
2828 'M-SEARCH * HTTP/1.1',
2829 'HOST: 239.255.255.250:1900',
2830 'MAN: "ssdp:discover"',
2831 'MX: 1',
2832 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2833 '', ''])
cc02ce96 2834 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2835
2836 try:
2837 r = sock.recv(1000)
2838 raise Exception("Unexpected M-SEARCH response: " + r)
2839 except socket.timeout:
2840 pass
2841
2842 logger.debug("Valid M-SEARCH")
2843 msg = '\r\n'.join([
2844 'M-SEARCH * HTTP/1.1',
2845 'HOST: 239.255.255.250:1900',
2846 'MAN: "ssdp:discover"',
2847 'MX: 1',
2848 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2849 '', ''])
cc02ce96 2850 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2851
2852 try:
2853 r = sock.recv(1000)
2854 pass
2855 except socket.timeout:
2856 raise Exception("No SSDP response")
2857
2858def test_ap_wps_ssdp_burst(dev, apdev):
2859 """WPS AP and SSDP burst"""
2860 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2861 add_ssdp_ap(apdev[0], ap_uuid)
44ff0400
JM
2862
2863 msg = '\r\n'.join([
2864 'M-SEARCH * HTTP/1.1',
2865 'HOST: 239.255.255.250:1900',
2866 'MAN: "ssdp:discover"',
2867 'MX: 1',
2868 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2869 '', ''])
2870 socket.setdefaulttimeout(1)
2871 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2872 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2873 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2874 sock.bind(("127.0.0.1", 0))
2875 for i in range(0, 25):
cc02ce96 2876 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2877 resp = 0
2878 while True:
2879 try:
cc02ce96 2880 r = sock.recv(1000).decode()
44ff0400
JM
2881 if not r.startswith("HTTP/1.1 200 OK\r\n"):
2882 raise Exception("Unexpected message: " + r)
2883 resp += 1
2884 except socket.timeout:
2885 break
2886 if resp < 20:
2887 raise Exception("Too few SSDP responses")
2888
2889 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2890 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2891 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2892 sock.bind(("127.0.0.1", 0))
2893 for i in range(0, 25):
cc02ce96 2894 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2895 while True:
2896 try:
cc02ce96 2897 r = sock.recv(1000).decode()
44ff0400
JM
2898 if ap_uuid in r:
2899 break
2900 except socket.timeout:
2901 raise Exception("No SSDP response")
47c549fd
JM
2902
2903def ssdp_get_location(uuid):
2904 res = ssdp_send_msearch("uuid:" + uuid)
2905 location = None
2906 for l in res.splitlines():
2907 if l.lower().startswith("location:"):
2908 location = l.split(':', 1)[1].strip()
2909 break
2910 if location is None:
2911 raise Exception("No UPnP location found")
2912 return location
2913
2914def upnp_get_urls(location):
308ecbc1
MH
2915 if sys.version_info[0] > 2:
2916 conn = urlopen(location)
2917 else:
2918 conn = urlopen(location, proxies={})
47c549fd
JM
2919 tree = ET.parse(conn)
2920 root = tree.getroot()
2921 urn = '{urn:schemas-upnp-org:device-1-0}'
2922 service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
2923 res = {}
9c06eda0
MH
2924 res['scpd_url'] = urljoin(location, service.find(urn + 'SCPDURL').text)
2925 res['control_url'] = urljoin(location,
2926 service.find(urn + 'controlURL').text)
2927 res['event_sub_url'] = urljoin(location,
2928 service.find(urn + 'eventSubURL').text)
47c549fd
JM
2929 return res
2930
dd124ee8
JM
2931def upnp_soap_action(conn, path, action, include_soap_action=True,
2932 soap_action_override=None, newmsg=None, neweventtype=None,
2933 neweventmac=None):
47c549fd
JM
2934 soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
2935 wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
2936 ET.register_namespace('soapenv', soapns)
2937 ET.register_namespace('wfa', wpsns)
2938 attrib = {}
2939 attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
2940 root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
2941 body = ET.SubElement(root, "{%s}Body" % soapns)
2942 act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
dd124ee8
JM
2943 if newmsg:
2944 msg = ET.SubElement(act, "NewMessage")
c4e333fa 2945 msg.text = base64.b64encode(newmsg.encode()).decode()
dd124ee8
JM
2946 if neweventtype:
2947 msg = ET.SubElement(act, "NewWLANEventType")
2948 msg.text = neweventtype
2949 if neweventmac:
2950 msg = ET.SubElement(act, "NewWLANEventMAC")
2951 msg.text = neweventmac
47c549fd 2952
fab49f61 2953 headers = {"Content-type": 'text/xml; charset="utf-8"'}
47c549fd
JM
2954 if include_soap_action:
2955 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
2956 elif soap_action_override:
2957 headers["SOAPAction"] = soap_action_override
69f58282
MH
2958 decl = b'<?xml version=\'1.0\' encoding=\'utf8\'?>\n'
2959 conn.request("POST", path, decl + ET.tostring(root), headers)
47c549fd
JM
2960 return conn.getresponse()
2961
2962def test_ap_wps_upnp(dev, apdev):
2963 """WPS AP and UPnP operations"""
2964 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2965 add_ssdp_ap(apdev[0], ap_uuid)
47c549fd
JM
2966
2967 location = ssdp_get_location(ap_uuid)
2968 urls = upnp_get_urls(location)
2969
308ecbc1
MH
2970 if sys.version_info[0] > 2:
2971 conn = urlopen(urls['scpd_url'])
2972 else:
2973 conn = urlopen(urls['scpd_url'], proxies={})
47c549fd
JM
2974 scpd = conn.read()
2975
308ecbc1
MH
2976 if sys.version_info[0] > 2:
2977 try:
2978 conn = urlopen(urljoin(location, "unknown.html"))
2979 raise Exception("Unexpected HTTP response to GET unknown URL")
2980 except HTTPError as e:
2981 if e.code != 404:
2982 raise Exception("Unexpected HTTP response to GET unknown URL")
2983 else:
2984 conn = urlopen(urljoin(location, "unknown.html"), proxies={})
2985 if conn.getcode() != 404:
2986 raise Exception("Unexpected HTTP response to GET unknown URL")
47c549fd 2987
9c06eda0
MH
2988 url = urlparse(location)
2989 conn = HTTPConnection(url.netloc)
47c549fd 2990 #conn.set_debuglevel(1)
fab49f61
JM
2991 headers = {"Content-type": 'text/xml; charset="utf-8"',
2992 "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"'}
47c549fd
JM
2993 conn.request("POST", "hello", "\r\n\r\n", headers)
2994 resp = conn.getresponse()
2995 if resp.status != 404:
5c267d71 2996 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2997
2998 conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
2999 resp = conn.getresponse()
3000 if resp.status != 501:
5c267d71 3001 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd 3002
fab49f61
JM
3003 headers = {"Content-type": 'text/xml; charset="utf-8"',
3004 "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"'}
9c06eda0 3005 ctrlurl = urlparse(urls['control_url'])
47c549fd
JM
3006 conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
3007 resp = conn.getresponse()
3008 if resp.status != 401:
5c267d71 3009 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3010
3011 logger.debug("GetDeviceInfo without SOAPAction header")
3012 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
3013 include_soap_action=False)
3014 if resp.status != 401:
5c267d71 3015 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3016
3017 logger.debug("GetDeviceInfo with invalid SOAPAction header")
fab49f61
JM
3018 for act in ["foo",
3019 "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
3020 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
3021 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
47c549fd
JM
3022 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
3023 include_soap_action=False,
3024 soap_action_override=act)
3025 if resp.status != 401:
5c267d71 3026 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3027
3028 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
3029 if resp.status != 200:
5c267d71 3030 raise Exception("Unexpected HTTP response: %d" % resp.status)
732b7613 3031 dev = resp.read().decode()
47c549fd
JM
3032 if "NewDeviceInfo" not in dev:
3033 raise Exception("Unexpected GetDeviceInfo response")
3034
3035 logger.debug("PutMessage without required parameters")
3036 resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
3037 if resp.status != 600:
5c267d71 3038 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3039
3040 logger.debug("PutWLANResponse without required parameters")
3041 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
3042 if resp.status != 600:
5c267d71 3043 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3044
3045 logger.debug("SetSelectedRegistrar from unregistered ER")
3046 resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
3047 if resp.status != 501:
5c267d71 3048 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3049
3050 logger.debug("Unknown action")
3051 resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
3052 if resp.status != 401:
5c267d71 3053 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3054
3055def test_ap_wps_upnp_subscribe(dev, apdev):
3056 """WPS AP and UPnP event subscription"""
3057 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 3058 hapd = add_ssdp_ap(apdev[0], ap_uuid)
47c549fd
JM
3059
3060 location = ssdp_get_location(ap_uuid)
3061 urls = upnp_get_urls(location)
9c06eda0 3062 eventurl = urlparse(urls['event_sub_url'])
47c549fd 3063
9c06eda0
MH
3064 url = urlparse(location)
3065 conn = HTTPConnection(url.netloc)
47c549fd 3066 #conn.set_debuglevel(1)
fab49f61
JM
3067 headers = {"callback": '<http://127.0.0.1:12345/event>',
3068 "timeout": "Second-1234"}
47c549fd
JM
3069 conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
3070 resp = conn.getresponse()
3071 if resp.status != 412:
5c267d71 3072 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3073
3074 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3075 resp = conn.getresponse()
3076 if resp.status != 412:
5c267d71 3077 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd 3078
fab49f61
JM
3079 headers = {"NT": "upnp:event",
3080 "timeout": "Second-1234"}
47c549fd
JM
3081 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3082 resp = conn.getresponse()
3083 if resp.status != 412:
5c267d71 3084 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd 3085
fab49f61
JM
3086 headers = {"callback": '<http://127.0.0.1:12345/event>',
3087 "NT": "upnp:foobar",
3088 "timeout": "Second-1234"}
47c549fd
JM
3089 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3090 resp = conn.getresponse()
3091 if resp.status != 400:
5c267d71 3092 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3093
3094 logger.debug("Valid subscription")
fab49f61
JM
3095 headers = {"callback": '<http://127.0.0.1:12345/event>',
3096 "NT": "upnp:event",
3097 "timeout": "Second-1234"}
47c549fd
JM
3098 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3099 resp = conn.getresponse()
3100 if resp.status != 200:
5c267d71 3101 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3102 sid = resp.getheader("sid")
3103 logger.debug("Subscription SID " + sid)
3104
3105 logger.debug("Invalid re-subscription")
fab49f61
JM
3106 headers = {"NT": "upnp:event",
3107 "sid": "123456734567854",
3108 "timeout": "Second-1234"}
47c549fd
JM
3109 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3110 resp = conn.getresponse()
3111 if resp.status != 400:
5c267d71 3112 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3113
3114 logger.debug("Invalid re-subscription")
fab49f61
JM
3115 headers = {"NT": "upnp:event",
3116 "sid": "uuid:123456734567854",
3117 "timeout": "Second-1234"}
47c549fd
JM
3118 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3119 resp = conn.getresponse()
3120 if resp.status != 400:
5c267d71 3121 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3122
3123 logger.debug("Invalid re-subscription")
fab49f61
JM
3124 headers = {"callback": '<http://127.0.0.1:12345/event>',
3125 "NT": "upnp:event",
3126 "sid": sid,
3127 "timeout": "Second-1234"}
47c549fd
JM
3128 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3129 resp = conn.getresponse()
3130 if resp.status != 400:
5c267d71 3131 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3132
3133 logger.debug("SID mismatch in re-subscription")
fab49f61
JM
3134 headers = {"NT": "upnp:event",
3135 "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
3136 "timeout": "Second-1234"}
47c549fd
JM
3137 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3138 resp = conn.getresponse()
3139 if resp.status != 412:
5c267d71 3140 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3141
3142 logger.debug("Valid re-subscription")
fab49f61
JM
3143 headers = {"NT": "upnp:event",
3144 "sid": sid,
3145 "timeout": "Second-1234"}
47c549fd
JM
3146 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3147 resp = conn.getresponse()
3148 if resp.status != 200:
5c267d71 3149 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3150 sid2 = resp.getheader("sid")
3151 logger.debug("Subscription SID " + sid2)
3152
3153 if sid != sid2:
3154 raise Exception("Unexpected SID change")
3155
3156 logger.debug("Valid re-subscription")
fab49f61
JM
3157 headers = {"NT": "upnp:event",
3158 "sid": "uuid: \t \t" + sid.split(':')[1],
3159 "timeout": "Second-1234"}
47c549fd
JM
3160 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3161 resp = conn.getresponse()
3162 if resp.status != 200:
5c267d71 3163 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3164
3165 logger.debug("Invalid unsubscription")
fab49f61 3166 headers = {"sid": sid}
47c549fd
JM
3167 conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
3168 resp = conn.getresponse()
3169 if resp.status != 412:
5c267d71 3170 raise Exception("Unexpected HTTP response: %d" % resp.status)
fab49f61 3171 headers = {"foo": "bar"}
47c549fd
JM
3172 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3173 resp = conn.getresponse()
3174 if resp.status != 412:
5c267d71 3175 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3176
3177 logger.debug("Valid unsubscription")
fab49f61 3178 headers = {"sid": sid}
47c549fd
JM
3179 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3180 resp = conn.getresponse()
3181 if resp.status != 200:
5c267d71 3182 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3183
3184 logger.debug("Unsubscription for not existing SID")
fab49f61 3185 headers = {"sid": sid}
47c549fd
JM
3186 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3187 resp = conn.getresponse()
3188 if resp.status != 412:
5c267d71 3189 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3190
3191 logger.debug("Invalid unsubscription")
fab49f61 3192 headers = {"sid": " \t \tfoo"}
47c549fd
JM
3193 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3194 resp = conn.getresponse()
3195 if resp.status != 400:
5c267d71 3196 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3197
3198 logger.debug("Invalid unsubscription")
fab49f61 3199 headers = {"sid": "uuid:\t \tfoo"}
47c549fd
JM
3200 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3201 resp = conn.getresponse()
3202 if resp.status != 400:
5c267d71 3203 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3204
3205 logger.debug("Invalid unsubscription")
fab49f61
JM
3206 headers = {"NT": "upnp:event",
3207 "sid": sid}
47c549fd
JM
3208 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3209 resp = conn.getresponse()
3210 if resp.status != 400:
5c267d71 3211 raise Exception("Unexpected HTTP response: %d" % resp.status)
fab49f61
JM
3212 headers = {"callback": '<http://127.0.0.1:12345/event>',
3213 "sid": sid}
47c549fd
JM
3214 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3215 resp = conn.getresponse()
3216 if resp.status != 400:
5c267d71 3217 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3218
3219 logger.debug("Valid subscription with multiple callbacks")
fab49f61
JM
3220 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>',
3221 "NT": "upnp:event",
3222 "timeout": "Second-1234"}
47c549fd
JM
3223 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3224 resp = conn.getresponse()
3225 if resp.status != 200:
5c267d71 3226 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3227 sid = resp.getheader("sid")
3228 logger.debug("Subscription SID " + sid)
d352c407 3229
24b7f282
JM
3230 # Force subscription to be deleted due to errors
3231 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3232 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3233 with alloc_fail(hapd, 1, "event_build_message"):
3234 for i in range(10):
3235 dev[1].dump_monitor()
3236 dev[2].dump_monitor()
3237 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3238 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3239 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3240 dev[1].request("WPS_CANCEL")
3241 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3242 dev[2].request("WPS_CANCEL")
3243 if i % 4 == 1:
3244 time.sleep(1)
3245 else:
3246 time.sleep(0.1)
3247 time.sleep(0.2)
3248
fab49f61 3249 headers = {"sid": sid}
24b7f282
JM
3250 conn.request("UNSUBSCRIBE", eventurl.path, "", headers)
3251 resp = conn.getresponse()
3252 if resp.status != 200 and resp.status != 412:
3253 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3254
fab49f61
JM
3255 headers = {"callback": '<http://127.0.0.1:12345/event>',
3256 "NT": "upnp:event",
3257 "timeout": "Second-1234"}
24b7f282
JM
3258 with alloc_fail(hapd, 1, "http_client_addr;event_send_start"):
3259 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3260 resp = conn.getresponse()
3261 if resp.status != 200:
3262 raise Exception("Unexpected HTTP response for SUBSCRIBE: %d" % resp.status)
3263 sid = resp.getheader("sid")
3264 logger.debug("Subscription SID " + sid)
3265
fab49f61 3266 headers = {"sid": sid}
24b7f282
JM
3267 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3268 resp = conn.getresponse()
3269 if resp.status != 200:
3270 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3271
fab49f61
JM
3272 headers = {"callback": '<http://127.0.0.1:12345/event>',
3273 "NT": "upnp:event",
3274 "timeout": "Second-1234"}
24b7f282
JM
3275 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3276 resp = conn.getresponse()
3277 if resp.status != 200:
3278 raise Exception("Unexpected HTTP response: %d" % resp.status)
3279 sid = resp.getheader("sid")
3280 logger.debug("Subscription SID " + sid)
3281
e6d3aca9 3282 with alloc_fail(hapd, 1, "=wps_upnp_event_add"):
24b7f282
JM
3283 for i in range(2):
3284 dev[1].dump_monitor()
3285 dev[2].dump_monitor()
3286 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3287 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3288 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3289 dev[1].request("WPS_CANCEL")
3290 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3291 dev[2].request("WPS_CANCEL")
3292 if i == 0:
3293 time.sleep(1)
3294 else:
3295 time.sleep(0.1)
3296
3297 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3298 resp = conn.getresponse()
3299 if resp.status != 200:
3300 raise Exception("Unexpected HTTP response: %d" % resp.status)
3301
e6d3aca9 3302 with alloc_fail(hapd, 1, "wpabuf_dup;wps_upnp_event_add"):
24b7f282
JM
3303 dev[1].dump_monitor()
3304 dev[2].dump_monitor()
3305 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3306 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3307 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3308 dev[1].request("WPS_CANCEL")
3309 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3310 dev[2].request("WPS_CANCEL")
3311 time.sleep(0.1)
3312
3313 with fail_test(hapd, 1, "os_get_random;uuid_make;subscription_start"):
3314 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3315 resp = conn.getresponse()
3316 if resp.status != 500:
3317 raise Exception("Unexpected HTTP response: %d" % resp.status)
3318
3319 with alloc_fail(hapd, 1, "=subscription_start"):
3320 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3321 resp = conn.getresponse()
3322 if resp.status != 500:
3323 raise Exception("Unexpected HTTP response: %d" % resp.status)
3324
fab49f61
JM
3325 headers = {"callback": '',
3326 "NT": "upnp:event",
3327 "timeout": "Second-1234"}
24b7f282
JM
3328 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3329 resp = conn.getresponse()
3330 if resp.status != 500:
3331 raise Exception("Unexpected HTTP response: %d" % resp.status)
3332
fab49f61
JM
3333 headers = {"callback": ' <',
3334 "NT": "upnp:event",
3335 "timeout": "Second-1234"}
24b7f282
JM
3336 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3337 resp = conn.getresponse()
3338 if resp.status != 500:
3339 raise Exception("Unexpected HTTP response: %d" % resp.status)
3340
fab49f61
JM
3341 headers = {"callback": '<http://127.0.0.1:12345/event>',
3342 "NT": "upnp:event",
3343 "timeout": "Second-1234"}
24b7f282
JM
3344 with alloc_fail(hapd, 1, "wpabuf_alloc;subscription_first_event"):
3345 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3346 resp = conn.getresponse()
3347 if resp.status != 500:
3348 raise Exception("Unexpected HTTP response: %d" % resp.status)
3349
e6d3aca9 3350 with alloc_fail(hapd, 1, "wps_upnp_event_add;subscription_first_event"):
24b7f282
JM
3351 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3352 resp = conn.getresponse()
3353 if resp.status != 500:
3354 raise Exception("Unexpected HTTP response: %d" % resp.status)
3355
3356 with alloc_fail(hapd, 1, "subscr_addr_add_url"):
3357 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3358 resp = conn.getresponse()
3359 if resp.status != 500:
3360 raise Exception("Unexpected HTTP response: %d" % resp.status)
3361
3362 with alloc_fail(hapd, 2, "subscr_addr_add_url"):
3363 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3364 resp = conn.getresponse()
3365 if resp.status != 500:
3366 raise Exception("Unexpected HTTP response: %d" % resp.status)
3367
3368 for i in range(6):
fab49f61
JM
3369 headers = {"callback": '<http://127.0.0.1:%d/event>' % (12345 + i),
3370 "NT": "upnp:event",
3371 "timeout": "Second-1234"}
24b7f282
JM
3372 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3373 resp = conn.getresponse()
3374 if resp.status != 200:
3375 raise Exception("Unexpected HTTP response: %d" % resp.status)
3376
3377 with alloc_fail(hapd, 1, "=upnp_wps_device_send_wlan_event"):
3378 dev[1].dump_monitor()
3379 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3380 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3381 dev[1].request("WPS_CANCEL")
3382 time.sleep(0.1)
3383
3384 with alloc_fail(hapd, 1, "wpabuf_alloc;upnp_wps_device_send_event"):
3385 dev[1].dump_monitor()
3386 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3387 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3388 dev[1].request("WPS_CANCEL")
3389 time.sleep(0.1)
3390
5b52e1ad
JM
3391 with alloc_fail(hapd, 1,
3392 "base64_gen_encode;?base64_encode;upnp_wps_device_send_wlan_event"):
24b7f282
JM
3393 dev[1].dump_monitor()
3394 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3395 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3396 dev[1].request("WPS_CANCEL")
3397 time.sleep(0.1)
3398
3399 hapd.disable()
3400 with alloc_fail(hapd, 1, "get_netif_info"):
3401 if "FAIL" not in hapd.request("ENABLE"):
3402 raise Exception("ENABLE succeeded during OOM")
3403
d91a64c4
JM
3404def test_ap_wps_upnp_subscribe_events(dev, apdev):
3405 """WPS AP and UPnP event subscription and many events"""
3406 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 3407 hapd = add_ssdp_ap(apdev[0], ap_uuid)
d91a64c4
JM
3408
3409 location = ssdp_get_location(ap_uuid)
3410 urls = upnp_get_urls(location)
9c06eda0 3411 eventurl = urlparse(urls['event_sub_url'])
d91a64c4 3412
9c06eda0 3413 class WPSERHTTPServer(StreamRequestHandler):
d91a64c4
JM
3414 def handle(self):
3415 data = self.rfile.readline().strip()
3416 logger.debug(data)
3417 self.wfile.write(gen_wps_event())
3418
3419 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
3420 server.timeout = 1
3421
9c06eda0
MH
3422 url = urlparse(location)
3423 conn = HTTPConnection(url.netloc)
d91a64c4 3424
fab49f61
JM
3425 headers = {"callback": '<http://127.0.0.1:12345/event>',
3426 "NT": "upnp:event",
3427 "timeout": "Second-1234"}
d91a64c4
JM
3428 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3429 resp = conn.getresponse()
3430 if resp.status != 200:
3431 raise Exception("Unexpected HTTP response: %d" % resp.status)
3432 sid = resp.getheader("sid")
3433 logger.debug("Subscription SID " + sid)
3434
3435 # Fetch the first event message
3436 server.handle_request()
3437
3438 # Force subscription event queue to reach the maximum length by generating
3439 # new proxied events without the ER fetching any of the pending events.
3440 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3441 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3442 for i in range(16):
3443 dev[1].dump_monitor()
3444 dev[2].dump_monitor()
3445 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3446 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3447 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3448 dev[1].request("WPS_CANCEL")
3449 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3450 dev[2].request("WPS_CANCEL")
3451 if i % 4 == 1:
3452 time.sleep(1)
3453 else:
3454 time.sleep(0.1)
3455
3456 hapd.request("WPS_PIN any 12345670")
3457 dev[1].dump_monitor()
3458 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3459 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=10)
3460 if ev is None:
3461 raise Exception("WPS success not reported")
3462
3463 # Close the WPS ER HTTP server without fetching all the pending events.
3464 # This tests hostapd code path that clears subscription and the remaining
3465 # event queue when the interface is deinitialized.
3466 server.handle_request()
3467 server.server_close()
3468
3469 dev[1].wait_connected()
3470
b2047531
JM
3471def test_ap_wps_upnp_http_proto(dev, apdev):
3472 """WPS AP and UPnP/HTTP protocol testing"""
3473 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 3474 add_ssdp_ap(apdev[0], ap_uuid)
b2047531
JM
3475
3476 location = ssdp_get_location(ap_uuid)
3477
9c06eda0
MH
3478 url = urlparse(location)
3479 conn = HTTPConnection(url.netloc, timeout=0.2)
b2047531
JM
3480 #conn.set_debuglevel(1)
3481
3482 conn.request("HEAD", "hello")
3483 resp = conn.getresponse()
3484 if resp.status != 501:
3485 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3486 conn.close()
3487
fab49f61 3488 for cmd in ["PUT", "DELETE", "TRACE", "CONNECT", "M-SEARCH", "M-POST"]:
b2047531
JM
3489 try:
3490 conn.request(cmd, "hello")
3491 resp = conn.getresponse()
bab493b9 3492 except Exception as e:
b2047531
JM
3493 pass
3494 conn.close()
3495
fab49f61 3496 headers = {"Content-Length": 'abc'}
b2047531
JM
3497 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3498 try:
3499 resp = conn.getresponse()
bab493b9 3500 except Exception as e:
b2047531
JM
3501 pass
3502 conn.close()
3503
fab49f61 3504 headers = {"Content-Length": '-10'}
b2047531
JM
3505 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3506 try:
3507 resp = conn.getresponse()
bab493b9 3508 except Exception as e:
b2047531
JM
3509 pass
3510 conn.close()
3511
fab49f61 3512 headers = {"Content-Length": '10000000000000'}
b2047531
JM
3513 conn.request("HEAD", "hello", "\r\n\r\nhello", headers)
3514 try:
3515 resp = conn.getresponse()
bab493b9 3516 except Exception as e:
b2047531
JM
3517 pass
3518 conn.close()
3519
fab49f61 3520 headers = {"Transfer-Encoding": 'abc'}
b2047531
JM
3521 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3522 resp = conn.getresponse()
3523 if resp.status != 501:
3524 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3525 conn.close()
3526
fab49f61 3527 headers = {"Transfer-Encoding": 'chunked'}
b2047531
JM
3528 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3529 resp = conn.getresponse()
3530 if resp.status != 501:
3531 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3532 conn.close()
3533
3534 # Too long a header
3535 conn.request("HEAD", 5000 * 'A')
3536 try:
3537 resp = conn.getresponse()
bab493b9 3538 except Exception as e:
b2047531
JM
3539 pass
3540 conn.close()
3541
3542 # Long URL but within header length limits
3543 conn.request("HEAD", 3000 * 'A')
3544 resp = conn.getresponse()
3545 if resp.status != 501:
3546 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3547 conn.close()
3548
fab49f61 3549 headers = {"Content-Length": '20'}
b2047531
JM
3550 conn.request("POST", "hello", 10 * 'A' + "\r\n\r\n", headers)
3551 try:
3552 resp = conn.getresponse()
bab493b9 3553 except Exception as e:
b2047531
JM
3554 pass
3555 conn.close()
3556
3557 conn.request("POST", "hello", 5000 * 'A' + "\r\n\r\n")
3558 resp = conn.getresponse()
3559 if resp.status != 404:
5c267d71 3560 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
3561 conn.close()
3562
3563 conn.request("POST", "hello", 60000 * 'A' + "\r\n\r\n")
3564 try:
3565 resp = conn.getresponse()
bab493b9 3566 except Exception as e:
b2047531
JM
3567 pass
3568 conn.close()
3569
3570def test_ap_wps_upnp_http_proto_chunked(dev, apdev):
3571 """WPS AP and UPnP/HTTP protocol testing for chunked encoding"""
3572 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 3573 add_ssdp_ap(apdev[0], ap_uuid)
b2047531
JM
3574
3575 location = ssdp_get_location(ap_uuid)
3576
9c06eda0
MH
3577 url = urlparse(location)
3578 conn = HTTPConnection(url.netloc)
b2047531
JM
3579 #conn.set_debuglevel(1)
3580
fab49f61 3581 headers = {"Transfer-Encoding": 'chunked'}
b2047531
JM
3582 conn.request("POST", "hello",
3583 "a\r\nabcdefghij\r\n" + "2\r\nkl\r\n" + "0\r\n\r\n",
3584 headers)
3585 resp = conn.getresponse()
3586 if resp.status != 404:
5c267d71 3587 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
3588 conn.close()
3589
3590 conn.putrequest("POST", "hello")
3591 conn.putheader('Transfer-Encoding', 'chunked')
3592 conn.endheaders()
cc02ce96 3593 conn.send(b"a\r\nabcdefghij\r\n")
b2047531 3594 time.sleep(0.1)
cc02ce96
MH
3595 conn.send(b"2\r\nkl\r\n")
3596 conn.send(b"0\r\n\r\n")
b2047531
JM
3597 resp = conn.getresponse()
3598 if resp.status != 404:
5c267d71 3599 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
3600 conn.close()
3601
3602 conn.putrequest("POST", "hello")
3603 conn.putheader('Transfer-Encoding', 'chunked')
3604 conn.endheaders()
3605 completed = False
3606 try:
3607 for i in range(20000):
cc02ce96
MH
3608 conn.send(b"1\r\nZ\r\n")
3609 conn.send(b"0\r\n\r\n")
b2047531
JM
3610 resp = conn.getresponse()
3611 completed = True
bab493b9 3612 except Exception as e:
b2047531
JM
3613 pass
3614 conn.close()
3615 if completed:
3616 raise Exception("Too long chunked request did not result in connection reset")
3617
fab49f61 3618 headers = {"Transfer-Encoding": 'chunked'}
b2047531
JM
3619 conn.request("POST", "hello", "80000000\r\na", headers)
3620 try:
3621 resp = conn.getresponse()
bab493b9 3622 except Exception as e:
b2047531
JM
3623 pass
3624 conn.close()
3625
3626 conn.request("POST", "hello", "10000000\r\na", headers)
3627 try:
3628 resp = conn.getresponse()
bab493b9 3629 except Exception as e:
b2047531
JM
3630 pass
3631 conn.close()
3632
9fd6804d 3633@remote_compatible
d352c407
JM
3634def test_ap_wps_disabled(dev, apdev):
3635 """WPS operations while WPS is disabled"""
3636 ssid = "test-wps-disabled"
fab49f61 3637 hapd = hostapd.add_ap(apdev[0], {"ssid": ssid})
d352c407
JM
3638 if "FAIL" not in hapd.request("WPS_PBC"):
3639 raise Exception("WPS_PBC succeeded unexpectedly")
3640 if "FAIL" not in hapd.request("WPS_CANCEL"):
3641 raise Exception("WPS_CANCEL succeeded unexpectedly")
a0fd2ae6
JM
3642
3643def test_ap_wps_mixed_cred(dev, apdev):
3644 """WPS 2.0 STA merging mixed mode WPA/WPA2 credentials"""
3645 ssid = "test-wps-wep"
fab49f61
JM
3646 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3647 "skip_cred_build": "1", "extra_cred": "wps-mixed-cred"}
6f334bf7 3648 hapd = hostapd.add_ap(apdev[0], params)
a0fd2ae6 3649 hapd.request("WPS_PBC")
33d0b157
JM
3650 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3651 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
9ed53f5e 3652 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
a0fd2ae6
JM
3653 if ev is None:
3654 raise Exception("WPS-SUCCESS event timed out")
3655 nets = dev[0].list_networks()
3656 if len(nets) != 1:
3657 raise Exception("Unexpected number of network blocks")
3658 id = nets[0]['id']
3659 proto = dev[0].get_network(id, "proto")
3660 if proto != "WPA RSN":
3661 raise Exception("Unexpected merged proto field value: " + proto)
3662 pairwise = dev[0].get_network(id, "pairwise")
70dcb4aa
JM
3663 p = pairwise.split()
3664 if "CCMP" not in p or "TKIP" not in p:
a0fd2ae6 3665 raise Exception("Unexpected merged pairwise field value: " + pairwise)
e5a79e3f 3666
9fd6804d 3667@remote_compatible
e5a79e3f
JM
3668def test_ap_wps_while_connected(dev, apdev):
3669 """WPS PBC provisioning while connected to another AP"""
3670 ssid = "test-wps-conf"
6f334bf7 3671 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
3672 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3673 "wpa_passphrase": "12345678", "wpa": "2",
3674 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e5a79e3f 3675
fab49f61 3676 hostapd.add_ap(apdev[1], {"ssid": "open"})
e5a79e3f
JM
3677 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3678
3679 logger.info("WPS provisioning step")
3680 hapd.request("WPS_PBC")
3681 dev[0].dump_monitor()
33d0b157 3682 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 3683 dev[0].wait_connected(timeout=30)
e5a79e3f
JM
3684 status = dev[0].get_status()
3685 if status['bssid'] != apdev[0]['bssid']:
3686 raise Exception("Unexpected BSSID")
3687
9fd6804d 3688@remote_compatible
e5a79e3f
JM
3689def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
3690 """WPS PBC provisioning while connected to another AP and STA_AUTOCONNECT disabled"""
3691 ssid = "test-wps-conf"
6f334bf7 3692 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
3693 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3694 "wpa_passphrase": "12345678", "wpa": "2",
3695 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e5a79e3f 3696
fab49f61 3697 hostapd.add_ap(apdev[1], {"ssid": "open"})
e5a79e3f
JM
3698
3699 try:
3700 dev[0].request("STA_AUTOCONNECT 0")
3701 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3702
3703 logger.info("WPS provisioning step")
3704 hapd.request("WPS_PBC")
3705 dev[0].dump_monitor()
33d0b157 3706 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 3707 dev[0].wait_connected(timeout=30)
e5a79e3f
JM
3708 status = dev[0].get_status()
3709 if status['bssid'] != apdev[0]['bssid']:
3710 raise Exception("Unexpected BSSID")
3711 finally:
3712 dev[0].request("STA_AUTOCONNECT 1")
3f08d1cd 3713
9fd6804d 3714@remote_compatible
3f08d1cd
JM
3715def test_ap_wps_from_event(dev, apdev):
3716 """WPS PBC event on AP to enable PBC"""
3717 ssid = "test-wps-conf"
8b8a1864 3718 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
3719 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3720 "wpa_passphrase": "12345678", "wpa": "2",
3721 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
33d0b157 3722 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3f08d1cd 3723 dev[0].dump_monitor()
33d0b157
JM
3724 hapd.dump_monitor()
3725 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3f08d1cd
JM
3726
3727 ev = hapd.wait_event(['WPS-ENROLLEE-SEEN'], timeout=15)
3728 if ev is None:
3729 raise Exception("No WPS-ENROLLEE-SEEN event on AP")
3730 vals = ev.split(' ')
3731 if vals[1] != dev[0].p2p_interface_addr():
3732 raise Exception("Unexpected enrollee address: " + vals[1])
3733 if vals[5] != '4':
3734 raise Exception("Unexpected Device Password Id: " + vals[5])
3735 hapd.request("WPS_PBC")
5f35a5e2 3736 dev[0].wait_connected(timeout=30)
1531402e
JM
3737
3738def test_ap_wps_ap_scan_2(dev, apdev):
3739 """AP_SCAN 2 for WPS"""
3740 ssid = "test-wps-conf"
8b8a1864 3741 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
3742 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3743 "wpa_passphrase": "12345678", "wpa": "2",
3744 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
1531402e
JM
3745 hapd.request("WPS_PBC")
3746
3747 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
3748 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
4b9d79b6 3749 wpas.dump_monitor()
1531402e
JM
3750
3751 if "OK" not in wpas.request("AP_SCAN 2"):
3752 raise Exception("Failed to set AP_SCAN 2")
3753
e51c8b2e 3754 wpas.flush_scan_cache()
33d0b157 3755 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
4b9d79b6 3756 wpas.dump_monitor()
33d0b157 3757 wpas.request("WPS_PBC " + apdev[0]['bssid'])
1531402e
JM
3758 ev = wpas.wait_event(["WPS-SUCCESS"], timeout=15)
3759 if ev is None:
3760 raise Exception("WPS-SUCCESS event timed out")
5f35a5e2 3761 wpas.wait_connected(timeout=30)
4b9d79b6 3762 wpas.dump_monitor()
1531402e 3763 wpas.request("DISCONNECT")
59642ca9
JM
3764 wpas.wait_disconnected()
3765 id = wpas.list_networks()[0]['id']
3766 pairwise = wpas.get_network(id, "pairwise")
3767 if "CCMP" not in pairwise.split():
3768 raise Exception("Unexpected pairwise parameter value: " + pairwise)
3769 group = wpas.get_network(id, "group")
3770 if "CCMP" not in group.split():
3771 raise Exception("Unexpected group parameter value: " + group)
3772 # Need to select a single cipher for ap_scan=2 testing
3773 wpas.set_network(id, "pairwise", "CCMP")
3774 wpas.set_network(id, "group", "CCMP")
1531402e
JM
3775 wpas.request("BSS_FLUSH 0")
3776 wpas.dump_monitor()
3777 wpas.request("REASSOCIATE")
5f35a5e2 3778 wpas.wait_connected(timeout=30)
4b9d79b6 3779 wpas.dump_monitor()
8b944cf7
JM
3780 wpas.request("DISCONNECT")
3781 wpas.wait_disconnected()
3782 wpas.flush_scan_cache()
a08fdb17 3783
9fd6804d 3784@remote_compatible
a08fdb17
JM
3785def test_ap_wps_eapol_workaround(dev, apdev):
3786 """EAPOL workaround code path for 802.1X header length mismatch"""
3787 ssid = "test-wps"
6f334bf7 3788 hapd = hostapd.add_ap(apdev[0],
fab49f61 3789 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
a08fdb17
JM
3790 bssid = apdev[0]['bssid']
3791 hapd.request("SET ext_eapol_frame_io 1")
3792 dev[0].request("SET ext_eapol_frame_io 1")
3793 hapd.request("WPS_PBC")
3794 dev[0].request("WPS_PBC")
3795
3796 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3797 if ev is None:
3798 raise Exception("Timeout on EAPOL-TX from hostapd")
3799
3800 res = dev[0].request("EAPOL_RX " + bssid + " 020000040193000501FFFF")
3801 if "OK" not in res:
3802 raise Exception("EAPOL_RX to wpa_supplicant failed")
46dea617
JM
3803
3804def test_ap_wps_iteration(dev, apdev):
3805 """WPS PIN and iterate through APs without selected registrar"""
3806 ssid = "test-wps-conf"
8b8a1864 3807 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
3808 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3809 "wpa_passphrase": "12345678", "wpa": "2",
3810 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
46dea617
JM
3811
3812 ssid2 = "test-wps-conf2"
8b8a1864 3813 hapd2 = hostapd.add_ap(apdev[1],
fab49f61
JM
3814 {"ssid": ssid2, "eap_server": "1", "wps_state": "2",
3815 "wpa_passphrase": "12345678", "wpa": "2",
3816 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
46dea617
JM
3817
3818 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3819 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
3820 dev[0].dump_monitor()
3821 pin = dev[0].request("WPS_PIN any")
3822
3823 # Wait for iteration through all WPS APs to happen before enabling any
3824 # Registrar.
3825 for i in range(2):
3826 ev = dev[0].wait_event(["Associated with"], timeout=30)
3827 if ev is None:
3828 raise Exception("No association seen")
3829 ev = dev[0].wait_event(["WPS-M2D"], timeout=10)
3830 if ev is None:
3831 raise Exception("No M2D from AP")
3832 dev[0].wait_disconnected()
3833
3834 # Verify that each AP requested PIN
3835 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3836 if ev is None:
3837 raise Exception("No WPS-PIN-NEEDED event from AP")
3838 ev = hapd2.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3839 if ev is None:
3840 raise Exception("No WPS-PIN-NEEDED event from AP2")
3841
3842 # Provide PIN to one of the APs and verify that connection gets formed
3843 hapd.request("WPS_PIN any " + pin)
3844 dev[0].wait_connected(timeout=30)
2272f5aa
JM
3845
3846def test_ap_wps_iteration_error(dev, apdev):
3847 """WPS AP iteration on no Selected Registrar and error case with an AP"""
3848 ssid = "test-wps-conf-pin"
8b8a1864 3849 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
3850 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3851 "wpa_passphrase": "12345678", "wpa": "2",
3852 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3853 "wps_independent": "1"})
2272f5aa
JM
3854 hapd.request("SET ext_eapol_frame_io 1")
3855 bssid = apdev[0]['bssid']
3856 pin = dev[0].wps_read_pin()
3857 dev[0].request("WPS_PIN any " + pin)
3858
3859 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3860 if ev is None:
3861 raise Exception("No EAPOL-TX (EAP-Request/Identity) from hostapd")
3862 dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
3863
3864 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3865 if ev is None:
3866 raise Exception("No EAPOL-TX (EAP-WSC/Start) from hostapd")
3867 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=5)
3868 if ev is None:
3869 raise Exception("No CTRL-EVENT-EAP-STARTED")
3870
3871 # Do not forward any more EAPOL frames to test wpa_supplicant behavior for
3872 # a case with an incorrectly behaving WPS AP.
3873
3874 # Start the real target AP and activate registrar on it.
8b8a1864 3875 hapd2 = hostapd.add_ap(apdev[1],
fab49f61
JM
3876 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3877 "wpa_passphrase": "12345678", "wpa": "2",
3878 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3879 "wps_independent": "1"})
2272f5aa
JM
3880 hapd2.request("WPS_PIN any " + pin)
3881
3882 dev[0].wait_disconnected(timeout=15)
3883 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
3884 if ev is None:
3885 raise Exception("No CTRL-EVENT-EAP-STARTED for the second AP")
3886 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
3887 if ev is None:
3888 raise Exception("No WPS-CRED-RECEIVED for the second AP")
3889 dev[0].wait_connected(timeout=15)
d6f6a86a 3890
9fd6804d 3891@remote_compatible
d6f6a86a
JM
3892def test_ap_wps_priority(dev, apdev):
3893 """WPS PIN provisioning with configured AP and wps_priority"""
3894 ssid = "test-wps-conf-pin"
6f334bf7 3895 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
3896 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3897 "wpa_passphrase": "12345678", "wpa": "2",
3898 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
d6f6a86a
JM
3899 logger.info("WPS provisioning step")
3900 pin = dev[0].wps_read_pin()
3901 hapd.request("WPS_PIN any " + pin)
3902 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3903 dev[0].dump_monitor()
3904 try:
3905 dev[0].request("SET wps_priority 6")
3906 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3907 dev[0].wait_connected(timeout=30)
3908 netw = dev[0].list_networks()
3909 prio = dev[0].get_network(netw[0]['id'], 'priority')
3910 if prio != '6':
3911 raise Exception("Unexpected network priority: " + prio)
3912 finally:
3913 dev[0].request("SET wps_priority 0")
2c3a0190 3914
9fd6804d 3915@remote_compatible
df1d01cf
JM
3916def test_ap_wps_and_non_wps(dev, apdev):
3917 """WPS and non-WPS AP in single hostapd process"""
fab49f61 3918 params = {"ssid": "wps", "eap_server": "1", "wps_state": "1"}
8b8a1864 3919 hapd = hostapd.add_ap(apdev[0], params)
df1d01cf 3920
fab49f61 3921 params = {"ssid": "no wps"}
8b8a1864 3922 hapd2 = hostapd.add_ap(apdev[1], params)
df1d01cf
JM
3923
3924 appin = hapd.request("WPS_AP_PIN random")
3925 if "FAIL" in appin:
3926 raise Exception("Could not generate random AP PIN")
3927 if appin not in hapd.request("WPS_AP_PIN get"):
3928 raise Exception("Could not fetch current AP PIN")
3929
3930 if "FAIL" in hapd.request("WPS_PBC"):
3931 raise Exception("WPS_PBC failed")
3932 if "FAIL" in hapd.request("WPS_CANCEL"):
3933 raise Exception("WPS_CANCEL failed")
3934
2c3a0190
JM
3935def test_ap_wps_init_oom(dev, apdev):
3936 """Initial AP configuration and OOM during PSK generation"""
3937 ssid = "test-wps"
fab49f61 3938 params = {"ssid": ssid, "eap_server": "1", "wps_state": "1"}
8b8a1864 3939 hapd = hostapd.add_ap(apdev[0], params)
2c3a0190 3940
5b52e1ad 3941 with alloc_fail(hapd, 1, "base64_gen_encode;?base64_encode;wps_build_cred"):
2c3a0190
JM
3942 pin = dev[0].wps_read_pin()
3943 hapd.request("WPS_PIN any " + pin)
3944 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3945 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3946 dev[0].wait_disconnected()
3947
3948 hapd.request("WPS_PIN any " + pin)
3949 dev[0].wait_connected(timeout=30)
ccf4d764 3950
9fd6804d 3951@remote_compatible
ccf4d764
JM
3952def test_ap_wps_er_oom(dev, apdev):
3953 """WPS ER OOM in XML processing"""
3954 try:
3955 _test_ap_wps_er_oom(dev, apdev)
3956 finally:
3957 dev[0].request("WPS_ER_STOP")
3958 dev[1].request("WPS_CANCEL")
3959 dev[0].request("DISCONNECT")
3960
3961def _test_ap_wps_er_oom(dev, apdev):
3962 ssid = "wps-er-ap-config"
3963 ap_pin = "12345670"
3964 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 3965 hostapd.add_ap(apdev[0],
fab49f61
JM
3966 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3967 "wpa_passphrase": "12345678", "wpa": "2",
3968 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3969 "device_name": "Wireless AP", "manufacturer": "Company",
3970 "model_name": "WAP", "model_number": "123",
3971 "serial_number": "12345", "device_type": "6-0050F204-1",
3972 "os_version": "01020300",
3973 "config_methods": "label push_button",
3974 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
ccf4d764
JM
3975
3976 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
3977
5b52e1ad
JM
3978 with alloc_fail(dev[0], 1,
3979 "base64_gen_decode;?base64_decode;xml_get_base64_item"):
ccf4d764
JM
3980 dev[0].request("WPS_ER_START ifname=lo")
3981 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=3)
3982 if ev is not None:
3983 raise Exception("Unexpected AP discovery")
3984
3985 dev[0].request("WPS_ER_STOP")
3986 dev[0].request("WPS_ER_START ifname=lo")
3987 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
3988 if ev is None:
3989 raise Exception("AP discovery timed out")
3990
3991 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
5b52e1ad
JM
3992 with alloc_fail(dev[0], 1,
3993 "base64_gen_decode;?base64_decode;xml_get_base64_item"):
ccf4d764
JM
3994 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
3995 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
3996 if ev is None:
3997 raise Exception("PBC scan failed")
3998 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
3999 if ev is None:
4000 raise Exception("Enrollee discovery timed out")
2602a2ff 4001
9fd6804d 4002@remote_compatible
c965ae03
JM
4003def test_ap_wps_er_init_oom(dev, apdev):
4004 """WPS ER and OOM during init"""
4005 try:
4006 _test_ap_wps_er_init_oom(dev, apdev)
4007 finally:
4008 dev[0].request("WPS_ER_STOP")
4009
4010def _test_ap_wps_er_init_oom(dev, apdev):
4011 with alloc_fail(dev[0], 1, "wps_er_init"):
4012 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
4013 raise Exception("WPS_ER_START succeeded during OOM")
4014 with alloc_fail(dev[0], 1, "http_server_init"):
4015 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
4016 raise Exception("WPS_ER_START succeeded during OOM")
4017 with alloc_fail(dev[0], 2, "http_server_init"):
4018 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
4019 raise Exception("WPS_ER_START succeeded during OOM")
9b35afd6 4020 with alloc_fail(dev[0], 1, "eloop_sock_table_add_sock;?eloop_register_sock;wps_er_ssdp_init"):
c965ae03
JM
4021 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
4022 raise Exception("WPS_ER_START succeeded during OOM")
4023 with fail_test(dev[0], 1, "os_get_random;wps_er_init"):
4024 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
4025 raise Exception("WPS_ER_START succeeded during os_get_random failure")
4026
9fd6804d 4027@remote_compatible
07536b18
JM
4028def test_ap_wps_er_init_fail(dev, apdev):
4029 """WPS ER init failure"""
4030 if "FAIL" not in dev[0].request("WPS_ER_START ifname=does-not-exist"):
4031 dev[0].request("WPS_ER_STOP")
4032 raise Exception("WPS_ER_START with non-existing ifname succeeded")
4033
2602a2ff
JM
4034def test_ap_wps_wpa_cli_action(dev, apdev, test_params):
4035 """WPS events and wpa_cli action script"""
8936b095
JM
4036 logdir = os.path.abspath(test_params['logdir'])
4037 pidfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.pid')
4038 logfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.res')
4039 actionfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.action.sh')
2602a2ff
JM
4040
4041 with open(actionfile, 'w') as f:
4042 f.write('#!/bin/sh\n')
4043 f.write('echo $* >> %s\n' % logfile)
4044 # Kill the process and wait some time before returning to allow all the
4045 # pending events to be processed with some of this happening after the
4046 # eloop SIGALRM signal has been scheduled.
4047 f.write('if [ $2 = "WPS-SUCCESS" -a -r %s ]; then kill `cat %s`; sleep 1; fi\n' % (pidfile, pidfile))
4048
8936b095
JM
4049 os.chmod(actionfile, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC |
4050 stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
2602a2ff
JM
4051
4052 ssid = "test-wps-conf"
6f334bf7 4053 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
4054 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
4055 "wpa_passphrase": "12345678", "wpa": "2",
4056 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2602a2ff
JM
4057
4058 prg = os.path.join(test_params['logdir'],
4059 'alt-wpa_supplicant/wpa_supplicant/wpa_cli')
4060 if not os.path.exists(prg):
4061 prg = '../../wpa_supplicant/wpa_cli'
fab49f61 4062 arg = [prg, '-P', pidfile, '-B', '-i', dev[0].ifname, '-a', actionfile]
2602a2ff
JM
4063 subprocess.call(arg)
4064
fab49f61 4065 arg = ['ps', 'ax']
2602a2ff 4066 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
04fa9fc7 4067 out = cmd.communicate()[0].decode()
2602a2ff
JM
4068 cmd.wait()
4069 logger.debug("Processes:\n" + out)
4070 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) not in out:
4071 raise Exception("Did not see wpa_cli running")
4072
4073 hapd.request("WPS_PIN any 12345670")
4074 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4075 dev[0].dump_monitor()
4076 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
4077 dev[0].wait_connected(timeout=30)
4078
4079 for i in range(30):
4080 if not os.path.exists(pidfile):
4081 break
4082 time.sleep(0.1)
4083
4084 if not os.path.exists(logfile):
4085 raise Exception("wpa_cli action results file not found")
4086 with open(logfile, 'r') as f:
4087 res = f.read()
4088 if "WPS-SUCCESS" not in res:
4089 raise Exception("WPS-SUCCESS event not seen in action file")
4090
fab49f61 4091 arg = ['ps', 'ax']
2602a2ff 4092 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
04fa9fc7 4093 out = cmd.communicate()[0].decode()
2602a2ff
JM
4094 cmd.wait()
4095 logger.debug("Remaining processes:\n" + out)
4096 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) in out:
4097 raise Exception("wpa_cli still running")
4098
4099 if os.path.exists(pidfile):
4100 raise Exception("PID file not removed")
c965ae03
JM
4101
4102def test_ap_wps_er_ssdp_proto(dev, apdev):
4103 """WPS ER SSDP protocol testing"""
4104 try:
4105 _test_ap_wps_er_ssdp_proto(dev, apdev)
4106 finally:
4107 dev[0].request("WPS_ER_STOP")
4108
4109def _test_ap_wps_er_ssdp_proto(dev, apdev):
4110 socket.setdefaulttimeout(1)
4111 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4112 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4113 sock.bind(("239.255.255.250", 1900))
4114 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo foo"):
4115 raise Exception("Invalid filter accepted")
4116 if "OK" not in dev[0].request("WPS_ER_START ifname=lo 1.2.3.4"):
4117 raise Exception("WPS_ER_START with filter failed")
fab49f61 4118 (msg, addr) = sock.recvfrom(1000)
cc02ce96 4119 msg = msg.decode()
c965ae03
JM
4120 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4121 if "M-SEARCH" not in msg:
4122 raise Exception("Not an M-SEARCH")
cc02ce96 4123 sock.sendto(b"FOO", addr)
c965ae03
JM
4124 time.sleep(0.1)
4125 dev[0].request("WPS_ER_STOP")
4126
4127 dev[0].request("WPS_ER_START ifname=lo")
fab49f61 4128 (msg, addr) = sock.recvfrom(1000)
cc02ce96 4129 msg = msg.decode()
c965ae03
JM
4130 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4131 if "M-SEARCH" not in msg:
4132 raise Exception("Not an M-SEARCH")
cc02ce96
MH
4133 sock.sendto(b"FOO", addr)
4134 sock.sendto(b"HTTP/1.1 200 OK\r\nFOO\r\n\r\n", addr)
4135 sock.sendto(b"HTTP/1.1 200 OK\r\nNTS:foo\r\n\r\n", addr)
4136 sock.sendto(b"HTTP/1.1 200 OK\r\nNTS:ssdp:byebye\r\n\r\n", addr)
4137 sock.sendto(b"HTTP/1.1 200 OK\r\ncache-control: foo=1\r\n\r\n", addr)
4138 sock.sendto(b"HTTP/1.1 200 OK\r\ncache-control: max-age=1\r\n\r\n", addr)
4139 sock.sendto(b"HTTP/1.1 200 OK\r\nusn:\r\n\r\n", addr)
4140 sock.sendto(b"HTTP/1.1 200 OK\r\nusn:foo\r\n\r\n", addr)
4141 sock.sendto(b"HTTP/1.1 200 OK\r\nusn: uuid:\r\n\r\n", addr)
4142 sock.sendto(b"HTTP/1.1 200 OK\r\nusn: uuid: \r\n\r\n", addr)
4143 sock.sendto(b"HTTP/1.1 200 OK\r\nusn: uuid: foo\r\n\r\n", addr)
4144 sock.sendto(b"HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\n\r\n", addr)
4145 sock.sendto(b"HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nNTS:ssdp:byebye\r\n\r\n", addr)
4146 sock.sendto(b"HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\n\r\n", addr)
c965ae03 4147 with alloc_fail(dev[0], 1, "wps_er_ap_add"):
cc02ce96 4148 sock.sendto(b"HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
c965ae03
JM
4149 time.sleep(0.1)
4150 with alloc_fail(dev[0], 2, "wps_er_ap_add"):
cc02ce96 4151 sock.sendto(b"HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
c965ae03
JM
4152 time.sleep(0.1)
4153
4154 # Add an AP with bogus URL
cc02ce96 4155 sock.sendto(b"HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
c965ae03 4156 # Update timeout on AP without updating URL
cc02ce96 4157 sock.sendto(b"HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1:12345/foo.xml\r\ncache-control:max-age=1\r\n\r\n", addr)
c965ae03
JM
4158 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4159 if ev is None:
4160 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4161
4162 # Add an AP with a valid URL (but no server listing to it)
cc02ce96 4163 sock.sendto(b"HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1:12345/foo.xml\r\ncache-control:max-age=1\r\n\r\n", addr)
c965ae03
JM
4164 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4165 if ev is None:
4166 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4167
4168 sock.close()
4169
4170wps_event_url = None
4171
6aaa661a
JM
4172def gen_upnp_info(eventSubURL='wps_event', controlURL='wps_control',
4173 udn='uuid:27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'):
4c3ae1c0 4174 payload = '''<?xml version="1.0"?>
c965ae03
JM
4175<root xmlns="urn:schemas-upnp-org:device-1-0">
4176<specVersion>
4177<major>1</major>
4178<minor>0</minor>
4179</specVersion>
4180<device>
4181<deviceType>urn:schemas-wifialliance-org:device:WFADevice:1</deviceType>
4182<friendlyName>WPS Access Point</friendlyName>
4183<manufacturer>Company</manufacturer>
4184<modelName>WAP</modelName>
4185<modelNumber>123</modelNumber>
4186<serialNumber>12345</serialNumber>
6aaa661a
JM
4187'''
4188 if udn:
4189 payload += '<UDN>' + udn + '</UDN>'
4190 payload += '''<serviceList>
c965ae03
JM
4191<service>
4192<serviceType>urn:schemas-wifialliance-org:service:WFAWLANConfig:1</serviceType>
4193<serviceId>urn:wifialliance-org:serviceId:WFAWLANConfig1</serviceId>
4194<SCPDURL>wps_scpd.xml</SCPDURL>
4c3ae1c0 4195'''
6aaa661a
JM
4196 if controlURL:
4197 payload += '<controlURL>' + controlURL + '</controlURL>\n'
4c3ae1c0 4198 if eventSubURL:
6aaa661a 4199 payload += '<eventSubURL>' + eventSubURL + '</eventSubURL>\n'
4c3ae1c0 4200 payload += '''</service>
c965ae03
JM
4201</serviceList>
4202</device>
4203</root>
4204'''
4c3ae1c0
JM
4205 hdr = 'HTTP/1.1 200 OK\r\n' + \
4206 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4207 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4208 'Connection: close\r\n' + \
4209 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4210 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
f94df3c0 4211 return (hdr + payload).encode()
4c3ae1c0 4212
6aaa661a 4213def gen_wps_control(payload_override=None):
4c3ae1c0 4214 payload = '''<?xml version="1.0"?>
c965ae03
JM
4215<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4216<s:Body>
4217<u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4218<NewDeviceInfo>EEoAARAQIgABBBBHABAn6oAanlxOc72C+Jy80Q1+ECAABgIAAAADABAaABCJZ7DPtbU3Ust9
4219Z3wJF07WEDIAwH45D3i1OqB7eJGwTzqeapS71h3KyXncK2xJZ+xqScrlorNEg6LijBJzG2Ca
4220+FZli0iliDJd397yAx/jk4nFXco3q5ylBSvSw9dhJ5u1xBKSnTilKGlUHPhLP75PUqM3fot9
42217zwtFZ4bx6x1sBA6oEe2d0aUJmLumQGCiKEIWlnxs44zego/2tAe81bDzdPBM7o5HH/FUhD+
4222KoGzFXp51atP+1n9Vta6AkI0Vye99JKLcC6Md9dMJltSVBgd4Xc4lRAEAAIAIxAQAAIADRAN
4223AAEBEAgAAgAEEEQAAQIQIQAHQ29tcGFueRAjAANXQVAQJAADMTIzEEIABTEyMzQ1EFQACAAG
4224AFDyBAABEBEAC1dpcmVsZXNzIEFQEDwAAQEQAgACAAAQEgACAAAQCQACAAAQLQAEgQIDABBJ
4225AAYANyoAASA=
4226</NewDeviceInfo>
4227</u:GetDeviceInfoResponse>
4228</s:Body>
4229</s:Envelope>
4230'''
6aaa661a
JM
4231 if payload_override:
4232 payload = payload_override
4c3ae1c0
JM
4233 hdr = 'HTTP/1.1 200 OK\r\n' + \
4234 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4235 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4236 'Connection: close\r\n' + \
4237 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4238 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
f94df3c0 4239 return (hdr + payload).encode()
4c3ae1c0 4240
6aaa661a 4241def gen_wps_event(sid='uuid:7eb3342a-8a5f-47fe-a585-0785bfec6d8a'):
4c3ae1c0
JM
4242 payload = ""
4243 hdr = 'HTTP/1.1 200 OK\r\n' + \
4244 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4245 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4246 'Connection: close\r\n' + \
6aaa661a
JM
4247 'Content-Length: ' + str(len(payload)) + '\r\n'
4248 if sid:
4249 hdr += 'SID: ' + sid + '\r\n'
4250 hdr += 'Timeout: Second-1801\r\n' + \
4c3ae1c0 4251 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
f94df3c0 4252 return (hdr + payload).encode()
4c3ae1c0 4253
9c06eda0 4254class WPSAPHTTPServer(StreamRequestHandler):
4c3ae1c0 4255 def handle(self):
59aecb1c 4256 data = self.rfile.readline().decode().strip()
4c3ae1c0
JM
4257 logger.info("HTTP server received: " + data)
4258 while True:
59aecb1c 4259 hdr = self.rfile.readline().decode().strip()
4c3ae1c0
JM
4260 if len(hdr) == 0:
4261 break
4262 logger.info("HTTP header: " + hdr)
4263 if "CALLBACK:" in hdr:
4264 global wps_event_url
4265 wps_event_url = hdr.split(' ')[1].strip('<>')
4266
4267 if "GET /foo.xml" in data:
6aaa661a
JM
4268 self.handle_upnp_info()
4269 elif "POST /wps_control" in data:
4270 self.handle_wps_control()
4271 elif "SUBSCRIBE /wps_event" in data:
4272 self.handle_wps_event()
24b7f282
JM
4273 else:
4274 self.handle_others(data)
6aaa661a
JM
4275
4276 def handle_upnp_info(self):
4277 self.wfile.write(gen_upnp_info())
4c3ae1c0 4278
6aaa661a
JM
4279 def handle_wps_control(self):
4280 self.wfile.write(gen_wps_control())
c965ae03 4281
6aaa661a
JM
4282 def handle_wps_event(self):
4283 self.wfile.write(gen_wps_event())
c965ae03 4284
24b7f282
JM
4285 def handle_others(self, data):
4286 logger.info("Ignore HTTP request: " + data)
4287
9c06eda0 4288class MyTCPServer(TCPServer):
4c3ae1c0
JM
4289 def __init__(self, addr, handler):
4290 self.allow_reuse_address = True
9c06eda0 4291 TCPServer.__init__(self, addr, handler)
c965ae03 4292
24b7f282
JM
4293def wps_er_start(dev, http_server, max_age=1, wait_m_search=False,
4294 location_url=None):
c965ae03
JM
4295 socket.setdefaulttimeout(1)
4296 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4297 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4298 sock.bind(("239.255.255.250", 1900))
4c3ae1c0 4299 dev.request("WPS_ER_START ifname=lo")
24b7f282 4300 for i in range(100):
fab49f61 4301 (msg, addr) = sock.recvfrom(1000)
cc02ce96 4302 msg = msg.decode()
24b7f282
JM
4303 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4304 if "M-SEARCH" in msg:
4305 break
4306 if not wait_m_search:
4307 raise Exception("Not an M-SEARCH")
4308 if i == 99:
4309 raise Exception("No M-SEARCH seen")
c965ae03
JM
4310
4311 # Add an AP with a valid URL and server listing to it
4c3ae1c0 4312 server = MyTCPServer(("127.0.0.1", 12345), http_server)
24b7f282
JM
4313 if not location_url:
4314 location_url = 'http://127.0.0.1:12345/foo.xml'
cc02ce96 4315 sock.sendto(("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:%s\r\ncache-control:max-age=%d\r\n\r\n" % (location_url, max_age)).encode(), addr)
c965ae03 4316 server.timeout = 1
fab49f61 4317 return server, sock
4c3ae1c0
JM
4318
4319def wps_er_stop(dev, sock, server, on_alloc_fail=False):
4320 sock.close()
4321 server.server_close()
4322
4323 if on_alloc_fail:
4324 done = False
4325 for i in range(50):
4326 res = dev.request("GET_ALLOC_FAIL")
4327 if res.startswith("0:"):
4328 done = True
4329 break
4330 time.sleep(0.1)
4331 if not done:
4332 raise Exception("No allocation failure reported")
4333 else:
4334 ev = dev.wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4335 if ev is None:
4336 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4337 dev.request("WPS_ER_STOP")
4338
24b7f282 4339def run_wps_er_proto_test(dev, handler, no_event_url=False, location_url=None):
6aaa661a
JM
4340 try:
4341 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
fab49f61 4342 server, sock = wps_er_start(dev, handler, location_url=location_url)
6aaa661a
JM
4343 global wps_event_url
4344 wps_event_url = None
4345 server.handle_request()
4346 server.handle_request()
4347 server.handle_request()
4348 server.server_close()
4349 if no_event_url:
4350 if wps_event_url:
4351 raise Exception("Received event URL unexpectedly")
4352 return
4353 if wps_event_url is None:
4354 raise Exception("Did not get event URL")
4355 logger.info("Event URL: " + wps_event_url)
4356 finally:
24b7f282 4357 dev.request("WPS_ER_STOP")
6aaa661a 4358
18478107 4359def send_wlanevent(url, uuid, data, no_response=False):
9c06eda0 4360 conn = HTTPConnection(url.netloc)
6aaa661a
JM
4361 payload = '''<?xml version="1.0" encoding="utf-8"?>
4362<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4363<e:property><STAStatus>1</STAStatus></e:property>
4364<e:property><APStatus>1</APStatus></e:property>
4365<e:property><WLANEvent>'''
c4e333fa 4366 payload += base64.b64encode(data).decode()
6aaa661a 4367 payload += '</WLANEvent></e:property></e:propertyset>'
fab49f61
JM
4368 headers = {"Content-type": 'text/xml; charset="utf-8"',
4369 "Server": "Unspecified, UPnP/1.0, Unspecified",
4370 "HOST": url.netloc,
4371 "NT": "upnp:event",
4372 "SID": "uuid:" + uuid,
4373 "SEQ": "0",
4374 "Content-Length": str(len(payload))}
6aaa661a 4375 conn.request("NOTIFY", url.path, payload, headers)
18478107
JM
4376 if no_response:
4377 try:
4378 conn.getresponse()
bab493b9 4379 except Exception as e:
18478107
JM
4380 pass
4381 return
6aaa661a
JM
4382 resp = conn.getresponse()
4383 if resp.status != 200:
4384 raise Exception("Unexpected HTTP response: %d" % resp.status)
4385
4c3ae1c0
JM
4386def test_ap_wps_er_http_proto(dev, apdev):
4387 """WPS ER HTTP protocol testing"""
4388 try:
4389 _test_ap_wps_er_http_proto(dev, apdev)
4390 finally:
4391 dev[0].request("WPS_ER_STOP")
4392
4393def _test_ap_wps_er_http_proto(dev, apdev):
4394 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
fab49f61 4395 server, sock = wps_er_start(dev[0], WPSAPHTTPServer, max_age=15)
c965ae03
JM
4396 global wps_event_url
4397 wps_event_url = None
4398 server.handle_request()
4399 server.handle_request()
4400 server.handle_request()
4401 server.server_close()
4402 if wps_event_url is None:
4403 raise Exception("Did not get event URL")
4404 logger.info("Event URL: " + wps_event_url)
4405
4406 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
4407 if ev is None:
4408 raise Exception("No WPS-ER-AP-ADD event")
4409 if uuid not in ev:
4410 raise Exception("UUID mismatch")
4411
4412 sock.close()
4413
4414 logger.info("Valid Probe Request notification")
9c06eda0
MH
4415 url = urlparse(wps_event_url)
4416 conn = HTTPConnection(url.netloc)
c965ae03
JM
4417 payload = '''<?xml version="1.0" encoding="utf-8"?>
4418<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4419<e:property><STAStatus>1</STAStatus></e:property>
4420<e:property><APStatus>1</APStatus></e:property>
4421<e:property><WLANEvent>ATAyOjAwOjAwOjAwOjAwOjAwEEoAARAQOgABAhAIAAIxSBBHABA2LbR7pTpRkYj7VFi5hrLk
4422EFQACAAAAAAAAAAAEDwAAQMQAgACAAAQCQACAAAQEgACAAAQIQABIBAjAAEgECQAASAQEQAI
4423RGV2aWNlIEEQSQAGADcqAAEg
4424</WLANEvent></e:property>
4425</e:propertyset>
4426'''
fab49f61
JM
4427 headers = {"Content-type": 'text/xml; charset="utf-8"',
4428 "Server": "Unspecified, UPnP/1.0, Unspecified",
4429 "HOST": url.netloc,
4430 "NT": "upnp:event",
4431 "SID": "uuid:" + uuid,
4432 "SEQ": "0",
4433 "Content-Length": str(len(payload))}
c965ae03
JM
4434 conn.request("NOTIFY", url.path, payload, headers)
4435 resp = conn.getresponse()
4436 if resp.status != 200:
4437 raise Exception("Unexpected HTTP response: %d" % resp.status)
4438
4439 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=5)
4440 if ev is None:
4441 raise Exception("No WPS-ER-ENROLLEE-ADD event")
4442 if "362db47b-a53a-5191-88fb-5458b986b2e4" not in ev:
4443 raise Exception("No Enrollee UUID match")
4444
4445 logger.info("Incorrect event URL AP id")
9c06eda0 4446 conn = HTTPConnection(url.netloc)
c965ae03
JM
4447 conn.request("NOTIFY", url.path + '123', payload, headers)
4448 resp = conn.getresponse()
4449 if resp.status != 404:
4450 raise Exception("Unexpected HTTP response: %d" % resp.status)
4451
4452 logger.info("Missing AP id")
9c06eda0 4453 conn = HTTPConnection(url.netloc)
c965ae03
JM
4454 conn.request("NOTIFY", '/event/' + url.path.split('/')[2],
4455 payload, headers)
4456 time.sleep(0.1)
4457
4458 logger.info("Incorrect event URL event id")
9c06eda0 4459 conn = HTTPConnection(url.netloc)
c965ae03
JM
4460 conn.request("NOTIFY", '/event/123456789/123', payload, headers)
4461 time.sleep(0.1)
4462
4463 logger.info("Incorrect event URL prefix")
9c06eda0 4464 conn = HTTPConnection(url.netloc)
c965ae03
JM
4465 conn.request("NOTIFY", '/foobar/123456789/123', payload, headers)
4466 resp = conn.getresponse()
4467 if resp.status != 404:
4468 raise Exception("Unexpected HTTP response: %d" % resp.status)
4469
4470 logger.info("Unsupported request")
9c06eda0 4471 conn = HTTPConnection(url.netloc)
c965ae03
JM
4472 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4473 resp = conn.getresponse()
4474 if resp.status != 501:
4475 raise Exception("Unexpected HTTP response: %d" % resp.status)
4476
4477 logger.info("Unsupported request and OOM")
4478 with alloc_fail(dev[0], 1, "wps_er_http_req"):
9c06eda0 4479 conn = HTTPConnection(url.netloc)
c965ae03
JM
4480 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4481 time.sleep(0.5)
4c3ae1c0 4482
6aaa661a 4483 logger.info("Too short WLANEvent")
15dfcb69 4484 data = b'\x00'
6aaa661a
JM
4485 send_wlanevent(url, uuid, data)
4486
4487 logger.info("Invalid WLANEventMAC")
15dfcb69 4488 data = b'\x00qwertyuiopasdfghjklzxcvbnm'
6aaa661a
JM
4489 send_wlanevent(url, uuid, data)
4490
4491 logger.info("Unknown WLANEventType")
15dfcb69 4492 data = b'\xff02:00:00:00:00:00'
6aaa661a
JM
4493 send_wlanevent(url, uuid, data)
4494
4495 logger.info("Probe Request notification without any attributes")
15dfcb69 4496 data = b'\x0102:00:00:00:00:00'
6aaa661a
JM
4497 send_wlanevent(url, uuid, data)
4498
4499 logger.info("Probe Request notification with invalid attribute")
15dfcb69 4500 data = b'\x0102:00:00:00:00:00\xff'
6aaa661a
JM
4501 send_wlanevent(url, uuid, data)
4502
4503 logger.info("EAP message without any attributes")
15dfcb69 4504 data = b'\x0202:00:00:00:00:00'
6aaa661a
JM
4505 send_wlanevent(url, uuid, data)
4506
4507 logger.info("EAP message with invalid attribute")
15dfcb69 4508 data = b'\x0202:00:00:00:00:00\xff'
6aaa661a
JM
4509 send_wlanevent(url, uuid, data)
4510
4511 logger.info("EAP message from new STA and not M1")
15dfcb69 4512 data = b'\x0202:ff:ff:ff:ff:ff' + b'\x10\x22\x00\x01\x05'
6aaa661a
JM
4513 send_wlanevent(url, uuid, data)
4514
4515 logger.info("EAP message: M1")
15dfcb69
MH
4516 data = b'\x0202:00:00:00:00:00'
4517 data += b'\x10\x22\x00\x01\x04'
4518 data += b'\x10\x47\x00\x10' + 16 * b'\x00'
4519 data += b'\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4520 data += b'\x10\x1a\x00\x10' + 16 * b'\x00'
4521 data += b'\x10\x32\x00\xc0' + 192 * b'\x00'
4522 data += b'\x10\x04\x00\x02\x00\x00'
4523 data += b'\x10\x10\x00\x02\x00\x00'
4524 data += b'\x10\x0d\x00\x01\x00'
4525 data += b'\x10\x08\x00\x02\x00\x00'
4526 data += b'\x10\x44\x00\x01\x00'
4527 data += b'\x10\x21\x00\x00'
4528 data += b'\x10\x23\x00\x00'
4529 data += b'\x10\x24\x00\x00'
4530 data += b'\x10\x42\x00\x00'
4531 data += b'\x10\x54\x00\x08' + 8 * b'\x00'
4532 data += b'\x10\x11\x00\x00'
4533 data += b'\x10\x3c\x00\x01\x00'
4534 data += b'\x10\x02\x00\x02\x00\x00'
4535 data += b'\x10\x12\x00\x02\x00\x00'
4536 data += b'\x10\x09\x00\x02\x00\x00'
4537 data += b'\x10\x2d\x00\x04\x00\x00\x00\x00'
6aaa661a
JM
4538 m1 = data
4539 send_wlanevent(url, uuid, data)
4540
4541 logger.info("EAP message: WSC_ACK")
15dfcb69 4542 data = b'\x0202:00:00:00:00:00' + b'\x10\x22\x00\x01\x0d'
6aaa661a
JM
4543 send_wlanevent(url, uuid, data)
4544
4545 logger.info("EAP message: M1")
4546 send_wlanevent(url, uuid, m1)
4547
4548 logger.info("EAP message: WSC_NACK")
15dfcb69 4549 data = b'\x0202:00:00:00:00:00' + b'\x10\x22\x00\x01\x0e'
6aaa661a
JM
4550 send_wlanevent(url, uuid, data)
4551
4552 logger.info("EAP message: M1 - Too long attribute values")
15dfcb69
MH
4553 data = b'\x0202:00:00:00:00:00'
4554 data += b'\x10\x11\x00\x21' + 33 * b'\x00'
4555 data += b'\x10\x45\x00\x21' + 33 * b'\x00'
4556 data += b'\x10\x42\x00\x21' + 33 * b'\x00'
4557 data += b'\x10\x24\x00\x21' + 33 * b'\x00'
4558 data += b'\x10\x23\x00\x21' + 33 * b'\x00'
4559 data += b'\x10\x21\x00\x41' + 65 * b'\x00'
4560 data += b'\x10\x49\x00\x09\x00\x37\x2a\x05\x02\x00\x00\x05\x00'
6aaa661a
JM
4561 send_wlanevent(url, uuid, data)
4562
4563 logger.info("EAP message: M1 missing UUID-E")
15dfcb69
MH
4564 data = b'\x0202:00:00:00:00:00'
4565 data += b'\x10\x22\x00\x01\x04'
6aaa661a
JM
4566 send_wlanevent(url, uuid, data)
4567
4568 logger.info("EAP message: M1 missing MAC Address")
15dfcb69 4569 data += b'\x10\x47\x00\x10' + 16 * b'\x00'
6aaa661a
JM
4570 send_wlanevent(url, uuid, data)
4571
4572 logger.info("EAP message: M1 missing Enrollee Nonce")
15dfcb69 4573 data += b'\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
6aaa661a
JM
4574 send_wlanevent(url, uuid, data)
4575
4576 logger.info("EAP message: M1 missing Public Key")
15dfcb69 4577 data += b'\x10\x1a\x00\x10' + 16 * b'\x00'
6aaa661a
JM
4578 send_wlanevent(url, uuid, data)
4579
4580 logger.info("EAP message: M1 missing Authentication Type flags")
15dfcb69 4581 data += b'\x10\x32\x00\xc0' + 192 * b'\x00'
6aaa661a
JM
4582 send_wlanevent(url, uuid, data)
4583
4584 logger.info("EAP message: M1 missing Encryption Type Flags")
15dfcb69 4585 data += b'\x10\x04\x00\x02\x00\x00'
6aaa661a
JM
4586 send_wlanevent(url, uuid, data)
4587
4588 logger.info("EAP message: M1 missing Connection Type flags")
15dfcb69 4589 data += b'\x10\x10\x00\x02\x00\x00'
6aaa661a
JM
4590 send_wlanevent(url, uuid, data)
4591
4592 logger.info("EAP message: M1 missing Config Methods")
15dfcb69 4593 data += b'\x10\x0d\x00\x01\x00'
6aaa661a
JM
4594 send_wlanevent(url, uuid, data)
4595
4596 logger.info("EAP message: M1 missing Wi-Fi Protected Setup State")
15dfcb69 4597 data += b'\x10\x08\x00\x02\x00\x00'
6aaa661a
JM
4598 send_wlanevent(url, uuid, data)
4599
4600 logger.info("EAP message: M1 missing Manufacturer")
15dfcb69 4601 data += b'\x10\x44\x00\x01\x00'
6aaa661a
JM
4602 send_wlanevent(url, uuid, data)
4603
4604 logger.info("EAP message: M1 missing Model Name")
15dfcb69 4605 data += b'\x10\x21\x00\x00'
6aaa661a
JM
4606 send_wlanevent(url, uuid, data)
4607
4608 logger.info("EAP message: M1 missing Model Number")
15dfcb69 4609 data += b'\x10\x23\x00\x00'
6aaa661a
JM
4610 send_wlanevent(url, uuid, data)
4611
4612 logger.info("EAP message: M1 missing Serial Number")
15dfcb69 4613 data += b'\x10\x24\x00\x00'
6aaa661a
JM
4614 send_wlanevent(url, uuid, data)
4615
4616 logger.info("EAP message: M1 missing Primary Device Type")
15dfcb69 4617 data += b'\x10\x42\x00\x00'
6aaa661a
JM
4618 send_wlanevent(url, uuid, data)
4619
4620 logger.info("EAP message: M1 missing Device Name")
15dfcb69 4621 data += b'\x10\x54\x00\x08' + 8 * b'\x00'
6aaa661a
JM
4622 send_wlanevent(url, uuid, data)
4623
4624 logger.info("EAP message: M1 missing RF Bands")
15dfcb69 4625 data += b'\x10\x11\x00\x00'
6aaa661a
JM
4626 send_wlanevent(url, uuid, data)
4627
4628 logger.info("EAP message: M1 missing Association State")
15dfcb69 4629 data += b'\x10\x3c\x00\x01\x00'
6aaa661a
JM
4630 send_wlanevent(url, uuid, data)
4631
4632 logger.info("EAP message: M1 missing Device Password ID")
15dfcb69 4633 data += b'\x10\x02\x00\x02\x00\x00'
6aaa661a
JM
4634 send_wlanevent(url, uuid, data)
4635
4636 logger.info("EAP message: M1 missing Configuration Error")
15dfcb69 4637 data += b'\x10\x12\x00\x02\x00\x00'
6aaa661a
JM
4638 send_wlanevent(url, uuid, data)
4639
4640 logger.info("EAP message: M1 missing OS Version")
15dfcb69 4641 data += b'\x10\x09\x00\x02\x00\x00'
6aaa661a 4642 send_wlanevent(url, uuid, data)
4c3ae1c0 4643
24b7f282
JM
4644 logger.info("Check max concurrent requests")
4645 addr = (url.hostname, url.port)
4646 socks = {}
4647 for i in range(20):
4648 socks[i] = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4649 socket.IPPROTO_TCP)
e5d3e13a
JM
4650 socks[i].settimeout(10)
4651 socks[i].connect(addr)
24b7f282 4652 for i in range(20):
cc02ce96 4653 socks[i].send(b"GET / HTTP/1.1\r\n\r\n")
24b7f282
JM
4654 count = 0
4655 for i in range(20):
4656 try:
cc02ce96 4657 res = socks[i].recv(100).decode()
24b7f282
JM
4658 if "HTTP/1" in res:
4659 count += 1
6f9b4de2
JM
4660 else:
4661 logger.info("recv[%d]: len=%d" % (i, len(res)))
24b7f282
JM
4662 except:
4663 pass
4664 socks[i].close()
4665 logger.info("%d concurrent HTTP GET operations returned response" % count)
6f9b4de2 4666 if count < 8:
24b7f282
JM
4667 raise Exception("Too few concurrent HTTP connections accepted")
4668
4669 logger.info("OOM in HTTP server")
fab49f61
JM
4670 for func in ["http_request_init", "httpread_create",
4671 "eloop_register_timeout;httpread_create",
4672 "eloop_sock_table_add_sock;?eloop_register_sock;httpread_create",
4673 "httpread_hdr_analyze"]:
24b7f282
JM
4674 with alloc_fail(dev[0], 1, func):
4675 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4676 socket.IPPROTO_TCP)
4677 sock.connect(addr)
cc02ce96 4678 sock.send(b"GET / HTTP/1.1\r\n\r\n")
24b7f282
JM
4679 try:
4680 sock.recv(100)
4681 except:
4682 pass
4683 sock.close()
4684
4685 logger.info("Invalid HTTP header")
fab49f61
JM
4686 for req in [" GET / HTTP/1.1\r\n\r\n",
4687 "HTTP/1.1 200 OK\r\n\r\n",
4688 "HTTP/\r\n\r\n",
4689 "GET %%a%aa% HTTP/1.1\r\n\r\n",
4690 "GET / HTTP/1.1\r\n FOO\r\n\r\n",
4691 "NOTIFY / HTTP/1.1\r\n" + 4097*'a' + '\r\n\r\n',
4692 "NOTIFY / HTTP/1.1\r\n\r\n" + 8193*'a',
4693 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n foo\r\n",
4694 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n1\r\nfoo\r\n",
4695 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\n",
4696 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\naa\ra\r\n\ra"]:
24b7f282
JM
4697 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4698 socket.IPPROTO_TCP)
4699 sock.settimeout(0.1)
4700 sock.connect(addr)
cc02ce96 4701 sock.send(req.encode())
24b7f282
JM
4702 try:
4703 sock.recv(100)
4704 except:
4705 pass
4706 sock.close()
4707
4708 with alloc_fail(dev[0], 2, "httpread_read_handler"):
4709 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4710 socket.IPPROTO_TCP)
4711 sock.connect(addr)
cc02ce96 4712 sock.send(b"NOTIFY / HTTP/1.1\r\n\r\n" + 4500 * b'a')
24b7f282
JM
4713 try:
4714 sock.recv(100)
4715 except:
4716 pass
4717 sock.close()
4718
9c06eda0 4719 conn = HTTPConnection(url.netloc)
24b7f282 4720 payload = '<foo'
fab49f61
JM
4721 headers = {"Content-type": 'text/xml; charset="utf-8"',
4722 "Server": "Unspecified, UPnP/1.0, Unspecified",
4723 "HOST": url.netloc,
4724 "NT": "upnp:event",
4725 "SID": "uuid:" + uuid,
4726 "SEQ": "0",
4727 "Content-Length": str(len(payload))}
24b7f282
JM
4728 conn.request("NOTIFY", url.path, payload, headers)
4729 resp = conn.getresponse()
4730 if resp.status != 200:
4731 raise Exception("Unexpected HTTP response: %d" % resp.status)
4732
9c06eda0 4733 conn = HTTPConnection(url.netloc)
24b7f282 4734 payload = '<WLANEvent foo></WLANEvent>'
fab49f61
JM
4735 headers = {"Content-type": 'text/xml; charset="utf-8"',
4736 "Server": "Unspecified, UPnP/1.0, Unspecified",
4737 "HOST": url.netloc,
4738 "NT": "upnp:event",
4739 "SID": "uuid:" + uuid,
4740 "SEQ": "0",
4741 "Content-Length": str(len(payload))}
24b7f282
JM
4742 conn.request("NOTIFY", url.path, payload, headers)
4743 resp = conn.getresponse()
4744 if resp.status != 200:
4745 raise Exception("Unexpected HTTP response: %d" % resp.status)
4746
4747 with alloc_fail(dev[0], 1, "xml_get_first_item"):
15dfcb69 4748 send_wlanevent(url, uuid, b'')
24b7f282
JM
4749
4750 with alloc_fail(dev[0], 1, "wpabuf_alloc_ext_data;xml_get_base64_item"):
15dfcb69 4751 send_wlanevent(url, uuid, b'foo')
24b7f282 4752
fab49f61
JM
4753 for func in ["wps_init",
4754 "wps_process_manufacturer",
4755 "wps_process_model_name",
4756 "wps_process_model_number",
4757 "wps_process_serial_number",
4758 "wps_process_dev_name"]:
24b7f282
JM
4759 with alloc_fail(dev[0], 1, func):
4760 send_wlanevent(url, uuid, m1)
4761
18478107
JM
4762 with alloc_fail(dev[0], 1, "wps_er_http_resp_ok"):
4763 send_wlanevent(url, uuid, m1, no_response=True)
4764
4765 with alloc_fail(dev[0], 1, "wps_er_http_resp_not_found"):
9c06eda0 4766 url2 = urlparse(wps_event_url.replace('/event/', '/notfound/'))
18478107
JM
4767 send_wlanevent(url2, uuid, m1, no_response=True)
4768
3d105cdf 4769 logger.info("EAP message: M1")
15dfcb69
MH
4770 data = b'\x0202:11:22:00:00:00'
4771 data += b'\x10\x22\x00\x01\x04'
4772 data += b'\x10\x47\x00\x10' + 16 * b'\x00'
4773 data += b'\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4774 data += b'\x10\x1a\x00\x10' + 16 * b'\x00'
4775 data += b'\x10\x32\x00\xc0' + 192 * b'\x00'
4776 data += b'\x10\x04\x00\x02\x00\x00'
4777 data += b'\x10\x10\x00\x02\x00\x00'
4778 data += b'\x10\x0d\x00\x01\x00'
4779 data += b'\x10\x08\x00\x02\x00\x00'
4780 data += b'\x10\x44\x00\x01\x00'
4781 data += b'\x10\x21\x00\x00'
4782 data += b'\x10\x23\x00\x00'
4783 data += b'\x10\x24\x00\x00'
4784 data += b'\x10\x42\x00\x00'
4785 data += b'\x10\x54\x00\x08' + 8 * b'\x00'
4786 data += b'\x10\x11\x00\x00'
4787 data += b'\x10\x3c\x00\x01\x00'
4788 data += b'\x10\x02\x00\x02\x00\x00'
4789 data += b'\x10\x12\x00\x02\x00\x00'
4790 data += b'\x10\x09\x00\x02\x00\x00'
4791 data += b'\x10\x2d\x00\x04\x00\x00\x00\x00'
3d105cdf
JM
4792 dev[0].dump_monitor()
4793 with alloc_fail(dev[0], 1, "wps_er_add_sta_data"):
4794 send_wlanevent(url, uuid, data)
4795 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=0.1)
4796 if ev is not None:
4797 raise Exception("Unexpected enrollee add event")
4798 send_wlanevent(url, uuid, data)
4799 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=2)
4800 if ev is None:
4801 raise Exception("Enrollee add event not seen")
4802
5b52e1ad
JM
4803 with alloc_fail(dev[0], 1,
4804 "base64_gen_encode;?base64_encode;wps_er_soap_hdr"):
fe67b945
JM
4805 send_wlanevent(url, uuid, data)
4806
4807 with alloc_fail(dev[0], 1, "wpabuf_alloc;wps_er_soap_hdr"):
4808 send_wlanevent(url, uuid, data)
4809
4810 with alloc_fail(dev[0], 1, "http_client_url_parse;wps_er_sta_send_msg"):
4811 send_wlanevent(url, uuid, data)
4812
4813 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_sta_send_msg"):
4814 send_wlanevent(url, uuid, data)
4815
4c3ae1c0
JM
4816def test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
4817 """WPS ER HTTP protocol testing - no eventSubURL"""
6aaa661a
JM
4818 class WPSAPHTTPServer_no_event_sub_url(WPSAPHTTPServer):
4819 def handle_upnp_info(self):
4820 self.wfile.write(gen_upnp_info(eventSubURL=None))
4821 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_event_sub_url,
4822 no_event_url=True)
4c3ae1c0
JM
4823
4824def test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev):
4825 """WPS ER HTTP protocol testing - DNS name in eventSubURL"""
6aaa661a
JM
4826 class WPSAPHTTPServer_event_sub_url_dns(WPSAPHTTPServer):
4827 def handle_upnp_info(self):
4828 self.wfile.write(gen_upnp_info(eventSubURL='http://example.com/wps_event'))
4829 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_event_sub_url_dns,
4830 no_event_url=True)
4c3ae1c0
JM
4831
4832def test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4833 """WPS ER HTTP protocol testing - subscribe OOM"""
4834 try:
4835 _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev)
4836 finally:
4837 dev[0].request("WPS_ER_STOP")
4838
4839def _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
fab49f61
JM
4840 tests = [(1, "http_client_url_parse"),
4841 (1, "wpabuf_alloc;wps_er_subscribe"),
4842 (1, "http_client_addr"),
4843 (1, "eloop_sock_table_add_sock;?eloop_register_sock;http_client_addr"),
4844 (1, "eloop_register_timeout;http_client_addr")]
4845 for count, func in tests:
4c3ae1c0 4846 with alloc_fail(dev[0], count, func):
fab49f61 4847 server, sock = wps_er_start(dev[0], WPSAPHTTPServer)
4c3ae1c0
JM
4848 server.handle_request()
4849 server.handle_request()
4850 wps_er_stop(dev[0], sock, server, on_alloc_fail=True)
6aaa661a
JM
4851
4852def test_ap_wps_er_http_proto_no_sid(dev, apdev):
4853 """WPS ER HTTP protocol testing - no SID"""
4854 class WPSAPHTTPServer_no_sid(WPSAPHTTPServer):
4855 def handle_wps_event(self):
4856 self.wfile.write(gen_wps_event(sid=None))
4857 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_sid)
4858
4859def test_ap_wps_er_http_proto_invalid_sid_no_uuid(dev, apdev):
4860 """WPS ER HTTP protocol testing - invalid SID - no UUID"""
4861 class WPSAPHTTPServer_invalid_sid_no_uuid(WPSAPHTTPServer):
4862 def handle_wps_event(self):
4863 self.wfile.write(gen_wps_event(sid='FOO'))
4864 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_no_uuid)
4865
4866def test_ap_wps_er_http_proto_invalid_sid_uuid(dev, apdev):
4867 """WPS ER HTTP protocol testing - invalid SID UUID"""
4868 class WPSAPHTTPServer_invalid_sid_uuid(WPSAPHTTPServer):
4869 def handle_wps_event(self):
4870 self.wfile.write(gen_wps_event(sid='uuid:FOO'))
4871 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_uuid)
4872
4873def test_ap_wps_er_http_proto_subscribe_failing(dev, apdev):
4874 """WPS ER HTTP protocol testing - SUBSCRIBE failing"""
4875 class WPSAPHTTPServer_fail_subscribe(WPSAPHTTPServer):
4876 def handle_wps_event(self):
4877 payload = ""
4878 hdr = 'HTTP/1.1 404 Not Found\r\n' + \
4879 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4880 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4881 'Connection: close\r\n' + \
4882 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4883 'Timeout: Second-1801\r\n' + \
4884 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
f94df3c0 4885 self.wfile.write((hdr + payload).encode())
6aaa661a
JM
4886 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_fail_subscribe)
4887
4888def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4889 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4890 class WPSAPHTTPServer_subscribe_invalid_response(WPSAPHTTPServer):
4891 def handle_wps_event(self):
4892 payload = ""
4893 hdr = 'HTTP/1.1 FOO\r\n' + \
4894 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4895 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4896 'Connection: close\r\n' + \
4897 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4898 'Timeout: Second-1801\r\n' + \
4899 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
f94df3c0 4900 self.wfile.write((hdr + payload).encode())
6aaa661a
JM
4901 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_subscribe_invalid_response)
4902
4903def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4904 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4905 class WPSAPHTTPServer_invalid_m1(WPSAPHTTPServer):
4906 def handle_wps_control(self):
4907 payload = '''<?xml version="1.0"?>
4908<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4909<s:Body>
4910<u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4911<NewDeviceInfo>Rk9P</NewDeviceInfo>
4912</u:GetDeviceInfoResponse>
4913</s:Body>
4914</s:Envelope>
4915'''
4916 self.wfile.write(gen_wps_control(payload_override=payload))
4917 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_m1, no_event_url=True)
4918
4919def test_ap_wps_er_http_proto_upnp_info_no_device(dev, apdev):
4920 """WPS ER HTTP protocol testing - No device in UPnP info"""
4921 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4922 def handle_upnp_info(self):
4923 payload = '''<?xml version="1.0"?>
4924<root xmlns="urn:schemas-upnp-org:device-1-0">
4925<specVersion>
4926<major>1</major>
4927<minor>0</minor>
4928</specVersion>
4929</root>
4930'''
4931 hdr = 'HTTP/1.1 200 OK\r\n' + \
4932 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4933 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4934 'Connection: close\r\n' + \
4935 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4936 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
f94df3c0 4937 self.wfile.write((hdr + payload).encode())
6aaa661a
JM
4938 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4939
4940def test_ap_wps_er_http_proto_upnp_info_no_device_type(dev, apdev):
4941 """WPS ER HTTP protocol testing - No deviceType in UPnP info"""
4942 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4943 def handle_upnp_info(self):
4944 payload = '''<?xml version="1.0"?>
4945<root xmlns="urn:schemas-upnp-org:device-1-0">
4946<specVersion>
4947<major>1</major>
4948<minor>0</minor>
4949</specVersion>
4950<device>
4951</device>
4952</root>
4953'''
4954 hdr = 'HTTP/1.1 200 OK\r\n' + \
4955 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4956 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4957 'Connection: close\r\n' + \
4958 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4959 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
f94df3c0 4960 self.wfile.write((hdr + payload).encode())
6aaa661a
JM
4961 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4962
4963def test_ap_wps_er_http_proto_upnp_info_invalid_udn_uuid(dev, apdev):
4964 """WPS ER HTTP protocol testing - Invalid UDN UUID"""
4965 class WPSAPHTTPServer_invalid_udn_uuid(WPSAPHTTPServer):
4966 def handle_upnp_info(self):
4967 self.wfile.write(gen_upnp_info(udn='uuid:foo'))
4968 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_udn_uuid)
4969
4970def test_ap_wps_er_http_proto_no_control_url(dev, apdev):
4971 """WPS ER HTTP protocol testing - no controlURL"""
4972 class WPSAPHTTPServer_no_control_url(WPSAPHTTPServer):
4973 def handle_upnp_info(self):
4974 self.wfile.write(gen_upnp_info(controlURL=None))
4975 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_control_url,
4976 no_event_url=True)
4977
4978def test_ap_wps_er_http_proto_control_url_dns(dev, apdev):
4979 """WPS ER HTTP protocol testing - DNS name in controlURL"""
4980 class WPSAPHTTPServer_control_url_dns(WPSAPHTTPServer):
4981 def handle_upnp_info(self):
4982 self.wfile.write(gen_upnp_info(controlURL='http://example.com/wps_control'))
4983 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_control_url_dns,
4984 no_event_url=True)
24b7f282
JM
4985
4986def test_ap_wps_http_timeout(dev, apdev):
4987 """WPS AP/ER and HTTP timeout"""
4988 try:
4989 _test_ap_wps_http_timeout(dev, apdev)
4990 finally:
4991 dev[0].request("WPS_ER_STOP")
4992
4993def _test_ap_wps_http_timeout(dev, apdev):
4994 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 4995 add_ssdp_ap(apdev[0], ap_uuid)
24b7f282
JM
4996
4997 location = ssdp_get_location(ap_uuid)
9c06eda0 4998 url = urlparse(location)
24b7f282
JM
4999 addr = (url.hostname, url.port)
5000 logger.debug("Open HTTP connection to hostapd, but do not complete request")
5001 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
5002 socket.IPPROTO_TCP)
5003 sock.connect(addr)
cc02ce96 5004 sock.send(b"G")
24b7f282 5005
9c06eda0 5006 class DummyServer(StreamRequestHandler):
24b7f282
JM
5007 def handle(self):
5008 logger.debug("DummyServer - start 31 sec wait")
5009 time.sleep(31)
5010 logger.debug("DummyServer - wait done")
5011
5012 logger.debug("Start WPS ER")
fab49f61
JM
5013 server, sock2 = wps_er_start(dev[0], DummyServer, max_age=40,
5014 wait_m_search=True)
24b7f282
JM
5015
5016 logger.debug("Start server to accept, but not complete, HTTP connection from WPS ER")
5017 # This will wait for 31 seconds..
5018 server.handle_request()
5019
5020 logger.debug("Complete HTTP connection with hostapd (that should have already closed the connection)")
5021 try:
5022 sock.send("ET / HTTP/1.1\r\n\r\n")
5023 res = sock.recv(100)
5024 sock.close()
5025 except:
5026 pass
5027
5028def test_ap_wps_er_url_parse(dev, apdev):
5029 """WPS ER and URL parsing special cases"""
5030 try:
5031 _test_ap_wps_er_url_parse(dev, apdev)
5032 finally:
5033 dev[0].request("WPS_ER_STOP")
5034
5035def _test_ap_wps_er_url_parse(dev, apdev):
5036 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
5037 sock.settimeout(1)
5038 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
5039 sock.bind(("239.255.255.250", 1900))
5040 dev[0].request("WPS_ER_START ifname=lo")
fab49f61 5041 (msg, addr) = sock.recvfrom(1000)
cc02ce96 5042 msg = msg.decode()
24b7f282
JM
5043 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
5044 if "M-SEARCH" not in msg:
5045 raise Exception("Not an M-SEARCH")
cc02ce96 5046 sock.sendto(b"HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1\r\ncache-control:max-age=1\r\n\r\n", addr)
24b7f282 5047 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
cc02ce96 5048 sock.sendto(b"HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1/:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
24b7f282 5049 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
cc02ce96 5050 sock.sendto(b"HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://255.255.255.255:0/foo.xml\r\ncache-control:max-age=1\r\n\r\n", addr)
24b7f282
JM
5051 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
5052
5053 sock.close()
5054
5055def test_ap_wps_er_link_update(dev, apdev):
5056 """WPS ER and link update special cases"""
5057 class WPSAPHTTPServer_link_update(WPSAPHTTPServer):
5058 def handle_upnp_info(self):
5059 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
5060 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update)
5061
5062 class WPSAPHTTPServer_link_update2(WPSAPHTTPServer):
5063 def handle_others(self, data):
5064 if "GET / " in data:
5065 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
5066 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update2,
5067 location_url='http://127.0.0.1:12345')
5068
5069def test_ap_wps_er_http_client(dev, apdev):
5070 """WPS ER and HTTP client special cases"""
5071 with alloc_fail(dev[0], 1, "http_link_update"):
5072 run_wps_er_proto_test(dev[0], WPSAPHTTPServer)
5073
5074 with alloc_fail(dev[0], 1, "wpabuf_alloc;http_client_url"):
5075 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
5076
5077 with alloc_fail(dev[0], 1, "httpread_create;http_client_tx_ready"):
5078 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
5079
5080 class WPSAPHTTPServer_req_as_resp(WPSAPHTTPServer):
5081 def handle_upnp_info(self):
15dfcb69 5082 self.wfile.write(b"GET / HTTP/1.1\r\n\r\n")
24b7f282
JM
5083 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_req_as_resp,
5084 no_event_url=True)
5085
5086def test_ap_wps_init_oom(dev, apdev):
5087 """wps_init OOM cases"""
5088 ssid = "test-wps"
5089 appin = "12345670"
fab49f61
JM
5090 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5091 "ap_pin": appin}
8b8a1864 5092 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5093 pin = dev[0].wps_read_pin()
5094
5095 with alloc_fail(hapd, 1, "wps_init"):
5096 hapd.request("WPS_PIN any " + pin)
5097 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5098 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5099 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5100 if ev is None:
5101 raise Exception("No EAP failure reported")
5102 dev[0].request("WPS_CANCEL")
5103
5104 with alloc_fail(dev[0], 2, "wps_init"):
5105 hapd.request("WPS_PIN any " + pin)
5106 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5107 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5108 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5109 if ev is None:
5110 raise Exception("No EAP failure reported")
5111 dev[0].request("WPS_CANCEL")
5112
5113 with alloc_fail(dev[0], 2, "wps_init"):
5114 hapd.request("WPS_PBC")
5115 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5116 dev[0].request("WPS_PBC %s" % (apdev[0]['bssid']))
5117 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5118 if ev is None:
5119 raise Exception("No EAP failure reported")
5120 dev[0].request("WPS_CANCEL")
5121
5122 dev[0].dump_monitor()
5123 new_ssid = "wps-new-ssid"
5124 new_passphrase = "1234567890"
5125 with alloc_fail(dev[0], 3, "wps_init"):
5126 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
5127 new_passphrase, no_wait=True)
5128 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5129 if ev is None:
5130 raise Exception("No EAP failure reported")
5131
5132 dev[0].flush_scan_cache()
5133
9fd6804d 5134@remote_compatible
24b7f282
JM
5135def test_ap_wps_invalid_assoc_req_elem(dev, apdev):
5136 """WPS and invalid IE in Association Request frame"""
5137 ssid = "test-wps"
fab49f61 5138 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
8b8a1864 5139 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5140 pin = "12345670"
5141 hapd.request("WPS_PIN any " + pin)
5142 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5143 try:
5144 dev[0].request("VENDOR_ELEM_ADD 13 dd050050f20410")
5145 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5146 for i in range(5):
5147 ev = hapd.wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=10)
5148 if ev and "vendor=14122" in ev:
5149 break
5150 if ev is None or "vendor=14122" not in ev:
5151 raise Exception("EAP-WSC not started")
5152 dev[0].request("WPS_CANCEL")
5153 finally:
5154 dev[0].request("VENDOR_ELEM_REMOVE 13 *")
5155
5156def test_ap_wps_pbc_pin_mismatch(dev, apdev):
5157 """WPS PBC/PIN mismatch"""
5158 ssid = "test-wps"
fab49f61 5159 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
8b8a1864 5160 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5161 hapd.request("SET wps_version_number 0x10")
5162 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5163 hapd.request("WPS_PBC")
5164 pin = dev[0].wps_read_pin()
5165 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5166 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5167 if ev is None:
5168 raise Exception("Scan did not complete")
5169 dev[0].request("WPS_CANCEL")
5170
5171 hapd.request("WPS_CANCEL")
5172 dev[0].flush_scan_cache()
5173
9fd6804d 5174@remote_compatible
24b7f282
JM
5175def test_ap_wps_ie_invalid(dev, apdev):
5176 """WPS PIN attempt with AP that has invalid WSC IE"""
5177 ssid = "test-wps"
fab49f61
JM
5178 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5179 "vendor_elements": "dd050050f20410"}
8b8a1864 5180 hapd = hostapd.add_ap(apdev[0], params)
fab49f61 5181 params = {'ssid': "another", "vendor_elements": "dd050050f20410"}
8b8a1864 5182 hostapd.add_ap(apdev[1], params)
24b7f282
JM
5183 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5184 pin = dev[0].wps_read_pin()
5185 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5186 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5187 if ev is None:
5188 raise Exception("Scan did not complete")
5189 dev[0].request("WPS_CANCEL")
5190
9fd6804d 5191@remote_compatible
24b7f282
JM
5192def test_ap_wps_scan_prio_order(dev, apdev):
5193 """WPS scan priority ordering"""
5194 ssid = "test-wps"
fab49f61 5195 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
8b8a1864 5196 hapd = hostapd.add_ap(apdev[0], params)
fab49f61 5197 params = {'ssid': "another", "vendor_elements": "dd050050f20410"}
8b8a1864 5198 hostapd.add_ap(apdev[1], params)
24b7f282
JM
5199 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5200 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
5201 pin = dev[0].wps_read_pin()
5202 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5203 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5204 if ev is None:
5205 raise Exception("Scan did not complete")
5206 dev[0].request("WPS_CANCEL")
5207
5208def test_ap_wps_probe_req_ie_oom(dev, apdev):
5209 """WPS ProbeReq IE OOM"""
5210 ssid = "test-wps"
fab49f61 5211 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
8b8a1864 5212 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5213 pin = dev[0].wps_read_pin()
5214 hapd.request("WPS_PIN any " + pin)
5215 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5216 with alloc_fail(dev[0], 1, "wps_build_probe_req_ie"):
5217 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5218 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5219 if ev is None:
5220 raise Exception("Association not seen")
5221 dev[0].request("WPS_CANCEL")
161c8515 5222 dev[0].wait_disconnected()
24b7f282
JM
5223
5224 with alloc_fail(dev[0], 1, "wps_ie_encapsulate"):
5225 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5226 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5227 if ev is None:
5228 raise Exception("Association not seen")
5229 dev[0].request("WPS_CANCEL")
161c8515
JM
5230 hapd.disable()
5231 dev[0].request("REMOVE_NETWORK all")
5232 dev[0].wait_disconnected()
5233 time.sleep(0.2)
5234 dev[0].flush_scan_cache()
24b7f282
JM
5235
5236def test_ap_wps_assoc_req_ie_oom(dev, apdev):
5237 """WPS AssocReq IE OOM"""
5238 ssid = "test-wps"
fab49f61 5239 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
8b8a1864 5240 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5241 pin = dev[0].wps_read_pin()
5242 hapd.request("WPS_PIN any " + pin)
5243 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5244 with alloc_fail(dev[0], 1, "wps_build_assoc_req_ie"):
5245 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5246 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5247 if ev is None:
5248 raise Exception("Association not seen")
5249 dev[0].request("WPS_CANCEL")
5250
5251def test_ap_wps_assoc_resp_ie_oom(dev, apdev):
5252 """WPS AssocResp IE OOM"""
5253 ssid = "test-wps"
fab49f61 5254 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
8b8a1864 5255 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5256 pin = dev[0].wps_read_pin()
5257 hapd.request("WPS_PIN any " + pin)
5258 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5259 with alloc_fail(hapd, 1, "wps_build_assoc_resp_ie"):
5260 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5261 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5262 if ev is None:
5263 raise Exception("Association not seen")
5264 dev[0].request("WPS_CANCEL")
5265
9fd6804d 5266@remote_compatible
24b7f282
JM
5267def test_ap_wps_bss_info_errors(dev, apdev):
5268 """WPS BSS info errors"""
fab49f61
JM
5269 params = {"ssid": "1",
5270 "vendor_elements": "dd0e0050f20410440001ff101100010a"}
8b8a1864 5271 hostapd.add_ap(apdev[0], params)
fab49f61 5272 params = {'ssid': "2", "vendor_elements": "dd050050f20410"}
8b8a1864 5273 hostapd.add_ap(apdev[1], params)
24b7f282
JM
5274 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5275 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
5276 bss = dev[0].get_bss(apdev[0]['bssid'])
5277 logger.info("BSS: " + str(bss))
5278 if "wps_state" in bss:
5279 raise Exception("Unexpected wps_state in BSS info")
5280 if 'wps_device_name' not in bss:
5281 raise Exception("No wps_device_name in BSS info")
5282 if bss['wps_device_name'] != '_':
5283 raise Exception("Unexpected wps_device_name value")
5284 bss = dev[0].get_bss(apdev[1]['bssid'])
5285 logger.info("BSS: " + str(bss))
5286
5287 with alloc_fail(dev[0], 1, "=wps_attr_text"):
5288 bss = dev[0].get_bss(apdev[0]['bssid'])
5289 logger.info("BSS(OOM): " + str(bss))
5290
5291def wps_run_pbc_fail_ap(apdev, dev, hapd):
5292 hapd.request("WPS_PBC")
5293 dev.scan_for_bss(apdev['bssid'], freq="2412")
5294 dev.request("WPS_PBC " + apdev['bssid'])
5295 ev = dev.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5296 if ev is None:
5297 raise Exception("No EAP failure reported")
5298 dev.request("WPS_CANCEL")
5299 dev.wait_disconnected()
5300 for i in range(5):
5301 try:
5302 dev.flush_scan_cache()
5303 break
bab493b9 5304 except Exception as e:
24b7f282
JM
5305 if str(e).startswith("Failed to trigger scan"):
5306 # Try again
5307 time.sleep(1)
5308 else:
5309 raise
5310
5311def wps_run_pbc_fail(apdev, dev):
5312 hapd = wps_start_ap(apdev)
5313 wps_run_pbc_fail_ap(apdev, dev, hapd)
5314
9fd6804d 5315@remote_compatible
24b7f282
JM
5316def test_ap_wps_pk_oom(dev, apdev):
5317 """WPS and public key OOM"""
5318 with alloc_fail(dev[0], 1, "wps_build_public_key"):
5319 wps_run_pbc_fail(apdev[0], dev[0])
5320
9fd6804d 5321@remote_compatible
24b7f282
JM
5322def test_ap_wps_pk_oom_ap(dev, apdev):
5323 """WPS and public key OOM on AP"""
5324 hapd = wps_start_ap(apdev[0])
5325 with alloc_fail(hapd, 1, "wps_build_public_key"):
5326 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5327
9fd6804d 5328@remote_compatible
24b7f282
JM
5329def test_ap_wps_encr_oom_ap(dev, apdev):
5330 """WPS and encrypted settings decryption OOM on AP"""
5331 hapd = wps_start_ap(apdev[0])
5332 pin = dev[0].wps_read_pin()
5333 hapd.request("WPS_PIN any " + pin)
5334 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5335 with alloc_fail(hapd, 1, "wps_decrypt_encr_settings"):
5336 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
5337 ev = hapd.wait_event(["WPS-FAIL"], timeout=10)
5338 if ev is None:
5339 raise Exception("No WPS-FAIL reported")
5340 dev[0].request("WPS_CANCEL")
5341 dev[0].wait_disconnected()
5342
9fd6804d 5343@remote_compatible
24b7f282
JM
5344def test_ap_wps_encr_no_random_ap(dev, apdev):
5345 """WPS and no random data available for encryption on AP"""
5346 hapd = wps_start_ap(apdev[0])
5347 with fail_test(hapd, 1, "os_get_random;wps_build_encr_settings"):
5348 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5349
9fd6804d 5350@remote_compatible
24b7f282
JM
5351def test_ap_wps_e_hash_no_random_sta(dev, apdev):
5352 """WPS and no random data available for e-hash on STA"""
5353 with fail_test(dev[0], 1, "os_get_random;wps_build_e_hash"):
5354 wps_run_pbc_fail(apdev[0], dev[0])
5355
9fd6804d 5356@remote_compatible
24b7f282
JM
5357def test_ap_wps_m1_no_random(dev, apdev):
5358 """WPS and no random for M1 on STA"""
5359 with fail_test(dev[0], 1, "os_get_random;wps_build_m1"):
5360 wps_run_pbc_fail(apdev[0], dev[0])
5361
9fd6804d 5362@remote_compatible
24b7f282
JM
5363def test_ap_wps_m1_oom(dev, apdev):
5364 """WPS and OOM for M1 on STA"""
5365 with alloc_fail(dev[0], 1, "wps_build_m1"):
5366 wps_run_pbc_fail(apdev[0], dev[0])
5367
9fd6804d 5368@remote_compatible
24b7f282
JM
5369def test_ap_wps_m3_oom(dev, apdev):
5370 """WPS and OOM for M3 on STA"""
5371 with alloc_fail(dev[0], 1, "wps_build_m3"):
5372 wps_run_pbc_fail(apdev[0], dev[0])
5373
9fd6804d 5374@remote_compatible
24b7f282
JM
5375def test_ap_wps_m5_oom(dev, apdev):
5376 """WPS and OOM for M5 on STA"""
5377 hapd = wps_start_ap(apdev[0])
5378 hapd.request("WPS_PBC")
5379 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5380 for i in range(1, 3):
5381 with alloc_fail(dev[0], i, "wps_build_m5"):
5382 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5383 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5384 if ev is None:
5385 raise Exception("No EAP failure reported")
5386 dev[0].request("WPS_CANCEL")
5387 dev[0].wait_disconnected()
5388 dev[0].flush_scan_cache()
5389
9fd6804d 5390@remote_compatible
24b7f282
JM
5391def test_ap_wps_m5_no_random(dev, apdev):
5392 """WPS and no random for M5 on STA"""
5393 with fail_test(dev[0], 1,
5394 "os_get_random;wps_build_encr_settings;wps_build_m5"):
5395 wps_run_pbc_fail(apdev[0], dev[0])
5396
9fd6804d 5397@remote_compatible
24b7f282
JM
5398def test_ap_wps_m7_oom(dev, apdev):
5399 """WPS and OOM for M7 on STA"""
5400 hapd = wps_start_ap(apdev[0])
5401 hapd.request("WPS_PBC")
5402 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5403 for i in range(1, 3):
5404 with alloc_fail(dev[0], i, "wps_build_m7"):
5405 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5406 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5407 if ev is None:
5408 raise Exception("No EAP failure reported")
5409 dev[0].request("WPS_CANCEL")
5410 dev[0].wait_disconnected()
5411 dev[0].flush_scan_cache()
5412
9fd6804d 5413@remote_compatible
24b7f282
JM
5414def test_ap_wps_m7_no_random(dev, apdev):
5415 """WPS and no random for M7 on STA"""
5416 with fail_test(dev[0], 1,
5417 "os_get_random;wps_build_encr_settings;wps_build_m7"):
5418 wps_run_pbc_fail(apdev[0], dev[0])
5419
9fd6804d 5420@remote_compatible
24b7f282
JM
5421def test_ap_wps_wsc_done_oom(dev, apdev):
5422 """WPS and OOM for WSC_Done on STA"""
5423 with alloc_fail(dev[0], 1, "wps_build_wsc_done"):
5424 wps_run_pbc_fail(apdev[0], dev[0])
5425
5426def test_ap_wps_random_psk_fail(dev, apdev):
5427 """WPS and no random for PSK on AP"""
5428 ssid = "test-wps"
5429 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
5430 appin = "12345670"
5431 try:
5432 os.remove(pskfile)
5433 except:
5434 pass
5435
5436 try:
5437 with open(pskfile, "w") as f:
5438 f.write("# WPA PSKs\n")
5439
fab49f61
JM
5440 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5441 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
5442 "rsn_pairwise": "CCMP", "ap_pin": appin,
5443 "wpa_psk_file": pskfile}
8b8a1864 5444 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5445
5446 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5447 with fail_test(hapd, 1, "os_get_random;wps_build_cred_network_key"):
5448 dev[0].request("WPS_REG " + apdev[0]['bssid'] + " " + appin)
5449 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5450 if ev is None:
5451 raise Exception("No EAP failure reported")
5452 dev[0].request("WPS_CANCEL")
5453 dev[0].wait_disconnected()
5454
5455 with fail_test(hapd, 1, "os_get_random;wps_build_cred"):
5456 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5457
5458 with alloc_fail(hapd, 1, "wps_build_cred"):
5459 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5460
5461 with alloc_fail(hapd, 2, "wps_build_cred"):
5462 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5463 finally:
5464 os.remove(pskfile)
5465
5466def wps_ext_eap_identity_req(dev, hapd, bssid):
5467 logger.debug("EAP-Identity/Request")
5468 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5469 if ev is None:
5470 raise Exception("Timeout on EAPOL-TX from hostapd")
5471 res = dev.request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
5472 if "OK" not in res:
5473 raise Exception("EAPOL_RX to wpa_supplicant failed")
5474
5475def wps_ext_eap_identity_resp(hapd, dev, addr):
5476 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
5477 if ev is None:
5478 raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
5479 res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
5480 if "OK" not in res:
5481 raise Exception("EAPOL_RX to hostapd failed")
5482
5483def wps_ext_eap_wsc(dst, src, src_addr, msg):
5484 logger.debug(msg)
5485 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5486 if ev is None:
5487 raise Exception("Timeout on EAPOL-TX")
5488 res = dst.request("EAPOL_RX " + src_addr + " " + ev.split(' ')[2])
5489 if "OK" not in res:
5490 raise Exception("EAPOL_RX failed")
5491
7511ead0 5492def wps_start_ext(apdev, dev, pbc=False, pin=None):
24b7f282
JM
5493 addr = dev.own_addr()
5494 bssid = apdev['bssid']
5495 ssid = "test-wps-conf"
fab49f61
JM
5496 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5497 "wpa_passphrase": "12345678", "wpa": "2",
5498 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
afc26df2 5499 hapd = hostapd.add_ap(apdev, params)
24b7f282 5500
d1883671
JM
5501 if pbc:
5502 hapd.request("WPS_PBC")
5503 else:
7511ead0
JM
5504 if pin is None:
5505 pin = dev.wps_read_pin()
d1883671 5506 hapd.request("WPS_PIN any " + pin)
24b7f282
JM
5507 dev.scan_for_bss(bssid, freq="2412")
5508 hapd.request("SET ext_eapol_frame_io 1")
5509 dev.request("SET ext_eapol_frame_io 1")
5510
d1883671
JM
5511 if pbc:
5512 dev.request("WPS_PBC " + bssid)
5513 else:
5514 dev.request("WPS_PIN " + bssid + " " + pin)
fab49f61 5515 return addr, bssid, hapd
24b7f282
JM
5516
5517def wps_auth_corrupt(dst, src, addr):
5518 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5519 if ev is None:
5520 raise Exception("Timeout on EAPOL-TX")
5521 src.request("SET ext_eapol_frame_io 0")
5522 dst.request("SET ext_eapol_frame_io 0")
5523 msg = ev.split(' ')[2]
5524 if msg[-24:-16] != '10050008':
5525 raise Exception("Could not find Authenticator attribute")
5526 # Corrupt Authenticator value
5527 msg = msg[:-1] + '%x' % ((int(msg[-1], 16) + 1) % 16)
5528 res = dst.request("EAPOL_RX " + addr + " " + msg)
5529 if "OK" not in res:
5530 raise Exception("EAPOL_RX failed")
5531
5532def wps_fail_finish(hapd, dev, fail_str):
5533 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5534 if ev is None:
5535 raise Exception("WPS-FAIL not indicated")
5536 if fail_str not in ev:
5537 raise Exception("Unexpected WPS-FAIL value: " + ev)
5538 dev.request("WPS_CANCEL")
5539 dev.wait_disconnected()
5540
5541def wps_auth_corrupt_from_ap(dev, hapd, bssid, fail_str):
5542 wps_auth_corrupt(dev, hapd, bssid)
5543 wps_fail_finish(hapd, dev, fail_str)
5544
5545def wps_auth_corrupt_to_ap(dev, hapd, addr, fail_str):
5546 wps_auth_corrupt(hapd, dev, addr)
5547 wps_fail_finish(hapd, dev, fail_str)
5548
5549def test_ap_wps_authenticator_mismatch_m2(dev, apdev):
5550 """WPS and Authenticator attribute mismatch in M2"""
fab49f61 5551 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
24b7f282
JM
5552 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5553 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5554 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5555 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5556 logger.debug("M2")
5557 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=5")
5558
5559def test_ap_wps_authenticator_mismatch_m3(dev, apdev):
5560 """WPS and Authenticator attribute mismatch in M3"""
fab49f61 5561 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
24b7f282
JM
5562 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5563 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5564 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5565 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5566 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5567 logger.debug("M3")
5568 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=7")
5569
5570def test_ap_wps_authenticator_mismatch_m4(dev, apdev):
5571 """WPS and Authenticator attribute mismatch in M4"""
fab49f61 5572 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
24b7f282
JM
5573 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5574 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5575 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5576 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5577 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5578 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5579 logger.debug("M4")
5580 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=8")
5581
5582def test_ap_wps_authenticator_mismatch_m5(dev, apdev):
5583 """WPS and Authenticator attribute mismatch in M5"""
fab49f61 5584 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
24b7f282
JM
5585 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5586 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5587 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5588 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5589 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5590 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5591 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5592 logger.debug("M5")
5593 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=9")
5594
5595def test_ap_wps_authenticator_mismatch_m6(dev, apdev):
5596 """WPS and Authenticator attribute mismatch in M6"""
fab49f61 5597 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
24b7f282
JM
5598 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5599 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5600 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5601 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5602 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5603 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5604 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5605 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5606 logger.debug("M6")
5607 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=10")
5608
5609def test_ap_wps_authenticator_mismatch_m7(dev, apdev):
5610 """WPS and Authenticator attribute mismatch in M7"""
fab49f61 5611 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
24b7f282
JM
5612 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5613 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5614 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5615 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5616 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5617 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5618 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5619 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5620 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5621 logger.debug("M7")
5622 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=11")
5623
5624def test_ap_wps_authenticator_mismatch_m8(dev, apdev):
5625 """WPS and Authenticator attribute mismatch in M8"""
fab49f61 5626 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
24b7f282
JM
5627 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5628 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5629 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5630 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5631 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5632 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5633 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5634 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5635 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5636 wps_ext_eap_wsc(hapd, dev[0], addr, "M7")
5637 logger.debug("M8")
5638 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=12")
5639
5640def test_ap_wps_authenticator_missing_m2(dev, apdev):
5641 """WPS and Authenticator attribute missing from M2"""
fab49f61 5642 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
24b7f282
JM
5643 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5644 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5645 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5646 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5647 logger.debug("M2")
5648 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5649 if ev is None:
5650 raise Exception("Timeout on EAPOL-TX")
5651 hapd.request("SET ext_eapol_frame_io 0")
5652 dev[0].request("SET ext_eapol_frame_io 0")
5653 msg = ev.split(' ')[2]
5654 if msg[-24:-16] != '10050008':
5655 raise Exception("Could not find Authenticator attribute")
5656 # Remove Authenticator value
5657 msg = msg[:-24]
5658 mlen = "%04x" % (int(msg[4:8], 16) - 12)
5659 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:]
5660 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5661 if "OK" not in res:
5662 raise Exception("EAPOL_RX failed")
5663 wps_fail_finish(hapd, dev[0], "msg=5")
5664
d1883671
JM
5665def test_ap_wps_m2_dev_passwd_id_p2p(dev, apdev):
5666 """WPS and M2 with different Device Password ID (P2P)"""
fab49f61 5667 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
d1883671
JM
5668 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5669 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5670 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5671 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5672 logger.debug("M2")
5673 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5674 if ev is None:
5675 raise Exception("Timeout on EAPOL-TX")
5676 hapd.request("SET ext_eapol_frame_io 0")
5677 dev[0].request("SET ext_eapol_frame_io 0")
5678 msg = ev.split(' ')[2]
5679 if msg[722:730] != '10120002':
5680 raise Exception("Could not find Device Password ID attribute")
5681 # Replace Device Password ID value. This will fail Authenticator check, but
5682 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5683 # log.
5684 msg = msg[0:730] + "0005" + msg[734:]
5685 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5686 if "OK" not in res:
5687 raise Exception("EAPOL_RX failed")
5688 wps_fail_finish(hapd, dev[0], "msg=5")
5689
5690def test_ap_wps_m2_dev_passwd_id_change_pin_to_pbc(dev, apdev):
5691 """WPS and M2 with different Device Password ID (PIN to PBC)"""
fab49f61 5692 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
d1883671
JM
5693 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5694 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5695 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5696 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5697 logger.debug("M2")
5698 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5699 if ev is None:
5700 raise Exception("Timeout on EAPOL-TX")
5701 hapd.request("SET ext_eapol_frame_io 0")
5702 dev[0].request("SET ext_eapol_frame_io 0")
5703 msg = ev.split(' ')[2]
5704 if msg[722:730] != '10120002':
5705 raise Exception("Could not find Device Password ID attribute")
5706 # Replace Device Password ID value (PIN --> PBC). This will be rejected.
5707 msg = msg[0:730] + "0004" + msg[734:]
5708 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5709 if "OK" not in res:
5710 raise Exception("EAPOL_RX failed")
5711 wps_fail_finish(hapd, dev[0], "msg=5")
5712
5713def test_ap_wps_m2_dev_passwd_id_change_pbc_to_pin(dev, apdev):
5714 """WPS and M2 with different Device Password ID (PBC to PIN)"""
fab49f61 5715 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5716 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5717 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5718 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5719 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5720 logger.debug("M2")
5721 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5722 if ev is None:
5723 raise Exception("Timeout on EAPOL-TX")
5724 hapd.request("SET ext_eapol_frame_io 0")
5725 dev[0].request("SET ext_eapol_frame_io 0")
5726 msg = ev.split(' ')[2]
5727 if msg[722:730] != '10120002':
5728 raise Exception("Could not find Device Password ID attribute")
5729 # Replace Device Password ID value. This will fail Authenticator check, but
5730 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5731 # log.
5732 msg = msg[0:730] + "0000" + msg[734:]
5733 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5734 if "OK" not in res:
5735 raise Exception("EAPOL_RX failed")
5736 wps_fail_finish(hapd, dev[0], "msg=5")
5737 dev[0].flush_scan_cache()
5738
5739def test_ap_wps_m2_missing_dev_passwd_id(dev, apdev):
5740 """WPS and M2 without Device Password ID"""
fab49f61 5741 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
d1883671
JM
5742 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5743 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5744 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5745 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5746 logger.debug("M2")
5747 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5748 if ev is None:
5749 raise Exception("Timeout on EAPOL-TX")
5750 hapd.request("SET ext_eapol_frame_io 0")
5751 dev[0].request("SET ext_eapol_frame_io 0")
5752 msg = ev.split(' ')[2]
5753 if msg[722:730] != '10120002':
5754 raise Exception("Could not find Device Password ID attribute")
5755 # Remove Device Password ID value. This will fail Authenticator check, but
5756 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5757 # log.
5758 mlen = "%04x" % (int(msg[4:8], 16) - 6)
5759 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:722] + msg[734:]
5760 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5761 if "OK" not in res:
5762 raise Exception("EAPOL_RX failed")
5763 wps_fail_finish(hapd, dev[0], "msg=5")
5764
5765def test_ap_wps_m2_missing_registrar_nonce(dev, apdev):
5766 """WPS and M2 without Registrar Nonce"""
fab49f61 5767 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5768 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5769 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5770 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5771 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5772 logger.debug("M2")
5773 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5774 if ev is None:
5775 raise Exception("Timeout on EAPOL-TX")
5776 hapd.request("SET ext_eapol_frame_io 0")
5777 dev[0].request("SET ext_eapol_frame_io 0")
5778 msg = ev.split(' ')[2]
5779 if msg[96:104] != '10390010':
5780 raise Exception("Could not find Registrar Nonce attribute")
5781 # Remove Registrar Nonce. This will fail Authenticator check, but
5782 # allows the code path in wps_process_registrar_nonce() to be checked from
5783 # the debug log.
5784 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5785 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:96] + msg[136:]
5786 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5787 if "OK" not in res:
5788 raise Exception("EAPOL_RX failed")
5789 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5790 if ev is None:
5791 raise Exception("Disconnect event not seen")
5792 dev[0].request("WPS_CANCEL")
5793 dev[0].flush_scan_cache()
5794
5795def test_ap_wps_m2_missing_enrollee_nonce(dev, apdev):
5796 """WPS and M2 without Enrollee Nonce"""
fab49f61 5797 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5798 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5799 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5800 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5801 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5802 logger.debug("M2")
5803 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5804 if ev is None:
5805 raise Exception("Timeout on EAPOL-TX")
5806 hapd.request("SET ext_eapol_frame_io 0")
5807 dev[0].request("SET ext_eapol_frame_io 0")
5808 msg = ev.split(' ')[2]
5809 if msg[56:64] != '101a0010':
5810 raise Exception("Could not find enrollee Nonce attribute")
5811 # Remove Enrollee Nonce. This will fail Authenticator check, but
5812 # allows the code path in wps_process_enrollee_nonce() to be checked from
5813 # the debug log.
5814 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5815 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:56] + msg[96:]
5816 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5817 if "OK" not in res:
5818 raise Exception("EAPOL_RX failed")
5819 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5820 if ev is None:
5821 raise Exception("Disconnect event not seen")
5822 dev[0].request("WPS_CANCEL")
5823 dev[0].flush_scan_cache()
5824
5825def test_ap_wps_m2_missing_uuid_r(dev, apdev):
5826 """WPS and M2 without UUID-R"""
fab49f61 5827 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5828 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5829 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5830 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5831 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5832 logger.debug("M2")
5833 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5834 if ev is None:
5835 raise Exception("Timeout on EAPOL-TX")
5836 hapd.request("SET ext_eapol_frame_io 0")
5837 dev[0].request("SET ext_eapol_frame_io 0")
5838 msg = ev.split(' ')[2]
5839 if msg[136:144] != '10480010':
5840 raise Exception("Could not find enrollee Nonce attribute")
5841 # Remove UUID-R. This will fail Authenticator check, but allows the code
5842 # path in wps_process_uuid_r() to be checked from the debug log.
5843 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5844 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:136] + msg[176:]
5845 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5846 if "OK" not in res:
5847 raise Exception("EAPOL_RX failed")
5848 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5849 if ev is None:
5850 raise Exception("Disconnect event not seen")
5851 dev[0].request("WPS_CANCEL")
5852 dev[0].flush_scan_cache()
5853
5854def test_ap_wps_m2_invalid(dev, apdev):
5855 """WPS and M2 parsing failure"""
fab49f61 5856 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5857 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5858 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5859 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5860 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5861 logger.debug("M2")
5862 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5863 if ev is None:
5864 raise Exception("Timeout on EAPOL-TX")
5865 hapd.request("SET ext_eapol_frame_io 0")
5866 dev[0].request("SET ext_eapol_frame_io 0")
5867 msg = ev.split(' ')[2]
5868 if msg[136:144] != '10480010':
5869 raise Exception("Could not find enrollee Nonce attribute")
5870 # Remove UUID-R. This will fail Authenticator check, but allows the code
5871 # path in wps_process_uuid_r() to be checked from the debug log.
5872 mlen = "%04x" % (int(msg[4:8], 16) - 1)
5873 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:-2]
5874 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5875 if "OK" not in res:
5876 raise Exception("EAPOL_RX failed")
5877 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5878 if ev is None:
5879 raise Exception("Disconnect event not seen")
5880 dev[0].request("WPS_CANCEL")
5881 dev[0].flush_scan_cache()
5882
5883def test_ap_wps_m2_missing_msg_type(dev, apdev):
5884 """WPS and M2 without Message Type"""
fab49f61 5885 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5886 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5887 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5888 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5889 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5890 logger.debug("M2")
5891 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5892 if ev is None:
5893 raise Exception("Timeout on EAPOL-TX")
5894 hapd.request("SET ext_eapol_frame_io 0")
5895 dev[0].request("SET ext_eapol_frame_io 0")
5896 msg = ev.split(' ')[2]
5897 if msg[46:54] != '10220001':
5898 raise Exception("Could not find Message Type attribute")
5899 # Remove Message Type. This will fail Authenticator check, but allows the
5900 # code path in wps_process_wsc_msg() to be checked from the debug log.
5901 mlen = "%04x" % (int(msg[4:8], 16) - 5)
5902 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:46] + msg[56:]
5903 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5904 if "OK" not in res:
5905 raise Exception("EAPOL_RX failed")
5906 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5907 if ev is None:
5908 raise Exception("Disconnect event not seen")
5909 dev[0].request("WPS_CANCEL")
5910 dev[0].flush_scan_cache()
5911
5912def test_ap_wps_m2_unknown_msg_type(dev, apdev):
5913 """WPS and M2 but unknown Message Type"""
fab49f61 5914 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5915 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5916 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5917 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5918 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5919 logger.debug("M2")
5920 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5921 if ev is None:
5922 raise Exception("Timeout on EAPOL-TX")
5923 hapd.request("SET ext_eapol_frame_io 0")
5924 dev[0].request("SET ext_eapol_frame_io 0")
5925 msg = ev.split(' ')[2]
5926 if msg[46:54] != '10220001':
5927 raise Exception("Could not find Message Type attribute")
5928 # Replace Message Type value. This will be rejected.
5929 msg = msg[0:54] + "00" + msg[56:]
5930 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5931 if "OK" not in res:
5932 raise Exception("EAPOL_RX failed")
5933 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5934 if ev is None:
5935 raise Exception("Disconnect event not seen")
5936 dev[0].request("WPS_CANCEL")
5937 dev[0].flush_scan_cache()
5938
5939def test_ap_wps_m2_unknown_opcode(dev, apdev):
5940 """WPS and M2 but unknown opcode"""
fab49f61 5941 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5942 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5943 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5944 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5945 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5946 logger.debug("M2")
5947 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5948 if ev is None:
5949 raise Exception("Timeout on EAPOL-TX")
5950 hapd.request("SET ext_eapol_frame_io 0")
5951 dev[0].request("SET ext_eapol_frame_io 0")
5952 msg = ev.split(' ')[2]
5953 # Replace opcode. This will be discarded in EAP-WSC processing.
5954 msg = msg[0:32] + "00" + msg[34:]
5955 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5956 if "OK" not in res:
5957 raise Exception("EAPOL_RX failed")
5958 dev[0].request("WPS_CANCEL")
5959 dev[0].wait_disconnected()
5960 dev[0].flush_scan_cache()
5961
5962def test_ap_wps_m2_unknown_opcode2(dev, apdev):
5963 """WPS and M2 but unknown opcode (WSC_Start)"""
fab49f61 5964 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5965 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5966 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5967 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5968 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5969 logger.debug("M2")
5970 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5971 if ev is None:
5972 raise Exception("Timeout on EAPOL-TX")
5973 hapd.request("SET ext_eapol_frame_io 0")
5974 dev[0].request("SET ext_eapol_frame_io 0")
5975 msg = ev.split(' ')[2]
5976 # Replace opcode. This will be discarded in EAP-WSC processing.
5977 msg = msg[0:32] + "01" + msg[34:]
5978 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5979 if "OK" not in res:
5980 raise Exception("EAPOL_RX failed")
5981 dev[0].request("WPS_CANCEL")
5982 dev[0].wait_disconnected()
5983 dev[0].flush_scan_cache()
5984
5985def test_ap_wps_m2_unknown_opcode3(dev, apdev):
5986 """WPS and M2 but unknown opcode (WSC_Done)"""
fab49f61 5987 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5988 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5989 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5990 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5991 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5992 logger.debug("M2")
5993 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5994 if ev is None:
5995 raise Exception("Timeout on EAPOL-TX")
5996 hapd.request("SET ext_eapol_frame_io 0")
5997 dev[0].request("SET ext_eapol_frame_io 0")
5998 msg = ev.split(' ')[2]
5999 # Replace opcode. This will be discarded in WPS Enrollee processing.
6000 msg = msg[0:32] + "05" + msg[34:]
6001 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
6002 if "OK" not in res:
6003 raise Exception("EAPOL_RX failed")
6004 dev[0].request("WPS_CANCEL")
6005 dev[0].wait_disconnected()
6006 dev[0].flush_scan_cache()
6007
6008def wps_m2_but_other(dev, apdev, title, msgtype):
fab49f61 6009 addr, bssid, hapd = wps_start_ext(apdev, dev)
d1883671
JM
6010 wps_ext_eap_identity_req(dev, hapd, bssid)
6011 wps_ext_eap_identity_resp(hapd, dev, addr)
6012 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
6013 wps_ext_eap_wsc(hapd, dev, addr, "M1")
6014 logger.debug(title)
6015 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
6016 if ev is None:
6017 raise Exception("Timeout on EAPOL-TX")
6018 hapd.request("SET ext_eapol_frame_io 0")
6019 dev.request("SET ext_eapol_frame_io 0")
6020 msg = ev.split(' ')[2]
6021 if msg[46:54] != '10220001':
6022 raise Exception("Could not find Message Type attribute")
6023 # Replace Message Type value. This will be rejected.
6024 msg = msg[0:54] + msgtype + msg[56:]
6025 res = dev.request("EAPOL_RX " + bssid + " " + msg)
6026 if "OK" not in res:
6027 raise Exception("EAPOL_RX failed")
6028 ev = dev.wait_event(["WPS-FAIL"], timeout=5)
6029 if ev is None:
6030 raise Exception("WPS-FAIL event not seen")
6031 dev.request("WPS_CANCEL")
6032 dev.wait_disconnected()
6033
6034def wps_m4_but_other(dev, apdev, title, msgtype):
fab49f61 6035 addr, bssid, hapd = wps_start_ext(apdev, dev)
d1883671
JM
6036 wps_ext_eap_identity_req(dev, hapd, bssid)
6037 wps_ext_eap_identity_resp(hapd, dev, addr)
6038 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
6039 wps_ext_eap_wsc(hapd, dev, addr, "M1")
6040 wps_ext_eap_wsc(dev, hapd, bssid, "M2")
6041 wps_ext_eap_wsc(hapd, dev, addr, "M3")
6042 logger.debug(title)
6043 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
6044 if ev is None:
6045 raise Exception("Timeout on EAPOL-TX")
6046 hapd.request("SET ext_eapol_frame_io 0")
6047 dev.request("SET ext_eapol_frame_io 0")
6048 msg = ev.split(' ')[2]
6049 if msg[46:54] != '10220001':
6050 raise Exception("Could not find Message Type attribute")
6051 # Replace Message Type value. This will be rejected.
6052 msg = msg[0:54] + msgtype + msg[56:]
6053 res = dev.request("EAPOL_RX " + bssid + " " + msg)
6054 if "OK" not in res:
6055 raise Exception("EAPOL_RX failed")
6056 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
6057 if ev is None:
6058 raise Exception("WPS-FAIL event not seen")
6059 dev.request("WPS_CANCEL")
6060 dev.wait_disconnected()
6061
6062def test_ap_wps_m2_msg_type_m4(dev, apdev):
6063 """WPS and M2 but Message Type M4"""
6064 wps_m2_but_other(dev[0], apdev[0], "M2/M4", "08")
6065
6066def test_ap_wps_m2_msg_type_m6(dev, apdev):
6067 """WPS and M2 but Message Type M6"""
6068 wps_m2_but_other(dev[0], apdev[0], "M2/M6", "0a")
6069
6070def test_ap_wps_m2_msg_type_m8(dev, apdev):
6071 """WPS and M2 but Message Type M8"""
6072 wps_m2_but_other(dev[0], apdev[0], "M2/M8", "0c")
6073
6074def test_ap_wps_m4_msg_type_m2(dev, apdev):
6075 """WPS and M4 but Message Type M2"""
6076 wps_m4_but_other(dev[0], apdev[0], "M4/M2", "05")
6077
6078def test_ap_wps_m4_msg_type_m2d(dev, apdev):
6079 """WPS and M4 but Message Type M2D"""
6080 wps_m4_but_other(dev[0], apdev[0], "M4/M2D", "06")
6081
9fd6804d 6082@remote_compatible
24b7f282
JM
6083def test_ap_wps_config_methods(dev, apdev):
6084 """WPS configuration method parsing"""
6085 ssid = "test-wps-conf"
fab49f61
JM
6086 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
6087 "wpa_passphrase": "12345678", "wpa": "2",
6088 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
6089 "config_methods": "ethernet display ext_nfc_token int_nfc_token physical_display physical_push_button"}
8b8a1864 6090 hapd = hostapd.add_ap(apdev[0], params)
fab49f61
JM
6091 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
6092 "wpa_passphrase": "12345678", "wpa": "2",
6093 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
6094 "config_methods": "display push_button"}
8b8a1864 6095 hapd2 = hostapd.add_ap(apdev[1], params)
476daa05
JM
6096
6097def test_ap_wps_set_selected_registrar_proto(dev, apdev):
6098 """WPS UPnP SetSelectedRegistrar protocol testing"""
6099 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 6100 hapd = add_ssdp_ap(apdev[0], ap_uuid)
476daa05
JM
6101
6102 location = ssdp_get_location(ap_uuid)
6103 urls = upnp_get_urls(location)
9c06eda0
MH
6104 eventurl = urlparse(urls['event_sub_url'])
6105 ctrlurl = urlparse(urls['control_url'])
6106 url = urlparse(location)
6107 conn = HTTPConnection(url.netloc)
476daa05 6108
9c06eda0 6109 class WPSERHTTPServer(StreamRequestHandler):
476daa05
JM
6110 def handle(self):
6111 data = self.rfile.readline().strip()
6112 logger.debug(data)
6113 self.wfile.write(gen_wps_event())
6114
6115 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
6116 server.timeout = 1
6117
fab49f61
JM
6118 headers = {"callback": '<http://127.0.0.1:12345/event>',
6119 "NT": "upnp:event",
6120 "timeout": "Second-1234"}
476daa05
JM
6121 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
6122 resp = conn.getresponse()
6123 if resp.status != 200:
6124 raise Exception("Unexpected HTTP response: %d" % resp.status)
6125 sid = resp.getheader("sid")
6126 logger.debug("Subscription SID " + sid)
6127 server.handle_request()
6128
fab49f61
JM
6129 tests = [(500, "10"),
6130 (200, "104a000110" + "1041000101" + "101200020000" +
6131 "105300023148" +
6132 "1049002c00372a0001200124111111111111222222222222333333333333444444444444555555555555666666666666" +
6133 "10480010362db47ba53a519188fb5458b986b2e4"),
6134 (200, "104a000110" + "1041000100" + "101200020000" +
6135 "105300020000"),
6136 (200, "104a000110" + "1041000100"),
6137 (200, "104a000110")]
6138 for status, test in tests:
476daa05 6139 tlvs = binascii.unhexlify(test)
c4e333fa 6140 newmsg = base64.b64encode(tlvs).decode()
476daa05
JM
6141 msg = '<?xml version="1.0"?>\n'
6142 msg += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
6143 msg += '<s:Body>'
6144 msg += '<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">'
6145 msg += '<NewMessage>'
6146 msg += newmsg
6147 msg += "</NewMessage></u:SetSelectedRegistrar></s:Body></s:Envelope>"
fab49f61 6148 headers = {"Content-type": 'text/xml; charset="utf-8"'}
476daa05
JM
6149 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
6150 conn.request("POST", ctrlurl.path, msg, headers)
6151 resp = conn.getresponse()
6152 if resp.status != status:
6153 raise Exception("Unexpected HTTP response: %d (expected %d)" % (resp.status, status))
96038a5f
JM
6154
6155def test_ap_wps_adv_oom(dev, apdev):
6156 """WPS AP and advertisement OOM"""
6157 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 6158 hapd = add_ssdp_ap(apdev[0], ap_uuid)
96038a5f
JM
6159
6160 with alloc_fail(hapd, 1, "=msearchreply_state_machine_start"):
6161 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
6162 no_recv=True)
6163 time.sleep(0.2)
6164
6165 with alloc_fail(hapd, 1, "eloop_register_timeout;msearchreply_state_machine_start"):
6166 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
6167 no_recv=True)
6168 time.sleep(0.2)
6169
6170 with alloc_fail(hapd, 1,
6171 "next_advertisement;advertisement_state_machine_stop"):
6172 hapd.disable()
6173
6174 with alloc_fail(hapd, 1, "ssdp_listener_start"):
6175 if "FAIL" not in hapd.request("ENABLE"):
6176 raise Exception("ENABLE succeeded during OOM")
926404a6
JM
6177
6178def test_wps_config_methods(dev):
6179 """WPS config method update"""
6180 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
6181 wpas.interface_add("wlan5")
6182 if "OK" not in wpas.request("SET config_methods display label"):
6183 raise Exception("Failed to set config_methods")
6184 if wpas.request("GET config_methods").strip() != "display label":
6185 raise Exception("config_methods were not updated")
6186 if "OK" not in wpas.request("SET config_methods "):
6187 raise Exception("Failed to clear config_methods")
6188 if wpas.request("GET config_methods").strip() != "":
6189 raise Exception("config_methods were not cleared")
7511ead0
JM
6190
6191WPS_VENDOR_ID_WFA = 14122
6192WPS_VENDOR_TYPE = 1
6193
6194# EAP-WSC Op-Code values
6195WSC_Start = 0x01
6196WSC_ACK = 0x02
6197WSC_NACK = 0x03
6198WSC_MSG = 0x04
6199WSC_Done = 0x05
6200WSC_FRAG_ACK = 0x06
6201
6202ATTR_AP_CHANNEL = 0x1001
6203ATTR_ASSOC_STATE = 0x1002
6204ATTR_AUTH_TYPE = 0x1003
6205ATTR_AUTH_TYPE_FLAGS = 0x1004
6206ATTR_AUTHENTICATOR = 0x1005
6207ATTR_CONFIG_METHODS = 0x1008
6208ATTR_CONFIG_ERROR = 0x1009
6209ATTR_CONFIRM_URL4 = 0x100a
6210ATTR_CONFIRM_URL6 = 0x100b
6211ATTR_CONN_TYPE = 0x100c
6212ATTR_CONN_TYPE_FLAGS = 0x100d
6213ATTR_CRED = 0x100e
6214ATTR_ENCR_TYPE = 0x100f
6215ATTR_ENCR_TYPE_FLAGS = 0x1010
6216ATTR_DEV_NAME = 0x1011
6217ATTR_DEV_PASSWORD_ID = 0x1012
6218ATTR_E_HASH1 = 0x1014
6219ATTR_E_HASH2 = 0x1015
6220ATTR_E_SNONCE1 = 0x1016
6221ATTR_E_SNONCE2 = 0x1017
6222ATTR_ENCR_SETTINGS = 0x1018
6223ATTR_ENROLLEE_NONCE = 0x101a
6224ATTR_FEATURE_ID = 0x101b
6225ATTR_IDENTITY = 0x101c
6226ATTR_IDENTITY_PROOF = 0x101d
6227ATTR_KEY_WRAP_AUTH = 0x101e
6228ATTR_KEY_ID = 0x101f
6229ATTR_MAC_ADDR = 0x1020
6230ATTR_MANUFACTURER = 0x1021
6231ATTR_MSG_TYPE = 0x1022
6232ATTR_MODEL_NAME = 0x1023
6233ATTR_MODEL_NUMBER = 0x1024
6234ATTR_NETWORK_INDEX = 0x1026
6235ATTR_NETWORK_KEY = 0x1027
6236ATTR_NETWORK_KEY_INDEX = 0x1028
6237ATTR_NEW_DEVICE_NAME = 0x1029
6238ATTR_NEW_PASSWORD = 0x102a
6239ATTR_OOB_DEVICE_PASSWORD = 0x102c
6240ATTR_OS_VERSION = 0x102d
6241ATTR_POWER_LEVEL = 0x102f
6242ATTR_PSK_CURRENT = 0x1030
6243ATTR_PSK_MAX = 0x1031
6244ATTR_PUBLIC_KEY = 0x1032
6245ATTR_RADIO_ENABLE = 0x1033
6246ATTR_REBOOT = 0x1034
6247ATTR_REGISTRAR_CURRENT = 0x1035
6248ATTR_REGISTRAR_ESTABLISHED = 0x1036
6249ATTR_REGISTRAR_LIST = 0x1037
6250ATTR_REGISTRAR_MAX = 0x1038
6251ATTR_REGISTRAR_NONCE = 0x1039
6252ATTR_REQUEST_TYPE = 0x103a
6253ATTR_RESPONSE_TYPE = 0x103b
6254ATTR_RF_BANDS = 0x103c
6255ATTR_R_HASH1 = 0x103d
6256ATTR_R_HASH2 = 0x103e
6257ATTR_R_SNONCE1 = 0x103f
6258ATTR_R_SNONCE2 = 0x1040
6259ATTR_SELECTED_REGISTRAR = 0x1041
6260ATTR_SERIAL_NUMBER = 0x1042
6261ATTR_WPS_STATE = 0x1044
6262ATTR_SSID = 0x1045
6263ATTR_TOTAL_NETWORKS = 0x1046
6264ATTR_UUID_E = 0x1047
6265ATTR_UUID_R = 0x1048
6266ATTR_VENDOR_EXT = 0x1049
6267ATTR_VERSION = 0x104a
6268ATTR_X509_CERT_REQ = 0x104b
6269ATTR_X509_CERT = 0x104c
6270ATTR_EAP_IDENTITY = 0x104d
6271ATTR_MSG_COUNTER = 0x104e
6272ATTR_PUBKEY_HASH = 0x104f
6273ATTR_REKEY_KEY = 0x1050
6274ATTR_KEY_LIFETIME = 0x1051
6275ATTR_PERMITTED_CFG_METHODS = 0x1052
6276ATTR_SELECTED_REGISTRAR_CONFIG_METHODS = 0x1053
6277ATTR_PRIMARY_DEV_TYPE = 0x1054
6278ATTR_SECONDARY_DEV_TYPE_LIST = 0x1055
6279ATTR_PORTABLE_DEV = 0x1056
6280ATTR_AP_SETUP_LOCKED = 0x1057
6281ATTR_APPLICATION_EXT = 0x1058
6282ATTR_EAP_TYPE = 0x1059
6283ATTR_IV = 0x1060
6284ATTR_KEY_PROVIDED_AUTO = 0x1061
6285ATTR_802_1X_ENABLED = 0x1062
6286ATTR_APPSESSIONKEY = 0x1063
6287ATTR_WEPTRANSMITKEY = 0x1064
6288ATTR_REQUESTED_DEV_TYPE = 0x106a
6289
6290# Message Type
6291WPS_Beacon = 0x01
6292WPS_ProbeRequest = 0x02
6293WPS_ProbeResponse = 0x03
6294WPS_M1 = 0x04
6295WPS_M2 = 0x05
6296WPS_M2D = 0x06
6297WPS_M3 = 0x07
6298WPS_M4 = 0x08
6299WPS_M5 = 0x09
6300WPS_M6 = 0x0a
6301WPS_M7 = 0x0b
6302WPS_M8 = 0x0c
6303WPS_WSC_ACK = 0x0d
6304WPS_WSC_NACK = 0x0e
6305WPS_WSC_DONE = 0x0f
6306
6307def get_wsc_msg(dev):
6308 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
6309 if ev is None:
6310 raise Exception("Timeout on EAPOL-TX")
6311 data = binascii.unhexlify(ev.split(' ')[2])
6312 msg = {}
6313
6314 # Parse EAPOL header
6315 if len(data) < 4:
6316 raise Exception("No room for EAPOL header")
fab49f61 6317 version, type, length = struct.unpack('>BBH', data[0:4])
7511ead0
JM
6318 msg['eapol_version'] = version
6319 msg['eapol_type'] = type
6320 msg['eapol_length'] = length
6321 data = data[4:]
6322 if length != len(data):
6323 raise Exception("EAPOL header length mismatch (%d != %d)" % (length, len(data)))
6324 if type != 0:
6325 raise Exception("Unexpected EAPOL header type: %d" % type)
6326
6327 # Parse EAP header
6328 if len(data) < 4:
6329 raise Exception("No room for EAP header")
fab49f61 6330 code, identifier, length = struct.unpack('>BBH', data[0:4])
7511ead0
JM
6331 msg['eap_code'] = code
6332 msg['eap_identifier'] = identifier
6333 msg['eap_length'] = length
6334 data = data[4:]
6335 if msg['eapol_length'] != msg['eap_length']:
6336 raise Exception("EAP header length mismatch (%d != %d)" % (msg['eapol_length'], length))
6337
6338 # Parse EAP expanded header
6339 if len(data) < 1:
6340 raise Exception("No EAP type included")
786ce912 6341 msg['eap_type'], = struct.unpack('B', data[0:1])
7511ead0
JM
6342 data = data[1:]
6343
6344 if msg['eap_type'] == 254:
6345 if len(data) < 3 + 4:
6346 raise Exception("Truncated EAP expanded header")
15dfcb69 6347 msg['eap_vendor_id'], msg['eap_vendor_type'] = struct.unpack('>LL', b'\x00' + data[0:7])
7511ead0
JM
6348 data = data[7:]
6349 else:
6350 raise Exception("Unexpected EAP type")
6351
6352 if msg['eap_vendor_id'] != WPS_VENDOR_ID_WFA:
6353 raise Exception("Unexpected Vendor-Id")
6354 if msg['eap_vendor_type'] != WPS_VENDOR_TYPE:
6355 raise Exception("Unexpected Vendor-Type")
6356
6357 # Parse EAP-WSC header
6358 if len(data) < 2:
6359 raise Exception("Truncated EAP-WSC header")
6360 msg['wsc_opcode'], msg['wsc_flags'] = struct.unpack('BB', data[0:2])
6361 data = data[2:]
6362
6363 # Parse WSC attributes
6364 msg['raw_attrs'] = data
6365 attrs = {}
6366 while len(data) > 0:
6367 if len(data) < 4:
6368 raise Exception("Truncated attribute header")
fab49f61 6369 attr, length = struct.unpack('>HH', data[0:4])
7511ead0
JM
6370 data = data[4:]
6371 if length > len(data):
6372 raise Exception("Truncated attribute 0x%04x" % attr)
6373 attrs[attr] = data[0:length]
6374 data = data[length:]
6375 msg['wsc_attrs'] = attrs
6376
6377 if ATTR_MSG_TYPE in attrs:
6378 msg['wsc_msg_type'], = struct.unpack('B', attrs[ATTR_MSG_TYPE])
6379
6380 return msg
6381
6382def recv_wsc_msg(dev, opcode, msg_type):
6383 msg = get_wsc_msg(dev)
6384 if msg['wsc_opcode'] != opcode or msg['wsc_msg_type'] != msg_type:
6385 raise Exception("Unexpected Op-Code/MsgType")
6386 return msg, msg['wsc_attrs'], msg['raw_attrs']
6387
6388def build_wsc_attr(attr, payload):
b7da11fd
JM
6389 _payload = payload if type(payload) == bytes else payload.encode()
6390 return struct.pack('>HH', attr, len(_payload)) + _payload
7511ead0
JM
6391
6392def build_attr_msg_type(msg_type):
6393 return build_wsc_attr(ATTR_MSG_TYPE, struct.pack('B', msg_type))
6394
6395def build_eap_wsc(eap_code, eap_id, payload, opcode=WSC_MSG):
6396 length = 4 + 8 + 2 + len(payload)
6397 # EAPOL header
6398 msg = struct.pack('>BBH', 2, 0, length)
6399 # EAP header
6400 msg += struct.pack('>BBH', eap_code, eap_id, length)
6401 # EAP expanded header for EAP-WSC
6402 msg += struct.pack('B', 254)
6403 msg += struct.pack('>L', WPS_VENDOR_ID_WFA)[1:4]
6404 msg += struct.pack('>L', WPS_VENDOR_TYPE)
6405 # EAP-WSC header
6406 msg += struct.pack('BB', opcode, 0)
6407 # WSC attributes
6408 msg += payload
6409 return msg
6410
6411def build_eap_success(eap_id):
6412 length = 4
6413 # EAPOL header
6414 msg = struct.pack('>BBH', 2, 0, length)
6415 # EAP header
6416 msg += struct.pack('>BBH', 3, eap_id, length)
6417 return msg
6418
6419def build_eap_failure(eap_id):
6420 length = 4
6421 # EAPOL header
6422 msg = struct.pack('>BBH', 2, 0, length)
6423 # EAP header
6424 msg += struct.pack('>BBH', 4, eap_id, length)
6425 return msg
6426
6427def send_wsc_msg(dev, src, msg):
7ab74770 6428 res = dev.request("EAPOL_RX " + src + " " + binascii.hexlify(msg).decode())
7511ead0
JM
6429 if "OK" not in res:
6430 raise Exception("EAPOL_RX failed")
6431
6432group_5_prime = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF
6433group_5_generator = 2
6434
6435def wsc_kdf(key, label, bits):
15dfcb69 6436 result = b''
7511ead0
JM
6437 i = 1
6438 while len(result) * 8 < bits:
f94df3c0 6439 data = struct.pack('>L', i) + label.encode() + struct.pack('>L', bits)
7511ead0
JM
6440 m = hmac.new(key, data, hashlib.sha256)
6441 result += m.digest()
6442 i += 1
236bbda8 6443 return result[0:bits // 8]
7511ead0
JM
6444
6445def wsc_keys(kdk):
6446 keys = wsc_kdf(kdk, "Wi-Fi Easy and Secure Key Derivation", 640)
6447 authkey = keys[0:32]
6448 keywrapkey = keys[32:48]
6449 emsk = keys[48:80]
fab49f61 6450 return authkey, keywrapkey, emsk
7511ead0
JM
6451
6452def wsc_dev_pw_half_psk(authkey, dev_pw):
f94df3c0 6453 m = hmac.new(authkey, dev_pw.encode(), hashlib.sha256)
7511ead0
JM
6454 return m.digest()[0:16]
6455
6456def wsc_dev_pw_psk(authkey, dev_pw):
236bbda8
JM
6457 dev_pw_1 = dev_pw[0:len(dev_pw) // 2]
6458 dev_pw_2 = dev_pw[len(dev_pw) // 2:]
7511ead0
JM
6459 psk1 = wsc_dev_pw_half_psk(authkey, dev_pw_1)
6460 psk2 = wsc_dev_pw_half_psk(authkey, dev_pw_2)
fab49f61 6461 return psk1, psk2
7511ead0
JM
6462
6463def build_attr_authenticator(authkey, prev_msg, curr_msg):
6464 m = hmac.new(authkey, prev_msg + curr_msg, hashlib.sha256)
6465 auth = m.digest()[0:8]
6466 return build_wsc_attr(ATTR_AUTHENTICATOR, auth)
6467
6468def build_attr_encr_settings(authkey, keywrapkey, data):
6469 m = hmac.new(authkey, data, hashlib.sha256)
6470 kwa = m.digest()[0:8]
6471 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
15dfcb69 6472 iv = 16*b'\x99'
7511ead0
JM
6473 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6474 pad_len = 16 - len(data) % 16
6475 ps = pad_len * struct.pack('B', pad_len)
6476 data += ps
6477 wrapped = aes.encrypt(data)
6478 return build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6479
6480def decrypt_attr_encr_settings(authkey, keywrapkey, data):
6481 if len(data) < 32 or len(data) % 16 != 0:
6482 raise Exception("Unexpected Encrypted Settings length: %d" % len(data))
6483 iv = data[0:16]
6484 encr = data[16:]
6485 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6486 decrypted = aes.decrypt(encr)
786ce912 6487 pad_len, = struct.unpack('B', decrypted[-1:])
7511ead0
JM
6488 if pad_len > len(decrypted):
6489 raise Exception("Invalid padding in Encrypted Settings")
6490 for i in range(-pad_len, -1):
6491 if decrypted[i] != decrypted[-1]:
6492 raise Exception("Invalid PS value in Encrypted Settings")
db98b587 6493
7511ead0
JM
6494 decrypted = decrypted[0:len(decrypted) - pad_len]
6495 if len(decrypted) < 12:
6496 raise Exception("Truncated Encrypted Settings plaintext")
6497 kwa = decrypted[-12:]
fab49f61 6498 attr, length = struct.unpack(">HH", kwa[0:4])
7511ead0
JM
6499 if attr != ATTR_KEY_WRAP_AUTH or length != 8:
6500 raise Exception("Invalid KWA header")
6501 kwa = kwa[4:]
6502 decrypted = decrypted[0:len(decrypted) - 12]
6503
6504 m = hmac.new(authkey, decrypted, hashlib.sha256)
6505 calc_kwa = m.digest()[0:8]
6506 if kwa != calc_kwa:
6507 raise Exception("KWA mismatch")
6508
6509 return decrypted
6510
6511def zeropad_str(val, pad_len):
6512 while len(val) < pad_len * 2:
6513 val = '0' + val
6514 return val
6515
6516def wsc_dh_init():
6517 # For now, use a hardcoded private key. In theory, this is supposed to be
6518 # randomly selected.
6519 own_private = 0x123456789
6520 own_public = pow(group_5_generator, own_private, group_5_prime)
6521 pk = binascii.unhexlify(zeropad_str(format(own_public, '02x'), 192))
6522 return own_private, pk
6523
6524def wsc_dh_kdf(peer_pk, own_private, mac_addr, e_nonce, r_nonce):
e6b283f7 6525 peer_public = int(binascii.hexlify(peer_pk), 16)
7511ead0
JM
6526 if peer_public < 2 or peer_public >= group_5_prime:
6527 raise Exception("Invalid peer public key")
236bbda8 6528 if pow(peer_public, (group_5_prime - 1) // 2, group_5_prime) != 1:
7511ead0
JM
6529 raise Exception("Unexpected Legendre symbol for peer public key")
6530
6531 shared_secret = pow(peer_public, own_private, group_5_prime)
6532 ss = zeropad_str(format(shared_secret, "02x"), 192)
6533 logger.debug("DH shared secret: " + ss)
6534
6535 dhkey = hashlib.sha256(binascii.unhexlify(ss)).digest()
7ab74770 6536 logger.debug("DHKey: " + binascii.hexlify(dhkey).decode())
7511ead0
JM
6537
6538 m = hmac.new(dhkey, e_nonce + mac_addr + r_nonce, hashlib.sha256)
6539 kdk = m.digest()
7ab74770 6540 logger.debug("KDK: " + binascii.hexlify(kdk).decode())
fab49f61 6541 authkey, keywrapkey, emsk = wsc_keys(kdk)
7ab74770
MH
6542 logger.debug("AuthKey: " + binascii.hexlify(authkey).decode())
6543 logger.debug("KeyWrapKey: " + binascii.hexlify(keywrapkey).decode())
6544 logger.debug("EMSK: " + binascii.hexlify(emsk).decode())
fab49f61 6545 return authkey, keywrapkey
7511ead0
JM
6546
6547def wsc_dev_pw_hash(authkey, dev_pw, e_pk, r_pk):
fab49f61 6548 psk1, psk2 = wsc_dev_pw_psk(authkey, dev_pw)
7ab74770
MH
6549 logger.debug("PSK1: " + binascii.hexlify(psk1).decode())
6550 logger.debug("PSK2: " + binascii.hexlify(psk2).decode())
7511ead0
JM
6551
6552 # Note: Secret values are supposed to be random, but hardcoded values are
6553 # fine for testing.
15dfcb69 6554 s1 = 16*b'\x77'
7511ead0
JM
6555 m = hmac.new(authkey, s1 + psk1 + e_pk + r_pk, hashlib.sha256)
6556 hash1 = m.digest()
7ab74770 6557 logger.debug("Hash1: " + binascii.hexlify(hash1).decode())
7511ead0 6558
15dfcb69 6559 s2 = 16*b'\x88'
7511ead0
JM
6560 m = hmac.new(authkey, s2 + psk2 + e_pk + r_pk, hashlib.sha256)
6561 hash2 = m.digest()
7ab74770 6562 logger.debug("Hash2: " + binascii.hexlify(hash2).decode())
fab49f61 6563 return s1, s2, hash1, hash2
7511ead0
JM
6564
6565def build_m1(eap_id, uuid_e, mac_addr, e_nonce, e_pk,
6566 manufacturer='', model_name='', config_methods='\x00\x00'):
6567 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6568 attrs += build_attr_msg_type(WPS_M1)
6569 attrs += build_wsc_attr(ATTR_UUID_E, uuid_e)
6570 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6571 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6572 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, e_pk)
6573 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6574 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6575 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6576 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, config_methods)
6577 attrs += build_wsc_attr(ATTR_WPS_STATE, '\x00')
6578 attrs += build_wsc_attr(ATTR_MANUFACTURER, manufacturer)
6579 attrs += build_wsc_attr(ATTR_MODEL_NAME, model_name)
6580 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6581 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6582 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6583 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6584 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6585 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6586 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, '\x00\x00')
6587 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6588 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6589 m1 = build_eap_wsc(2, eap_id, attrs)
6590 return m1, attrs
6591
6592def build_m2(authkey, m1, eap_id, e_nonce, r_nonce, uuid_r, r_pk,
6593 dev_pw_id='\x00\x00', eap_code=1):
6594 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6595 attrs += build_attr_msg_type(WPS_M2)
6596 if e_nonce:
6597 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6598 if r_nonce:
6599 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6600 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6601 if r_pk:
6602 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, r_pk)
6603 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6604 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6605 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6606 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6607 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6608 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6609 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6610 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6611 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6612 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6613 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6614 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6615 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6616 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6617 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6618 attrs += build_attr_authenticator(authkey, m1, attrs)
6619 m2 = build_eap_wsc(eap_code, eap_id, attrs)
6620 return m2, attrs
6621
6622def build_m2d(m1, eap_id, e_nonce, r_nonce, uuid_r, dev_pw_id=None, eap_code=1):
6623 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6624 attrs += build_attr_msg_type(WPS_M2D)
6625 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6626 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6627 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6628 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6629 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6630 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6631 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6632 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6633 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6634 #attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6635 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6636 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6637 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6638 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6639 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6640 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6641 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6642 if dev_pw_id:
6643 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6644 m2d = build_eap_wsc(eap_code, eap_id, attrs)
6645 return m2d, attrs
6646
6647def build_ack(eap_id, e_nonce, r_nonce, msg_type=WPS_WSC_ACK, eap_code=1):
6648 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6649 if msg_type is not None:
6650 attrs += build_attr_msg_type(msg_type)
6651 if e_nonce:
6652 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6653 if r_nonce:
6654 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6655 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_ACK)
6656 return msg, attrs
6657
6658def build_nack(eap_id, e_nonce, r_nonce, config_error='\x00\x00',
6659 msg_type=WPS_WSC_NACK, eap_code=1):
6660 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6661 if msg_type is not None:
6662 attrs += build_attr_msg_type(msg_type)
6663 if e_nonce:
6664 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6665 if r_nonce:
6666 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6667 if config_error:
6668 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, config_error)
6669 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_NACK)
6670 return msg, attrs
6671
6672def test_wps_ext(dev, apdev):
6673 """WPS against external implementation"""
6674 pin = "12345670"
fab49f61 6675 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
6676 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6677 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6678
6679 logger.debug("Receive WSC/Start from AP")
6680 msg = get_wsc_msg(hapd)
6681 if msg['wsc_opcode'] != WSC_Start:
6682 raise Exception("Unexpected Op-Code for WSC/Start")
6683 wsc_start_id = msg['eap_identifier']
6684
6685 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
6686 uuid_e = 16*b'\x11'
6687 e_nonce = 16*b'\x22'
7511ead0
JM
6688 own_private, e_pk = wsc_dh_init()
6689
6690 logger.debug("Send M1 to AP")
6691 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
6692 e_nonce, e_pk)
6693 send_wsc_msg(hapd, addr, m1)
6694
6695 logger.debug("Receive M2 from AP")
6696 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
6697
fab49f61
JM
6698 authkey, keywrapkey = wsc_dh_kdf(m2_attrs[ATTR_PUBLIC_KEY], own_private,
6699 mac_addr, e_nonce,
6700 m2_attrs[ATTR_REGISTRAR_NONCE])
6701 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk,
6702 m2_attrs[ATTR_PUBLIC_KEY])
7511ead0
JM
6703
6704 logger.debug("Send M3 to AP")
6705 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6706 attrs += build_attr_msg_type(WPS_M3)
6707 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6708 m2_attrs[ATTR_REGISTRAR_NONCE])
6709 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
6710 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
6711 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
6712 raw_m3_attrs = attrs
6713 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6714 send_wsc_msg(hapd, addr, m3)
6715
6716 logger.debug("Receive M4 from AP")
6717 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
6718
6719 logger.debug("Send M5 to AP")
6720 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6721 attrs += build_attr_msg_type(WPS_M5)
6722 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6723 m2_attrs[ATTR_REGISTRAR_NONCE])
6724 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
6725 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6726 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
6727 raw_m5_attrs = attrs
6728 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6729 send_wsc_msg(hapd, addr, m5)
6730
6731 logger.debug("Receive M6 from AP")
6732 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
6733
6734 logger.debug("Send M7 to AP")
6735 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6736 attrs += build_attr_msg_type(WPS_M7)
6737 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6738 m2_attrs[ATTR_REGISTRAR_NONCE])
6739 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
6740 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6741 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
6742 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6743 raw_m7_attrs = attrs
6744 send_wsc_msg(hapd, addr, m7)
6745
6746 logger.debug("Receive M8 from AP")
6747 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
6748 m8_cred = decrypt_attr_encr_settings(authkey, keywrapkey,
6749 m8_attrs[ATTR_ENCR_SETTINGS])
7ab74770 6750 logger.debug("M8 Credential: " + binascii.hexlify(m8_cred).decode())
7511ead0
JM
6751
6752 logger.debug("Prepare WSC_Done")
6753 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6754 attrs += build_attr_msg_type(WPS_WSC_DONE)
6755 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6756 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6757 m2_attrs[ATTR_REGISTRAR_NONCE])
6758 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
6759 # Do not send WSC_Done yet to allow exchangw with STA complete before the
6760 # AP disconnects.
6761
15dfcb69
MH
6762 uuid_r = 16*b'\x33'
6763 r_nonce = 16*b'\x44'
7511ead0
JM
6764
6765 eap_id = wsc_start_id
6766 logger.debug("Send WSC/Start to STA")
15dfcb69 6767 wsc_start = build_eap_wsc(1, eap_id, b'', opcode=WSC_Start)
7511ead0
JM
6768 send_wsc_msg(dev[0], bssid, wsc_start)
6769 eap_id = (eap_id + 1) % 256
6770
6771 logger.debug("Receive M1 from STA")
6772 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6773
fab49f61
JM
6774 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6775 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6776 r_nonce)
6777 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
6778 m1_attrs[ATTR_PUBLIC_KEY],
6779 e_pk)
7511ead0
JM
6780
6781 logger.debug("Send M2 to STA")
6782 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6783 m1_attrs[ATTR_ENROLLEE_NONCE],
6784 r_nonce, uuid_r, e_pk)
6785 send_wsc_msg(dev[0], bssid, m2)
6786 eap_id = (eap_id + 1) % 256
6787
6788 logger.debug("Receive M3 from STA")
6789 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6790
6791 logger.debug("Send M4 to STA")
6792 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6793 attrs += build_attr_msg_type(WPS_M4)
6794 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6795 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6796 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6797 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6798 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6799 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6800 raw_m4_attrs = attrs
6801 m4 = build_eap_wsc(1, eap_id, attrs)
6802 send_wsc_msg(dev[0], bssid, m4)
6803 eap_id = (eap_id + 1) % 256
6804
6805 logger.debug("Receive M5 from STA")
6806 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6807
6808 logger.debug("Send M6 to STA")
6809 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6810 attrs += build_attr_msg_type(WPS_M6)
6811 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6812 m1_attrs[ATTR_ENROLLEE_NONCE])
6813 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6814 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6815 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6816 raw_m6_attrs = attrs
6817 m6 = build_eap_wsc(1, eap_id, attrs)
6818 send_wsc_msg(dev[0], bssid, m6)
6819 eap_id = (eap_id + 1) % 256
6820
6821 logger.debug("Receive M7 from STA")
6822 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6823
6824 logger.debug("Send M8 to STA")
6825 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6826 attrs += build_attr_msg_type(WPS_M8)
6827 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6828 m1_attrs[ATTR_ENROLLEE_NONCE])
6829 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6830 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6831 raw_m8_attrs = attrs
6832 m8 = build_eap_wsc(1, eap_id, attrs)
6833 send_wsc_msg(dev[0], bssid, m8)
6834 eap_id = (eap_id + 1) % 256
6835
6836 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=5)
6837 if ev is None:
6838 raise Exception("wpa_supplicant did not report credential")
6839
6840 logger.debug("Receive WSC_Done from STA")
6841 msg = get_wsc_msg(dev[0])
6842 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6843 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6844
6845 logger.debug("Send WSC_Done to AP")
6846 hapd.request("SET ext_eapol_frame_io 0")
6847 dev[0].request("SET ext_eapol_frame_io 0")
6848 send_wsc_msg(hapd, addr, wsc_done)
6849
6850 ev = hapd.wait_event(["WPS-REG-SUCCESS"], timeout=5)
6851 if ev is None:
6852 raise Exception("hostapd did not report WPS success")
6853
6854 dev[0].wait_connected()
6855
6856def wps_start_kwa(dev, apdev):
6857 pin = "12345670"
fab49f61 6858 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
6859 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6860 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6861 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6862
6863 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
6864 uuid_r = 16*b'\x33'
6865 r_nonce = 16*b'\x44'
7511ead0
JM
6866 own_private, e_pk = wsc_dh_init()
6867
6868 logger.debug("Receive M1 from STA")
6869 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6870 eap_id = (msg['eap_identifier'] + 1) % 256
6871
fab49f61
JM
6872 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6873 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6874 r_nonce)
6875 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
6876 m1_attrs[ATTR_PUBLIC_KEY],
6877 e_pk)
7511ead0
JM
6878
6879 logger.debug("Send M2 to STA")
6880 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6881 m1_attrs[ATTR_ENROLLEE_NONCE],
6882 r_nonce, uuid_r, e_pk)
6883 send_wsc_msg(dev[0], bssid, m2)
6884 eap_id = (eap_id + 1) % 256
6885
6886 logger.debug("Receive M3 from STA")
6887 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6888
6889 logger.debug("Send M4 to STA")
6890 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6891 attrs += build_attr_msg_type(WPS_M4)
6892 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6893 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6894 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6895
6896 return r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs
6897
6898def wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id):
6899 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6900 m4 = build_eap_wsc(1, eap_id, attrs)
6901 send_wsc_msg(dev[0], bssid, m4)
6902 eap_id = (eap_id + 1) % 256
6903
6904 logger.debug("Receive M5 from STA")
6905 msg = get_wsc_msg(dev[0])
6906 if msg['wsc_opcode'] != WSC_NACK:
6907 raise Exception("Unexpected message - expected WSC_Nack")
6908
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_kwa_proto_no_kwa(dev, apdev):
6914 """WPS and KWA error: No KWA attribute"""
fab49f61 6915 r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs = wps_start_kwa(dev, apdev)
7511ead0
JM
6916 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6917 # Encrypted Settings without KWA
15dfcb69 6918 iv = 16*b'\x99'
7511ead0
JM
6919 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6920 pad_len = 16 - len(data) % 16
6921 ps = pad_len * struct.pack('B', pad_len)
6922 data += ps
6923 wrapped = aes.encrypt(data)
6924 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6925 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6926
6927def test_wps_ext_kwa_proto_data_after_kwa(dev, apdev):
6928 """WPS and KWA error: Data after KWA"""
fab49f61 6929 r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs = wps_start_kwa(dev, apdev)
7511ead0
JM
6930 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6931 # Encrypted Settings and data after KWA
6932 m = hmac.new(authkey, data, hashlib.sha256)
6933 kwa = m.digest()[0:8]
6934 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6935 data += build_wsc_attr(ATTR_VENDOR_EXT, "1234567890")
15dfcb69 6936 iv = 16*b'\x99'
7511ead0
JM
6937 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6938 pad_len = 16 - len(data) % 16
6939 ps = pad_len * struct.pack('B', pad_len)
6940 data += ps
6941 wrapped = aes.encrypt(data)
6942 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6943 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6944
6945def test_wps_ext_kwa_proto_kwa_mismatch(dev, apdev):
6946 """WPS and KWA error: KWA mismatch"""
fab49f61 6947 r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs = wps_start_kwa(dev, apdev)
7511ead0
JM
6948 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6949 # Encrypted Settings and KWA with incorrect value
6950 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, 8*'\x00')
15dfcb69 6951 iv = 16*b'\x99'
7511ead0
JM
6952 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6953 pad_len = 16 - len(data) % 16
6954 ps = pad_len * struct.pack('B', pad_len)
6955 data += ps
6956 wrapped = aes.encrypt(data)
6957 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6958 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6959
6960def wps_run_cred_proto(dev, apdev, m8_cred, connect=False, no_connect=False):
6961 pin = "12345670"
fab49f61 6962 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
6963 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6964 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6965 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6966
6967 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
6968 uuid_r = 16*b'\x33'
6969 r_nonce = 16*b'\x44'
7511ead0
JM
6970 own_private, e_pk = wsc_dh_init()
6971
6972 logger.debug("Receive M1 from STA")
6973 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6974 eap_id = (msg['eap_identifier'] + 1) % 256
6975
fab49f61
JM
6976 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6977 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6978 r_nonce)
6979 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
6980 m1_attrs[ATTR_PUBLIC_KEY],
6981 e_pk)
7511ead0
JM
6982
6983 logger.debug("Send M2 to STA")
6984 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6985 m1_attrs[ATTR_ENROLLEE_NONCE],
6986 r_nonce, uuid_r, e_pk)
6987 send_wsc_msg(dev[0], bssid, m2)
6988 eap_id = (eap_id + 1) % 256
6989
6990 logger.debug("Receive M3 from STA")
6991 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6992
6993 logger.debug("Send M4 to STA")
6994 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6995 attrs += build_attr_msg_type(WPS_M4)
6996 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6997 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6998 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6999 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7000 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7001 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7002 raw_m4_attrs = attrs
7003 m4 = build_eap_wsc(1, eap_id, attrs)
7004 send_wsc_msg(dev[0], bssid, m4)
7005 eap_id = (eap_id + 1) % 256
7006
7007 logger.debug("Receive M5 from STA")
7008 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7009
7010 logger.debug("Send M6 to STA")
7011 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7012 attrs += build_attr_msg_type(WPS_M6)
7013 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
7014 m1_attrs[ATTR_ENROLLEE_NONCE])
7015 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7016 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7017 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
7018 raw_m6_attrs = attrs
7019 m6 = build_eap_wsc(1, eap_id, attrs)
7020 send_wsc_msg(dev[0], bssid, m6)
7021 eap_id = (eap_id + 1) % 256
7022
7023 logger.debug("Receive M7 from STA")
7024 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
7025
7026 logger.debug("Send M8 to STA")
7027 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7028 attrs += build_attr_msg_type(WPS_M8)
7029 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
7030 m1_attrs[ATTR_ENROLLEE_NONCE])
7031 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
7032 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7033 raw_m8_attrs = attrs
7034 m8 = build_eap_wsc(1, eap_id, attrs)
7035 send_wsc_msg(dev[0], bssid, m8)
7036 eap_id = (eap_id + 1) % 256
7037
7038 if no_connect:
7039 logger.debug("Receive WSC_Done from STA")
7040 msg = get_wsc_msg(dev[0])
7041 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
7042 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
7043
7044 hapd.request("SET ext_eapol_frame_io 0")
7045 dev[0].request("SET ext_eapol_frame_io 0")
7046
7047 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7048
7049 dev[0].wait_disconnected()
7050 dev[0].request("REMOVE_NETWORK all")
7051 elif connect:
7052 logger.debug("Receive WSC_Done from STA")
7053 msg = get_wsc_msg(dev[0])
7054 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
7055 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
7056
7057 hapd.request("SET ext_eapol_frame_io 0")
7058 dev[0].request("SET ext_eapol_frame_io 0")
7059
7060 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7061
7062 dev[0].wait_connected()
7063 else:
7064 # Verify STA NACK's the credential
7065 msg = get_wsc_msg(dev[0])
7066 if msg['wsc_opcode'] != WSC_NACK:
7067 raise Exception("Unexpected message - expected WSC_Nack")
7068 dev[0].request("WPS_CANCEL")
7069 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7070 dev[0].wait_disconnected()
7071
7072def build_cred(nw_idx='\x01', ssid='test-wps-conf', auth_type='\x00\x20',
7073 encr_type='\x00\x08', nw_key="12345678",
7074 mac_addr='\x00\x00\x00\x00\x00\x00'):
15dfcb69 7075 attrs = b''
7511ead0
JM
7076 if nw_idx is not None:
7077 attrs += build_wsc_attr(ATTR_NETWORK_INDEX, nw_idx)
7078 if ssid is not None:
7079 attrs += build_wsc_attr(ATTR_SSID, ssid)
7080 if auth_type is not None:
7081 attrs += build_wsc_attr(ATTR_AUTH_TYPE, auth_type)
7082 if encr_type is not None:
7083 attrs += build_wsc_attr(ATTR_ENCR_TYPE, encr_type)
7084 if nw_key is not None:
7085 attrs += build_wsc_attr(ATTR_NETWORK_KEY, nw_key)
7086 if mac_addr is not None:
7087 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
7088 return build_wsc_attr(ATTR_CRED, attrs)
7089
7090def test_wps_ext_cred_proto_success(dev, apdev):
7091 """WPS and Credential: success"""
7092 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7093 m8_cred = build_cred(mac_addr=mac_addr)
7094 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
7095
7096def test_wps_ext_cred_proto_mac_addr_mismatch(dev, apdev):
7097 """WPS and Credential: MAC Address mismatch"""
7098 m8_cred = build_cred()
7099 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
7100
7101def test_wps_ext_cred_proto_zero_padding(dev, apdev):
7102 """WPS and Credential: zeropadded attributes"""
7103 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7104 m8_cred = build_cred(mac_addr=mac_addr, ssid='test-wps-conf\x00',
7105 nw_key="12345678\x00")
7106 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
7107
7108def test_wps_ext_cred_proto_ssid_missing(dev, apdev):
7109 """WPS and Credential: SSID missing"""
7110 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7111 m8_cred = build_cred(mac_addr=mac_addr, ssid=None)
7112 wps_run_cred_proto(dev, apdev, m8_cred)
7113
7114def test_wps_ext_cred_proto_ssid_zero_len(dev, apdev):
7115 """WPS and Credential: Zero-length SSID"""
7116 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7117 m8_cred = build_cred(mac_addr=mac_addr, ssid="")
7118 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
7119
7120def test_wps_ext_cred_proto_auth_type_missing(dev, apdev):
7121 """WPS and Credential: Auth Type missing"""
7122 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7123 m8_cred = build_cred(mac_addr=mac_addr, auth_type=None)
7124 wps_run_cred_proto(dev, apdev, m8_cred)
7125
7126def test_wps_ext_cred_proto_encr_type_missing(dev, apdev):
7127 """WPS and Credential: Encr Type missing"""
7128 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7129 m8_cred = build_cred(mac_addr=mac_addr, encr_type=None)
7130 wps_run_cred_proto(dev, apdev, m8_cred)
7131
7132def test_wps_ext_cred_proto_network_key_missing(dev, apdev):
7133 """WPS and Credential: Network Key missing"""
7134 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7135 m8_cred = build_cred(mac_addr=mac_addr, nw_key=None)
7136 wps_run_cred_proto(dev, apdev, m8_cred)
7137
7138def test_wps_ext_cred_proto_network_key_missing_open(dev, apdev):
7139 """WPS and Credential: Network Key missing (open)"""
7140 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7141 m8_cred = build_cred(mac_addr=mac_addr, auth_type='\x00\x01',
7142 encr_type='\x00\x01', nw_key=None, ssid="foo")
7143 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
7144
7145def test_wps_ext_cred_proto_mac_addr_missing(dev, apdev):
7146 """WPS and Credential: MAC Address missing"""
7147 m8_cred = build_cred(mac_addr=None)
7148 wps_run_cred_proto(dev, apdev, m8_cred)
7149
7150def test_wps_ext_cred_proto_invalid_encr_type(dev, apdev):
7151 """WPS and Credential: Invalid Encr Type"""
7152 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7153 m8_cred = build_cred(mac_addr=mac_addr, encr_type='\x00\x00')
7154 wps_run_cred_proto(dev, apdev, m8_cred)
7155
7156def test_wps_ext_cred_proto_missing_cred(dev, apdev):
7157 """WPS and Credential: Missing Credential"""
7158 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69 7159 m8_cred = b''
7511ead0
JM
7160 wps_run_cred_proto(dev, apdev, m8_cred)
7161
7162def test_wps_ext_proto_m2_no_public_key(dev, apdev):
7163 """WPS and no Public Key in M2"""
7164 pin = "12345670"
fab49f61 7165 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
7166 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7167 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7168 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7169
7170 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
7171 uuid_r = 16*b'\x33'
7172 r_nonce = 16*b'\x44'
7511ead0
JM
7173 own_private, e_pk = wsc_dh_init()
7174
7175 logger.debug("Receive M1 from STA")
7176 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7177 eap_id = (msg['eap_identifier'] + 1) % 256
7178
fab49f61
JM
7179 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7180 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7181 r_nonce)
7182 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7183 m1_attrs[ATTR_PUBLIC_KEY],
7184 e_pk)
7511ead0
JM
7185
7186 logger.debug("Send M2 to STA")
7187 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7188 m1_attrs[ATTR_ENROLLEE_NONCE],
7189 r_nonce, uuid_r, None)
7190 send_wsc_msg(dev[0], bssid, m2)
7191 eap_id = (eap_id + 1) % 256
7192
7193 # Verify STA NACK's the credential
7194 msg = get_wsc_msg(dev[0])
7195 if msg['wsc_opcode'] != WSC_NACK:
7196 raise Exception("Unexpected message - expected WSC_Nack")
7197 dev[0].request("WPS_CANCEL")
7198 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7199 dev[0].wait_disconnected()
7200
7201def test_wps_ext_proto_m2_invalid_public_key(dev, apdev):
7202 """WPS and invalid Public Key in M2"""
7203 pin = "12345670"
fab49f61 7204 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
7205 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7206 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7207 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7208
7209 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
7210 uuid_r = 16*b'\x33'
7211 r_nonce = 16*b'\x44'
7511ead0
JM
7212 own_private, e_pk = wsc_dh_init()
7213
7214 logger.debug("Receive M1 from STA")
7215 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7216 eap_id = (msg['eap_identifier'] + 1) % 256
7217
fab49f61
JM
7218 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7219 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7220 r_nonce)
7221 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7222 m1_attrs[ATTR_PUBLIC_KEY],
7223 e_pk)
7511ead0
JM
7224
7225 logger.debug("Send M2 to STA")
7226 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7227 m1_attrs[ATTR_ENROLLEE_NONCE],
15dfcb69 7228 r_nonce, uuid_r, 192*b'\xff')
7511ead0
JM
7229 send_wsc_msg(dev[0], bssid, m2)
7230 eap_id = (eap_id + 1) % 256
7231
7232 # Verify STA NACK's the credential
7233 msg = get_wsc_msg(dev[0])
7234 if msg['wsc_opcode'] != WSC_NACK:
7235 raise Exception("Unexpected message - expected WSC_Nack")
7236 dev[0].request("WPS_CANCEL")
7237 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7238 dev[0].wait_disconnected()
7239
7240def test_wps_ext_proto_m2_public_key_oom(dev, apdev):
7241 """WPS and Public Key OOM in M2"""
7242 pin = "12345670"
fab49f61 7243 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
7244 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7245 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7246 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7247
7248 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
7249 uuid_r = 16*b'\x33'
7250 r_nonce = 16*b'\x44'
7511ead0
JM
7251 own_private, e_pk = wsc_dh_init()
7252
7253 logger.debug("Receive M1 from STA")
7254 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7255 eap_id = (msg['eap_identifier'] + 1) % 256
7256
fab49f61
JM
7257 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7258 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7259 r_nonce)
7260 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7261 m1_attrs[ATTR_PUBLIC_KEY],
7262 e_pk)
7511ead0
JM
7263
7264 logger.debug("Send M2 to STA")
7265 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7266 m1_attrs[ATTR_ENROLLEE_NONCE],
7267 r_nonce, uuid_r, e_pk)
7268 with alloc_fail(dev[0], 1, "wpabuf_alloc_copy;wps_process_pubkey"):
7269 send_wsc_msg(dev[0], bssid, m2)
7270 eap_id = (eap_id + 1) % 256
7271
7272 # Verify STA NACK's the credential
7273 msg = get_wsc_msg(dev[0])
7274 if msg['wsc_opcode'] != WSC_NACK:
7275 raise Exception("Unexpected message - expected WSC_Nack")
7276 dev[0].request("WPS_CANCEL")
7277 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7278 dev[0].wait_disconnected()
7279
7280def test_wps_ext_proto_nack_m3(dev, apdev):
7281 """WPS and NACK M3"""
7282 pin = "12345670"
fab49f61 7283 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
7284 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7285 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7286 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7287
7288 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
7289 uuid_r = 16*b'\x33'
7290 r_nonce = 16*b'\x44'
7511ead0
JM
7291 own_private, e_pk = wsc_dh_init()
7292
7293 logger.debug("Receive M1 from STA")
7294 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7295 eap_id = (msg['eap_identifier'] + 1) % 256
7296
fab49f61
JM
7297 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7298 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7299 r_nonce)
7300 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7301 m1_attrs[ATTR_PUBLIC_KEY],
7302 e_pk)
7511ead0
JM
7303
7304 logger.debug("Send M2 to STA")
7305 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7306 m1_attrs[ATTR_ENROLLEE_NONCE],
7307 r_nonce, uuid_r, e_pk)
7308 send_wsc_msg(dev[0], bssid, m2)
7309 eap_id = (eap_id + 1) % 256
7310
7311 logger.debug("Receive M3 from STA")
7312 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7313
7314 logger.debug("Send NACK to STA")
7315 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7316 r_nonce, config_error='\x01\x23')
7317 send_wsc_msg(dev[0], bssid, msg)
7318 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7319 if ev is None:
7320 raise Exception("Failure not reported")
7321 if "msg=7 config_error=291" not in ev:
7322 raise Exception("Unexpected failure reason: " + ev)
7323
7324def test_wps_ext_proto_nack_m5(dev, apdev):
7325 """WPS and NACK M5"""
7326 pin = "12345670"
fab49f61 7327 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
7328 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7329 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7330 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7331
7332 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
7333 uuid_r = 16*b'\x33'
7334 r_nonce = 16*b'\x44'
7511ead0
JM
7335 own_private, e_pk = wsc_dh_init()
7336
7337 logger.debug("Receive M1 from STA")
7338 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7339 eap_id = (msg['eap_identifier'] + 1) % 256
7340
fab49f61
JM
7341 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7342 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7343 r_nonce)
7344 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7345 m1_attrs[ATTR_PUBLIC_KEY],
7346 e_pk)
7511ead0
JM
7347
7348 logger.debug("Send M2 to STA")
7349 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7350 m1_attrs[ATTR_ENROLLEE_NONCE],
7351 r_nonce, uuid_r, e_pk)
7352 send_wsc_msg(dev[0], bssid, m2)
7353 eap_id = (eap_id + 1) % 256
7354
7355 logger.debug("Receive M3 from STA")
7356 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7357
7358 logger.debug("Send M4 to STA")
7359 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7360 attrs += build_attr_msg_type(WPS_M4)
7361 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7362 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7363 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7364 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7365 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7366 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7367 raw_m4_attrs = attrs
7368 m4 = build_eap_wsc(1, eap_id, attrs)
7369 send_wsc_msg(dev[0], bssid, m4)
7370 eap_id = (eap_id + 1) % 256
7371
7372 logger.debug("Receive M5 from STA")
7373 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7374
7375 logger.debug("Send NACK to STA")
7376 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7377 r_nonce, config_error='\x01\x24')
7378 send_wsc_msg(dev[0], bssid, msg)
7379 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7380 if ev is None:
7381 raise Exception("Failure not reported")
7382 if "msg=9 config_error=292" not in ev:
7383 raise Exception("Unexpected failure reason: " + ev)
7384
7385def wps_nack_m3(dev, apdev):
7386 pin = "00000000"
fab49f61 7387 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
7511ead0
JM
7388 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7389 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7390 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7391
7392 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
7393 uuid_r = 16*b'\x33'
7394 r_nonce = 16*b'\x44'
7511ead0
JM
7395 own_private, e_pk = wsc_dh_init()
7396
7397 logger.debug("Receive M1 from STA")
7398 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7399 eap_id = (msg['eap_identifier'] + 1) % 256
7400
fab49f61
JM
7401 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7402 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7403 r_nonce)
7404 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7405 m1_attrs[ATTR_PUBLIC_KEY],
7406 e_pk)
7511ead0
JM
7407
7408 logger.debug("Send M2 to STA")
7409 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7410 m1_attrs[ATTR_ENROLLEE_NONCE],
7411 r_nonce, uuid_r, e_pk, dev_pw_id='\x00\x04')
7412 send_wsc_msg(dev[0], bssid, m2)
7413 eap_id = (eap_id + 1) % 256
7414
7415 logger.debug("Receive M3 from STA")
7416 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7417 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid
7418
7419def test_wps_ext_proto_nack_m3_no_config_error(dev, apdev):
7420 """WPS and NACK M3 missing Config Error"""
7421 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7422 logger.debug("Send NACK to STA")
7423 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, config_error=None)
7424 send_wsc_msg(dev[0], bssid, msg)
7425 dev[0].request("WPS_CANCEL")
7426 dev[0].wait_disconnected()
7427 dev[0].flush_scan_cache()
7428
7429def test_wps_ext_proto_nack_m3_no_e_nonce(dev, apdev):
7430 """WPS and NACK M3 missing E-Nonce"""
7431 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7432 logger.debug("Send NACK to STA")
7433 msg, attrs = build_nack(eap_id, None, r_nonce)
7434 send_wsc_msg(dev[0], bssid, msg)
7435 dev[0].request("WPS_CANCEL")
7436 dev[0].wait_disconnected()
7437 dev[0].flush_scan_cache()
7438
7439def test_wps_ext_proto_nack_m3_e_nonce_mismatch(dev, apdev):
7440 """WPS and NACK M3 E-Nonce mismatch"""
7441 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7442 logger.debug("Send NACK to STA")
7443 msg, attrs = build_nack(eap_id, 16*'\x00', r_nonce)
7444 send_wsc_msg(dev[0], bssid, msg)
7445 dev[0].request("WPS_CANCEL")
7446 dev[0].wait_disconnected()
7447 dev[0].flush_scan_cache()
7448
7449def test_wps_ext_proto_nack_m3_no_r_nonce(dev, apdev):
7450 """WPS and NACK M3 missing R-Nonce"""
7451 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7452 logger.debug("Send NACK to STA")
7453 msg, attrs = build_nack(eap_id, e_nonce, None)
7454 send_wsc_msg(dev[0], bssid, msg)
7455 dev[0].request("WPS_CANCEL")
7456 dev[0].wait_disconnected()
7457 dev[0].flush_scan_cache()
7458
7459def test_wps_ext_proto_nack_m3_r_nonce_mismatch(dev, apdev):
7460 """WPS and NACK M3 R-Nonce mismatch"""
7461 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7462 logger.debug("Send NACK to STA")
7463 msg, attrs = build_nack(eap_id, e_nonce, 16*'\x00')
7464 send_wsc_msg(dev[0], bssid, msg)
7465 dev[0].request("WPS_CANCEL")
7466 dev[0].wait_disconnected()
7467 dev[0].flush_scan_cache()
7468
7469def test_wps_ext_proto_nack_m3_no_msg_type(dev, apdev):
7470 """WPS and NACK M3 no Message Type"""
7471 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7472 logger.debug("Send NACK to STA")
7473 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=None)
7474 send_wsc_msg(dev[0], bssid, msg)
7475 dev[0].request("WPS_CANCEL")
7476 dev[0].wait_disconnected()
7477 dev[0].flush_scan_cache()
7478
7479def test_wps_ext_proto_nack_m3_invalid_msg_type(dev, apdev):
7480 """WPS and NACK M3 invalid Message Type"""
7481 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7482 logger.debug("Send NACK to STA")
7483 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=123)
7484 send_wsc_msg(dev[0], bssid, msg)
7485 dev[0].request("WPS_CANCEL")
7486 dev[0].wait_disconnected()
7487 dev[0].flush_scan_cache()
7488
7489def test_wps_ext_proto_nack_m3_invalid_attr(dev, apdev):
7490 """WPS and NACK M3 invalid attribute"""
7491 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7492 logger.debug("Send NACK to STA")
15dfcb69 7493 attrs = b'\x10\x10\x00'
7511ead0
JM
7494 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_NACK)
7495 send_wsc_msg(dev[0], bssid, msg)
7496 dev[0].request("WPS_CANCEL")
7497 dev[0].wait_disconnected()
7498 dev[0].flush_scan_cache()
7499
7500def test_wps_ext_proto_ack_m3_no_e_nonce(dev, apdev):
7501 """WPS and ACK M3 missing E-Nonce"""
7502 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7503 logger.debug("Send NACK to STA")
7504 msg, attrs = build_ack(eap_id, None, r_nonce)
7505 send_wsc_msg(dev[0], bssid, msg)
7506 dev[0].request("WPS_CANCEL")
7507 dev[0].wait_disconnected()
7508 dev[0].flush_scan_cache()
7509
7510def test_wps_ext_proto_ack_m3_e_nonce_mismatch(dev, apdev):
7511 """WPS and ACK M3 E-Nonce mismatch"""
7512 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7513 logger.debug("Send NACK to STA")
7514 msg, attrs = build_ack(eap_id, 16*'\x00', r_nonce)
7515 send_wsc_msg(dev[0], bssid, msg)
7516 dev[0].request("WPS_CANCEL")
7517 dev[0].wait_disconnected()
7518 dev[0].flush_scan_cache()
7519
7520def test_wps_ext_proto_ack_m3_no_r_nonce(dev, apdev):
7521 """WPS and ACK M3 missing R-Nonce"""
7522 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7523 logger.debug("Send NACK to STA")
7524 msg, attrs = build_ack(eap_id, e_nonce, None)
7525 send_wsc_msg(dev[0], bssid, msg)
7526 dev[0].request("WPS_CANCEL")
7527 dev[0].wait_disconnected()
7528 dev[0].flush_scan_cache()
7529
7530def test_wps_ext_proto_ack_m3_r_nonce_mismatch(dev, apdev):
7531 """WPS and ACK M3 R-Nonce mismatch"""
7532 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7533 logger.debug("Send NACK to STA")
7534 msg, attrs = build_ack(eap_id, e_nonce, 16*'\x00')
7535 send_wsc_msg(dev[0], bssid, msg)
7536 dev[0].request("WPS_CANCEL")
7537 dev[0].wait_disconnected()
7538 dev[0].flush_scan_cache()
7539
7540def test_wps_ext_proto_ack_m3_no_msg_type(dev, apdev):
7541 """WPS and ACK M3 no Message Type"""
7542 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7543 logger.debug("Send NACK to STA")
7544 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=None)
7545 send_wsc_msg(dev[0], bssid, msg)
7546 dev[0].request("WPS_CANCEL")
7547 dev[0].wait_disconnected()
7548 dev[0].flush_scan_cache()
7549
7550def test_wps_ext_proto_ack_m3_invalid_msg_type(dev, apdev):
7551 """WPS and ACK M3 invalid Message Type"""
7552 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7553 logger.debug("Send NACK to STA")
7554 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=123)
7555 send_wsc_msg(dev[0], bssid, msg)
7556 dev[0].request("WPS_CANCEL")
7557 dev[0].wait_disconnected()
7558 dev[0].flush_scan_cache()
7559
7560def test_wps_ext_proto_ack_m3_invalid_attr(dev, apdev):
7561 """WPS and ACK M3 invalid attribute"""
7562 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7563 logger.debug("Send ACK to STA")
15dfcb69 7564 attrs = b'\x10\x10\x00'
7511ead0
JM
7565 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_ACK)
7566 send_wsc_msg(dev[0], bssid, msg)
7567 dev[0].request("WPS_CANCEL")
7568 dev[0].wait_disconnected()
7569 dev[0].flush_scan_cache()
7570
7571def test_wps_ext_proto_ack_m3(dev, apdev):
7572 """WPS and ACK M3"""
7573 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7574 logger.debug("Send ACK to STA")
7575 msg, attrs = build_ack(eap_id, e_nonce, r_nonce)
7576 send_wsc_msg(dev[0], bssid, msg)
7577 dev[0].request("WPS_CANCEL")
7578 dev[0].wait_disconnected()
7579 dev[0].flush_scan_cache()
7580
7581def wps_to_m3_helper(dev, apdev):
7582 pin = "12345670"
fab49f61 7583 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
7584 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7585 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7586 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7587
7588 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
7589 uuid_r = 16*b'\x33'
7590 r_nonce = 16*b'\x44'
7511ead0
JM
7591 own_private, e_pk = wsc_dh_init()
7592
7593 logger.debug("Receive M1 from STA")
7594 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7595 eap_id = (msg['eap_identifier'] + 1) % 256
7596
fab49f61
JM
7597 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7598 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7599 r_nonce)
7600 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7601 m1_attrs[ATTR_PUBLIC_KEY],
7602 e_pk)
7511ead0
JM
7603
7604 logger.debug("Send M2 to STA")
7605 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7606 m1_attrs[ATTR_ENROLLEE_NONCE],
7607 r_nonce, uuid_r, e_pk)
7608 send_wsc_msg(dev[0], bssid, m2)
7609 eap_id = (eap_id + 1) % 256
7610
7611 logger.debug("Receive M3 from STA")
7612 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7613 return eap_id, m1_attrs, r_nonce, bssid, r_hash1, r_hash2, r_s1, r_s2, raw_m3_attrs, authkey, keywrapkey
7614
7615def wps_to_m3(dev, apdev):
7616 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)
7617 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s1, raw_m3_attrs, authkey, keywrapkey
7618
7619def wps_to_m5(dev, apdev):
7620 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)
7621
7622 logger.debug("Send M4 to STA")
7623 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7624 attrs += build_attr_msg_type(WPS_M4)
7625 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7626 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7627 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7628 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7629 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7630 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7631 raw_m4_attrs = attrs
7632 m4 = build_eap_wsc(1, eap_id, attrs)
7633 send_wsc_msg(dev[0], bssid, m4)
7634 eap_id = (eap_id + 1) % 256
7635
7636 logger.debug("Receive M5 from STA")
7637 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7638
7639 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s2, raw_m5_attrs, authkey, keywrapkey
7640
7641def test_wps_ext_proto_m4_missing_r_hash1(dev, apdev):
7642 """WPS and no R-Hash1 in M4"""
7643 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7644
7645 logger.debug("Send M4 to STA")
7646 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7647 attrs += build_attr_msg_type(WPS_M4)
7648 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7649 #attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7650 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7651 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7652 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7653 attrs += build_attr_authenticator(authkey, m3, attrs)
7654 m4 = build_eap_wsc(1, eap_id, attrs)
7655 send_wsc_msg(dev[0], bssid, m4)
7656 eap_id = (eap_id + 1) % 256
7657
7658 logger.debug("Receive M5 (NACK) from STA")
7659 msg = get_wsc_msg(dev[0])
7660 if msg['wsc_opcode'] != WSC_NACK:
7661 raise Exception("Unexpected message - expected WSC_Nack")
7662
7663 dev[0].request("WPS_CANCEL")
7664 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7665 dev[0].wait_disconnected()
7666
7667def test_wps_ext_proto_m4_missing_r_hash2(dev, apdev):
7668 """WPS and no R-Hash2 in M4"""
7669 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7670
7671 logger.debug("Send M4 to STA")
7672 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7673 attrs += build_attr_msg_type(WPS_M4)
7674 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7675 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7676 #attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7677 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7678 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7679 attrs += build_attr_authenticator(authkey, m3, attrs)
7680 m4 = build_eap_wsc(1, eap_id, attrs)
7681 send_wsc_msg(dev[0], bssid, m4)
7682 eap_id = (eap_id + 1) % 256
7683
7684 logger.debug("Receive M5 (NACK) from STA")
7685 msg = get_wsc_msg(dev[0])
7686 if msg['wsc_opcode'] != WSC_NACK:
7687 raise Exception("Unexpected message - expected WSC_Nack")
7688
7689 dev[0].request("WPS_CANCEL")
7690 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7691 dev[0].wait_disconnected()
7692
7693def test_wps_ext_proto_m4_missing_r_snonce1(dev, apdev):
7694 """WPS and no R-SNonce1 in M4"""
7695 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7696
7697 logger.debug("Send M4 to STA")
7698 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7699 attrs += build_attr_msg_type(WPS_M4)
7700 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7701 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7702 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7703 #data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
15dfcb69 7704 data = b''
7511ead0
JM
7705 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7706 attrs += build_attr_authenticator(authkey, m3, attrs)
7707 m4 = build_eap_wsc(1, eap_id, attrs)
7708 send_wsc_msg(dev[0], bssid, m4)
7709 eap_id = (eap_id + 1) % 256
7710
7711 logger.debug("Receive M5 (NACK) from STA")
7712 msg = get_wsc_msg(dev[0])
7713 if msg['wsc_opcode'] != WSC_NACK:
7714 raise Exception("Unexpected message - expected WSC_Nack")
7715
7716 dev[0].request("WPS_CANCEL")
7717 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7718 dev[0].wait_disconnected()
7719
7720def test_wps_ext_proto_m4_invalid_pad_string(dev, apdev):
7721 """WPS and invalid pad string in M4"""
7722 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7723
7724 logger.debug("Send M4 to STA")
7725 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7726 attrs += build_attr_msg_type(WPS_M4)
7727 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7728 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7729 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7730 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7731
7732 m = hmac.new(authkey, data, hashlib.sha256)
7733 kwa = m.digest()[0:8]
7734 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
15dfcb69 7735 iv = 16*b'\x99'
7511ead0
JM
7736 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7737 pad_len = 16 - len(data) % 16
7738 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', pad_len - 1)
7739 data += ps
7740 wrapped = aes.encrypt(data)
7741 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7742
7743 attrs += build_attr_authenticator(authkey, m3, attrs)
7744 m4 = build_eap_wsc(1, eap_id, attrs)
7745 send_wsc_msg(dev[0], bssid, m4)
7746 eap_id = (eap_id + 1) % 256
7747
7748 logger.debug("Receive M5 (NACK) from STA")
7749 msg = get_wsc_msg(dev[0])
7750 if msg['wsc_opcode'] != WSC_NACK:
7751 raise Exception("Unexpected message - expected WSC_Nack")
7752
7753 dev[0].request("WPS_CANCEL")
7754 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7755 dev[0].wait_disconnected()
7756
7757def test_wps_ext_proto_m4_invalid_pad_value(dev, apdev):
7758 """WPS and invalid pad value in M4"""
7759 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7760
7761 logger.debug("Send M4 to STA")
7762 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7763 attrs += build_attr_msg_type(WPS_M4)
7764 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7765 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7766 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7767 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7768
7769 m = hmac.new(authkey, data, hashlib.sha256)
7770 kwa = m.digest()[0:8]
7771 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
15dfcb69 7772 iv = 16*b'\x99'
7511ead0
JM
7773 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7774 pad_len = 16 - len(data) % 16
7775 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', 255)
7776 data += ps
7777 wrapped = aes.encrypt(data)
7778 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7779
7780 attrs += build_attr_authenticator(authkey, m3, attrs)
7781 m4 = build_eap_wsc(1, eap_id, attrs)
7782 send_wsc_msg(dev[0], bssid, m4)
7783 eap_id = (eap_id + 1) % 256
7784
7785 logger.debug("Receive M5 (NACK) from STA")
7786 msg = get_wsc_msg(dev[0])
7787 if msg['wsc_opcode'] != WSC_NACK:
7788 raise Exception("Unexpected message - expected WSC_Nack")
7789
7790 dev[0].request("WPS_CANCEL")
7791 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7792 dev[0].wait_disconnected()
7793
7794def test_wps_ext_proto_m4_no_encr_settings(dev, apdev):
7795 """WPS and no Encr Settings in M4"""
7796 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7797
7798 logger.debug("Send M4 to STA")
7799 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7800 attrs += build_attr_msg_type(WPS_M4)
7801 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7802 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7803 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7804 attrs += build_attr_authenticator(authkey, m3, attrs)
7805 m4 = build_eap_wsc(1, eap_id, attrs)
7806 send_wsc_msg(dev[0], bssid, m4)
7807 eap_id = (eap_id + 1) % 256
7808
7809 logger.debug("Receive M5 (NACK) from STA")
7810 msg = get_wsc_msg(dev[0])
7811 if msg['wsc_opcode'] != WSC_NACK:
7812 raise Exception("Unexpected message - expected WSC_Nack")
7813
7814 dev[0].request("WPS_CANCEL")
7815 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7816 dev[0].wait_disconnected()
7817
7818def test_wps_ext_proto_m6_missing_r_snonce2(dev, apdev):
7819 """WPS and no R-SNonce2 in M6"""
7820 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7821
7822 logger.debug("Send M6 to STA")
7823 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7824 attrs += build_attr_msg_type(WPS_M6)
7825 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7826 #data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
15dfcb69 7827 data = b''
7511ead0
JM
7828 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7829 attrs += build_attr_authenticator(authkey, m5, attrs)
7830 m6 = build_eap_wsc(1, eap_id, attrs)
7831 send_wsc_msg(dev[0], bssid, m6)
7832 eap_id = (eap_id + 1) % 256
7833
7834 logger.debug("Receive M7 (NACK) from STA")
7835 msg = get_wsc_msg(dev[0])
7836 if msg['wsc_opcode'] != WSC_NACK:
7837 raise Exception("Unexpected message - expected WSC_Nack")
7838
7839 dev[0].request("WPS_CANCEL")
7840 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7841 dev[0].wait_disconnected()
7842
7843def test_wps_ext_proto_m6_no_encr_settings(dev, apdev):
7844 """WPS and no Encr Settings in M6"""
7845 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7846
7847 logger.debug("Send M6 to STA")
7848 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7849 attrs += build_attr_msg_type(WPS_M6)
7850 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7851 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7852 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7853 attrs += build_attr_authenticator(authkey, m5, attrs)
7854 m6 = build_eap_wsc(1, eap_id, attrs)
7855 send_wsc_msg(dev[0], bssid, m6)
7856 eap_id = (eap_id + 1) % 256
7857
7858 logger.debug("Receive M7 (NACK) from STA")
7859 msg = get_wsc_msg(dev[0])
7860 if msg['wsc_opcode'] != WSC_NACK:
7861 raise Exception("Unexpected message - expected WSC_Nack")
7862
7863 dev[0].request("WPS_CANCEL")
7864 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7865 dev[0].wait_disconnected()
7866
7867def test_wps_ext_proto_m8_no_encr_settings(dev, apdev):
7868 """WPS and no Encr Settings in M6"""
7869 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7870
7871 logger.debug("Send M6 to STA")
7872 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7873 attrs += build_attr_msg_type(WPS_M6)
7874 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7875 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7876 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7877 attrs += build_attr_authenticator(authkey, m5, attrs)
7878 raw_m6_attrs = attrs
7879 m6 = build_eap_wsc(1, eap_id, attrs)
7880 send_wsc_msg(dev[0], bssid, m6)
7881 eap_id = (eap_id + 1) % 256
7882
7883 logger.debug("Receive M7 from STA")
7884 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
7885
7886 logger.debug("Send M8 to STA")
7887 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7888 attrs += build_attr_msg_type(WPS_M8)
7889 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7890 #attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
7891 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7892 raw_m8_attrs = attrs
7893 m8 = build_eap_wsc(1, eap_id, attrs)
7894 send_wsc_msg(dev[0], bssid, m8)
7895
7896 logger.debug("Receive WSC_Done (NACK) from STA")
7897 msg = get_wsc_msg(dev[0])
7898 if msg['wsc_opcode'] != WSC_NACK:
7899 raise Exception("Unexpected message - expected WSC_Nack")
7900
7901 dev[0].request("WPS_CANCEL")
7902 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7903 dev[0].wait_disconnected()
7904
7905def wps_start_ext_reg(apdev, dev):
7906 addr = dev.own_addr()
7907 bssid = apdev['bssid']
7908 ssid = "test-wps-conf"
7909 appin = "12345670"
fab49f61
JM
7910 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
7911 "wpa_passphrase": "12345678", "wpa": "2",
7912 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
7913 "ap_pin": appin}
afc26df2 7914 hapd = hostapd.add_ap(apdev, params)
7511ead0
JM
7915
7916 dev.scan_for_bss(bssid, freq="2412")
7917 hapd.request("SET ext_eapol_frame_io 1")
7918 dev.request("SET ext_eapol_frame_io 1")
7919
7920 dev.request("WPS_REG " + bssid + " " + appin)
7921
fab49f61 7922 return addr, bssid, hapd
7511ead0
JM
7923
7924def wps_run_ap_settings_proto(dev, apdev, ap_settings, success):
fab49f61 7925 addr, bssid, hapd = wps_start_ext_reg(apdev[0], dev[0])
7511ead0
JM
7926 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7927 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7928
7929 logger.debug("Receive M1 from AP")
7930 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7931 mac_addr = m1_attrs[ATTR_MAC_ADDR]
7932 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7933 e_pk = m1_attrs[ATTR_PUBLIC_KEY]
7934
7935 appin = '12345670'
15dfcb69
MH
7936 uuid_r = 16*b'\x33'
7937 r_nonce = 16*b'\x44'
7511ead0 7938 own_private, r_pk = wsc_dh_init()
fab49f61
JM
7939 authkey, keywrapkey = wsc_dh_kdf(e_pk, own_private, mac_addr, e_nonce,
7940 r_nonce)
7941 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, appin, e_pk, r_pk)
7511ead0
JM
7942
7943 logger.debug("Send M2 to AP")
7944 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, msg['eap_identifier'],
7945 e_nonce, r_nonce, uuid_r, r_pk, eap_code=2)
7946 send_wsc_msg(hapd, addr, m2)
7947
7948 logger.debug("Receive M3 from AP")
7949 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M3)
7950
7951 logger.debug("Send M4 to AP")
7952 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7953 attrs += build_attr_msg_type(WPS_M4)
7954 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7955 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7956 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7957 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7958 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7959 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7960 raw_m4_attrs = attrs
7961 m4 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7962 send_wsc_msg(hapd, addr, m4)
7963
7964 logger.debug("Receive M5 from AP")
7965 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M5)
7966
7967 logger.debug("Send M6 to STA")
7968 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7969 attrs += build_attr_msg_type(WPS_M6)
7970 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7971 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7972 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7973 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
7974 raw_m6_attrs = attrs
7975 m6 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7976 send_wsc_msg(hapd, addr, m6)
7977
7978 logger.debug("Receive M7 from AP")
7979 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M7)
7980
7981 logger.debug("Send M8 to STA")
7982 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7983 attrs += build_attr_msg_type(WPS_M8)
7984 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7985 if ap_settings:
7986 attrs += build_attr_encr_settings(authkey, keywrapkey, ap_settings)
7987 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7988 raw_m8_attrs = attrs
7989 m8 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7990 send_wsc_msg(hapd, addr, m8)
7991
7992 if success:
7993 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
7994 if ev is None:
7995 raise Exception("New AP settings not reported")
7996 logger.debug("Receive WSC_Done from AP")
7997 msg = get_wsc_msg(hapd)
7998 if msg['wsc_opcode'] != WSC_Done:
7999 raise Exception("Unexpected message - expected WSC_Done")
8000
8001 logger.debug("Send WSC_ACK to AP")
fab49f61
JM
8002 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8003 eap_code=2)
7511ead0
JM
8004 send_wsc_msg(hapd, addr, ack)
8005 dev[0].wait_disconnected()
8006 else:
8007 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
8008 if ev is None:
8009 raise Exception("WPS failure not reported")
8010 logger.debug("Receive WSC_NACK from AP")
8011 msg = get_wsc_msg(hapd)
8012 if msg['wsc_opcode'] != WSC_NACK:
8013 raise Exception("Unexpected message - expected WSC_NACK")
8014
8015 logger.debug("Send WSC_NACK to AP")
fab49f61
JM
8016 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8017 eap_code=2)
7511ead0
JM
8018 send_wsc_msg(hapd, addr, nack)
8019 dev[0].wait_disconnected()
8020
8021def test_wps_ext_ap_settings_success(dev, apdev):
8022 """WPS and AP Settings: success"""
8023 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
8024 ap_settings += build_wsc_attr(ATTR_SSID, "test")
8025 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
8026 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
8027 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
8028 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
8029 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
8030
9fd6804d 8031@remote_compatible
7511ead0
JM
8032def test_wps_ext_ap_settings_missing(dev, apdev):
8033 """WPS and AP Settings: missing"""
8034 wps_run_ap_settings_proto(dev, apdev, None, False)
8035
9fd6804d 8036@remote_compatible
7511ead0
JM
8037def test_wps_ext_ap_settings_mac_addr_mismatch(dev, apdev):
8038 """WPS and AP Settings: MAC Address mismatch"""
8039 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
8040 ap_settings += build_wsc_attr(ATTR_SSID, "test")
8041 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
8042 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
8043 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
8044 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, '\x00\x00\x00\x00\x00\x00')
8045 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
8046
9fd6804d 8047@remote_compatible
7511ead0
JM
8048def test_wps_ext_ap_settings_mac_addr_missing(dev, apdev):
8049 """WPS and AP Settings: missing MAC Address"""
8050 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
8051 ap_settings += build_wsc_attr(ATTR_SSID, "test")
8052 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
8053 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
8054 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
8055 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
8056
9fd6804d 8057@remote_compatible
7511ead0
JM
8058def test_wps_ext_ap_settings_reject_encr_type(dev, apdev):
8059 """WPS and AP Settings: reject Encr Type"""
8060 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
8061 ap_settings += build_wsc_attr(ATTR_SSID, "test")
8062 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
8063 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x00')
8064 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
8065 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
8066 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
8067
9fd6804d 8068@remote_compatible
7511ead0
JM
8069def test_wps_ext_ap_settings_m2d(dev, apdev):
8070 """WPS and AP Settings: M2D"""
fab49f61 8071 addr, bssid, hapd = wps_start_ext_reg(apdev[0], dev[0])
7511ead0
JM
8072 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8073 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8074
8075 logger.debug("Receive M1 from AP")
8076 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
8077 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
8078
8079 r_nonce = 16*'\x44'
8080 uuid_r = 16*'\x33'
8081
8082 logger.debug("Send M2D to AP")
8083 m2d, raw_m2d_attrs = build_m2d(raw_m1_attrs, msg['eap_identifier'],
8084 e_nonce, r_nonce, uuid_r,
8085 dev_pw_id='\x00\x00', eap_code=2)
8086 send_wsc_msg(hapd, addr, m2d)
8087
8088 ev = hapd.wait_event(["WPS-M2D"], timeout=5)
8089 if ev is None:
8090 raise Exception("M2D not reported")
8091
8092 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8093
8094def wps_wait_ap_nack(hapd, dev, e_nonce, r_nonce):
8095 logger.debug("Receive WSC_NACK from AP")
8096 msg = get_wsc_msg(hapd)
8097 if msg['wsc_opcode'] != WSC_NACK:
8098 raise Exception("Unexpected message - expected WSC_NACK")
8099
8100 logger.debug("Send WSC_NACK to AP")
fab49f61
JM
8101 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8102 eap_code=2)
7511ead0
JM
8103 send_wsc_msg(hapd, dev.own_addr(), nack)
8104 dev.wait_disconnected()
8105
9fd6804d 8106@remote_compatible
7511ead0
JM
8107def test_wps_ext_m3_missing_e_hash1(dev, apdev):
8108 """WPS proto: M3 missing E-Hash1"""
8109 pin = "12345670"
fab49f61 8110 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8111 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8112 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8113
8114 logger.debug("Receive WSC/Start from AP")
8115 msg = get_wsc_msg(hapd)
8116 if msg['wsc_opcode'] != WSC_Start:
8117 raise Exception("Unexpected Op-Code for WSC/Start")
8118
8119 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8120 uuid_e = 16*b'\x11'
8121 e_nonce = 16*b'\x22'
7511ead0
JM
8122 own_private, e_pk = wsc_dh_init()
8123
8124 logger.debug("Send M1 to AP")
8125 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8126 e_nonce, e_pk)
8127 send_wsc_msg(hapd, addr, m1)
8128
8129 logger.debug("Receive M2 from AP")
8130 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8131 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8132 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8133
fab49f61
JM
8134 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8135 r_nonce)
8136 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8137
8138 logger.debug("Send M3 to AP")
8139 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8140 attrs += build_attr_msg_type(WPS_M3)
8141 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8142 #attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8143 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8144 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8145 raw_m3_attrs = attrs
8146 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8147 send_wsc_msg(hapd, addr, m3)
8148
8149 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8150
9fd6804d 8151@remote_compatible
7511ead0
JM
8152def test_wps_ext_m3_missing_e_hash2(dev, apdev):
8153 """WPS proto: M3 missing E-Hash2"""
8154 pin = "12345670"
fab49f61 8155 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8156 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8157 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8158
8159 logger.debug("Receive WSC/Start from AP")
8160 msg = get_wsc_msg(hapd)
8161 if msg['wsc_opcode'] != WSC_Start:
8162 raise Exception("Unexpected Op-Code for WSC/Start")
8163
8164 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8165 uuid_e = 16*b'\x11'
8166 e_nonce = 16*b'\x22'
7511ead0
JM
8167 own_private, e_pk = wsc_dh_init()
8168
8169 logger.debug("Send M1 to AP")
8170 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8171 e_nonce, e_pk)
8172 send_wsc_msg(hapd, addr, m1)
8173
8174 logger.debug("Receive M2 from AP")
8175 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8176 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8177 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8178
fab49f61
JM
8179 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8180 r_nonce)
8181 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8182
8183 logger.debug("Send M3 to AP")
8184 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8185 attrs += build_attr_msg_type(WPS_M3)
8186 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8187 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8188 #attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8189 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8190 raw_m3_attrs = attrs
8191 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8192 send_wsc_msg(hapd, addr, m3)
8193
8194 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8195
9fd6804d 8196@remote_compatible
7511ead0
JM
8197def test_wps_ext_m5_missing_e_snonce1(dev, apdev):
8198 """WPS proto: M5 missing E-SNonce1"""
8199 pin = "12345670"
fab49f61 8200 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8201 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8202 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8203
8204 logger.debug("Receive WSC/Start from AP")
8205 msg = get_wsc_msg(hapd)
8206 if msg['wsc_opcode'] != WSC_Start:
8207 raise Exception("Unexpected Op-Code for WSC/Start")
8208
8209 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8210 uuid_e = 16*b'\x11'
8211 e_nonce = 16*b'\x22'
7511ead0
JM
8212 own_private, e_pk = wsc_dh_init()
8213
8214 logger.debug("Send M1 to AP")
8215 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8216 e_nonce, e_pk)
8217 send_wsc_msg(hapd, addr, m1)
8218
8219 logger.debug("Receive M2 from AP")
8220 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8221 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8222 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8223
fab49f61
JM
8224 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8225 r_nonce)
8226 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8227
8228 logger.debug("Send M3 to AP")
8229 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8230 attrs += build_attr_msg_type(WPS_M3)
8231 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8232 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8233 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8234 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8235 raw_m3_attrs = attrs
8236 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8237 send_wsc_msg(hapd, addr, m3)
8238
8239 logger.debug("Receive M4 from AP")
8240 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8241
8242 logger.debug("Send M5 to AP")
8243 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8244 attrs += build_attr_msg_type(WPS_M5)
8245 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8246 #data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
15dfcb69 8247 data = b''
7511ead0
JM
8248 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8249 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8250 raw_m5_attrs = attrs
8251 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8252 send_wsc_msg(hapd, addr, m5)
8253
8254 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8255
9fd6804d 8256@remote_compatible
7511ead0
JM
8257def test_wps_ext_m5_e_snonce1_mismatch(dev, apdev):
8258 """WPS proto: M5 E-SNonce1 mismatch"""
8259 pin = "12345670"
fab49f61 8260 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8261 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8262 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8263
8264 logger.debug("Receive WSC/Start from AP")
8265 msg = get_wsc_msg(hapd)
8266 if msg['wsc_opcode'] != WSC_Start:
8267 raise Exception("Unexpected Op-Code for WSC/Start")
8268
8269 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8270 uuid_e = 16*b'\x11'
8271 e_nonce = 16*b'\x22'
7511ead0
JM
8272 own_private, e_pk = wsc_dh_init()
8273
8274 logger.debug("Send M1 to AP")
8275 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8276 e_nonce, e_pk)
8277 send_wsc_msg(hapd, addr, m1)
8278
8279 logger.debug("Receive M2 from AP")
8280 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8281 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8282 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8283
fab49f61
JM
8284 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8285 r_nonce)
8286 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8287
8288 logger.debug("Send M3 to AP")
8289 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8290 attrs += build_attr_msg_type(WPS_M3)
8291 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8292 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8293 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8294 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8295 raw_m3_attrs = attrs
8296 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8297 send_wsc_msg(hapd, addr, m3)
8298
8299 logger.debug("Receive M4 from AP")
8300 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8301
8302 logger.debug("Send M5 to AP")
8303 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8304 attrs += build_attr_msg_type(WPS_M5)
8305 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8306 data = build_wsc_attr(ATTR_E_SNONCE1, 16*'\x00')
8307 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8308 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8309 raw_m5_attrs = attrs
8310 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8311 send_wsc_msg(hapd, addr, m5)
8312
8313 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8314
8315def test_wps_ext_m7_missing_e_snonce2(dev, apdev):
8316 """WPS proto: M7 missing E-SNonce2"""
8317 pin = "12345670"
fab49f61 8318 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8319 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8320 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8321
8322 logger.debug("Receive WSC/Start from AP")
8323 msg = get_wsc_msg(hapd)
8324 if msg['wsc_opcode'] != WSC_Start:
8325 raise Exception("Unexpected Op-Code for WSC/Start")
8326
8327 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8328 uuid_e = 16*b'\x11'
8329 e_nonce = 16*b'\x22'
7511ead0
JM
8330 own_private, e_pk = wsc_dh_init()
8331
8332 logger.debug("Send M1 to AP")
8333 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8334 e_nonce, e_pk)
8335 send_wsc_msg(hapd, addr, m1)
8336
8337 logger.debug("Receive M2 from AP")
8338 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8339 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8340 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8341
fab49f61
JM
8342 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8343 r_nonce)
8344 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8345
8346 logger.debug("Send M3 to AP")
8347 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8348 attrs += build_attr_msg_type(WPS_M3)
8349 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8350 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8351 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8352 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8353 raw_m3_attrs = attrs
8354 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8355 send_wsc_msg(hapd, addr, m3)
8356
8357 logger.debug("Receive M4 from AP")
8358 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8359
8360 logger.debug("Send M5 to AP")
8361 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8362 attrs += build_attr_msg_type(WPS_M5)
8363 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8364 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8365 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8366 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8367 raw_m5_attrs = attrs
8368 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8369 send_wsc_msg(hapd, addr, m5)
8370
8371 logger.debug("Receive M6 from AP")
8372 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8373
8374 logger.debug("Send M7 to AP")
8375 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8376 attrs += build_attr_msg_type(WPS_M7)
8377 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8378 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
15dfcb69 8379 data = b''
7511ead0
JM
8380 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8381 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8382 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8383 raw_m7_attrs = attrs
8384 send_wsc_msg(hapd, addr, m7)
8385
8386 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8387
9fd6804d 8388@remote_compatible
7511ead0
JM
8389def test_wps_ext_m7_e_snonce2_mismatch(dev, apdev):
8390 """WPS proto: M7 E-SNonce2 mismatch"""
8391 pin = "12345670"
fab49f61 8392 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8393 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8394 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8395
8396 logger.debug("Receive WSC/Start from AP")
8397 msg = get_wsc_msg(hapd)
8398 if msg['wsc_opcode'] != WSC_Start:
8399 raise Exception("Unexpected Op-Code for WSC/Start")
8400
8401 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8402 uuid_e = 16*b'\x11'
8403 e_nonce = 16*b'\x22'
7511ead0
JM
8404 own_private, e_pk = wsc_dh_init()
8405
8406 logger.debug("Send M1 to AP")
8407 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8408 e_nonce, e_pk)
8409 send_wsc_msg(hapd, addr, m1)
8410
8411 logger.debug("Receive M2 from AP")
8412 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8413 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8414 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8415
fab49f61
JM
8416 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8417 r_nonce)
8418 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8419
8420 logger.debug("Send M3 to AP")
8421 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8422 attrs += build_attr_msg_type(WPS_M3)
8423 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8424 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8425 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8426 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8427 raw_m3_attrs = attrs
8428 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8429 send_wsc_msg(hapd, addr, m3)
8430
8431 logger.debug("Receive M4 from AP")
8432 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8433
8434 logger.debug("Send M5 to AP")
8435 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8436 attrs += build_attr_msg_type(WPS_M5)
8437 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8438 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8439 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8440 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8441 raw_m5_attrs = attrs
8442 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8443 send_wsc_msg(hapd, addr, m5)
8444
8445 logger.debug("Receive M6 from AP")
8446 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8447
8448 logger.debug("Send M7 to AP")
8449 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8450 attrs += build_attr_msg_type(WPS_M7)
8451 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8452 data = build_wsc_attr(ATTR_E_SNONCE2, 16*'\x00')
8453 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8454 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8455 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8456 raw_m7_attrs = attrs
8457 send_wsc_msg(hapd, addr, m7)
8458
8459 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8460
9fd6804d 8461@remote_compatible
7511ead0
JM
8462def test_wps_ext_m1_pubkey_oom(dev, apdev):
8463 """WPS proto: M1 PubKey OOM"""
8464 pin = "12345670"
fab49f61 8465 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8466 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8467 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8468
8469 logger.debug("Receive WSC/Start from AP")
8470 msg = get_wsc_msg(hapd)
8471 if msg['wsc_opcode'] != WSC_Start:
8472 raise Exception("Unexpected Op-Code for WSC/Start")
8473
8474 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8475 uuid_e = 16*'\x11'
8476 e_nonce = 16*'\x22'
8477 own_private, e_pk = wsc_dh_init()
8478
8479 logger.debug("Send M1 to AP")
8480 with alloc_fail(hapd, 1, "wpabuf_alloc_copy;wps_process_pubkey"):
8481 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8482 e_nonce, e_pk)
8483 send_wsc_msg(hapd, addr, m1)
8484 wps_wait_eap_failure(hapd, dev[0])
8485
8486def wps_wait_eap_failure(hapd, dev):
8487 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
8488 if ev is None:
8489 raise Exception("EAP-Failure not reported")
8490 dev.wait_disconnected()
8491
9fd6804d 8492@remote_compatible
7511ead0
JM
8493def test_wps_ext_m3_m1(dev, apdev):
8494 """WPS proto: M3 replaced with M1"""
8495 pin = "12345670"
fab49f61 8496 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8497 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8498 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8499
8500 logger.debug("Receive WSC/Start from AP")
8501 msg = get_wsc_msg(hapd)
8502 if msg['wsc_opcode'] != WSC_Start:
8503 raise Exception("Unexpected Op-Code for WSC/Start")
8504
8505 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8506 uuid_e = 16*b'\x11'
8507 e_nonce = 16*b'\x22'
7511ead0
JM
8508 own_private, e_pk = wsc_dh_init()
8509
8510 logger.debug("Send M1 to AP")
8511 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8512 e_nonce, e_pk)
8513 send_wsc_msg(hapd, addr, m1)
8514
8515 logger.debug("Receive M2 from AP")
8516 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8517 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8518 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8519
fab49f61
JM
8520 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8521 r_nonce)
8522 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8523
8524 logger.debug("Send M3(M1) to AP")
8525 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8526 attrs += build_attr_msg_type(WPS_M1)
8527 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8528 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8529 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8530 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8531 raw_m3_attrs = attrs
8532 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8533 send_wsc_msg(hapd, addr, m3)
8534
8535 wps_wait_eap_failure(hapd, dev[0])
8536
9fd6804d 8537@remote_compatible
7511ead0
JM
8538def test_wps_ext_m5_m3(dev, apdev):
8539 """WPS proto: M5 replaced with M3"""
8540 pin = "12345670"
fab49f61 8541 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8542 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8543 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8544
8545 logger.debug("Receive WSC/Start from AP")
8546 msg = get_wsc_msg(hapd)
8547 if msg['wsc_opcode'] != WSC_Start:
8548 raise Exception("Unexpected Op-Code for WSC/Start")
8549
8550 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8551 uuid_e = 16*b'\x11'
8552 e_nonce = 16*b'\x22'
7511ead0
JM
8553 own_private, e_pk = wsc_dh_init()
8554
8555 logger.debug("Send M1 to AP")
8556 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8557 e_nonce, e_pk)
8558 send_wsc_msg(hapd, addr, m1)
8559
8560 logger.debug("Receive M2 from AP")
8561 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8562 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8563 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8564
fab49f61
JM
8565 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8566 r_nonce)
8567 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8568
8569 logger.debug("Send M3 to AP")
8570 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8571 attrs += build_attr_msg_type(WPS_M3)
8572 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8573 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8574 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8575 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8576 raw_m3_attrs = attrs
8577 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8578 send_wsc_msg(hapd, addr, m3)
8579
8580 logger.debug("Receive M4 from AP")
8581 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8582
8583 logger.debug("Send M5(M3) to AP")
8584 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8585 attrs += build_attr_msg_type(WPS_M3)
8586 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8587 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8588 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8589 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8590 raw_m5_attrs = attrs
8591 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8592 send_wsc_msg(hapd, addr, m5)
8593
8594 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8595
9fd6804d 8596@remote_compatible
7511ead0
JM
8597def test_wps_ext_m3_m2(dev, apdev):
8598 """WPS proto: M3 replaced with M2"""
8599 pin = "12345670"
fab49f61 8600 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8601 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8602 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8603
8604 logger.debug("Receive WSC/Start from AP")
8605 msg = get_wsc_msg(hapd)
8606 if msg['wsc_opcode'] != WSC_Start:
8607 raise Exception("Unexpected Op-Code for WSC/Start")
8608
8609 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8610 uuid_e = 16*b'\x11'
8611 e_nonce = 16*b'\x22'
7511ead0
JM
8612 own_private, e_pk = wsc_dh_init()
8613
8614 logger.debug("Send M1 to AP")
8615 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8616 e_nonce, e_pk)
8617 send_wsc_msg(hapd, addr, m1)
8618
8619 logger.debug("Receive M2 from AP")
8620 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8621 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8622 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8623
fab49f61
JM
8624 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8625 r_nonce)
8626 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8627
8628 logger.debug("Send M3(M2) to AP")
8629 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8630 attrs += build_attr_msg_type(WPS_M2)
8631 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8632 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8633 raw_m3_attrs = attrs
8634 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8635 send_wsc_msg(hapd, addr, m3)
8636
8637 wps_wait_eap_failure(hapd, dev[0])
8638
9fd6804d 8639@remote_compatible
7511ead0
JM
8640def test_wps_ext_m3_m5(dev, apdev):
8641 """WPS proto: M3 replaced with M5"""
8642 pin = "12345670"
fab49f61 8643 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8644 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8645 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8646
8647 logger.debug("Receive WSC/Start from AP")
8648 msg = get_wsc_msg(hapd)
8649 if msg['wsc_opcode'] != WSC_Start:
8650 raise Exception("Unexpected Op-Code for WSC/Start")
8651
8652 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8653 uuid_e = 16*b'\x11'
8654 e_nonce = 16*b'\x22'
7511ead0
JM
8655 own_private, e_pk = wsc_dh_init()
8656
8657 logger.debug("Send M1 to AP")
8658 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8659 e_nonce, e_pk)
8660 send_wsc_msg(hapd, addr, m1)
8661
8662 logger.debug("Receive M2 from AP")
8663 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8664 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8665 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8666
fab49f61
JM
8667 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8668 r_nonce)
8669 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8670
8671 logger.debug("Send M3(M5) to AP")
8672 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8673 attrs += build_attr_msg_type(WPS_M5)
8674 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8675 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8676 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8677 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8678 raw_m3_attrs = attrs
8679 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8680 send_wsc_msg(hapd, addr, m3)
8681
8682 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8683
9fd6804d 8684@remote_compatible
7511ead0
JM
8685def test_wps_ext_m3_m7(dev, apdev):
8686 """WPS proto: M3 replaced with M7"""
8687 pin = "12345670"
fab49f61 8688 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8689 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8690 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8691
8692 logger.debug("Receive WSC/Start from AP")
8693 msg = get_wsc_msg(hapd)
8694 if msg['wsc_opcode'] != WSC_Start:
8695 raise Exception("Unexpected Op-Code for WSC/Start")
8696
8697 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8698 uuid_e = 16*b'\x11'
8699 e_nonce = 16*b'\x22'
7511ead0
JM
8700 own_private, e_pk = wsc_dh_init()
8701
8702 logger.debug("Send M1 to AP")
8703 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8704 e_nonce, e_pk)
8705 send_wsc_msg(hapd, addr, m1)
8706
8707 logger.debug("Receive M2 from AP")
8708 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8709 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8710 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8711
fab49f61
JM
8712 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8713 r_nonce)
8714 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8715
8716 logger.debug("Send M3(M7) to AP")
8717 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8718 attrs += build_attr_msg_type(WPS_M7)
8719 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8720 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8721 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8722 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8723 raw_m3_attrs = attrs
8724 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8725 send_wsc_msg(hapd, addr, m3)
8726
8727 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8728
9fd6804d 8729@remote_compatible
7511ead0
JM
8730def test_wps_ext_m3_done(dev, apdev):
8731 """WPS proto: M3 replaced with WSC_Done"""
8732 pin = "12345670"
fab49f61 8733 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8734 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8735 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8736
8737 logger.debug("Receive WSC/Start from AP")
8738 msg = get_wsc_msg(hapd)
8739 if msg['wsc_opcode'] != WSC_Start:
8740 raise Exception("Unexpected Op-Code for WSC/Start")
8741
8742 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8743 uuid_e = 16*b'\x11'
8744 e_nonce = 16*b'\x22'
7511ead0
JM
8745 own_private, e_pk = wsc_dh_init()
8746
8747 logger.debug("Send M1 to AP")
8748 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8749 e_nonce, e_pk)
8750 send_wsc_msg(hapd, addr, m1)
8751
8752 logger.debug("Receive M2 from AP")
8753 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8754 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8755 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8756
fab49f61
JM
8757 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8758 r_nonce)
8759 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8760
8761 logger.debug("Send M3(WSC_Done) to AP")
8762 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8763 attrs += build_attr_msg_type(WPS_WSC_DONE)
8764 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8765 raw_m3_attrs = attrs
8766 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8767 send_wsc_msg(hapd, addr, m3)
8768
8769 wps_wait_eap_failure(hapd, dev[0])
8770
9fd6804d 8771@remote_compatible
7511ead0
JM
8772def test_wps_ext_m2_nack_invalid(dev, apdev):
8773 """WPS proto: M2 followed by invalid NACK"""
8774 pin = "12345670"
fab49f61 8775 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8776 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8777 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8778
8779 logger.debug("Receive WSC/Start from AP")
8780 msg = get_wsc_msg(hapd)
8781 if msg['wsc_opcode'] != WSC_Start:
8782 raise Exception("Unexpected Op-Code for WSC/Start")
8783
8784 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8785 uuid_e = 16*b'\x11'
8786 e_nonce = 16*b'\x22'
7511ead0
JM
8787 own_private, e_pk = wsc_dh_init()
8788
8789 logger.debug("Send M1 to AP")
8790 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8791 e_nonce, e_pk)
8792 send_wsc_msg(hapd, addr, m1)
8793
8794 logger.debug("Receive M2 from AP")
8795 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8796 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8797 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8798
fab49f61
JM
8799 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8800 r_nonce)
8801 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8802
8803 logger.debug("Send WSC_NACK to AP")
15dfcb69 8804 attrs = b'\x10\x00\x00'
7511ead0
JM
8805 nack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_NACK)
8806 send_wsc_msg(hapd, addr, nack)
8807
8808 wps_wait_eap_failure(hapd, dev[0])
8809
9fd6804d 8810@remote_compatible
7511ead0
JM
8811def test_wps_ext_m2_nack_no_msg_type(dev, apdev):
8812 """WPS proto: M2 followed by NACK without Msg Type"""
8813 pin = "12345670"
fab49f61 8814 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8815 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8816 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8817
8818 logger.debug("Receive WSC/Start from AP")
8819 msg = get_wsc_msg(hapd)
8820 if msg['wsc_opcode'] != WSC_Start:
8821 raise Exception("Unexpected Op-Code for WSC/Start")
8822
8823 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8824 uuid_e = 16*b'\x11'
8825 e_nonce = 16*b'\x22'
7511ead0
JM
8826 own_private, e_pk = wsc_dh_init()
8827
8828 logger.debug("Send M1 to AP")
8829 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8830 e_nonce, e_pk)
8831 send_wsc_msg(hapd, addr, m1)
8832
8833 logger.debug("Receive M2 from AP")
8834 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8835 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8836 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8837
fab49f61
JM
8838 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8839 r_nonce)
8840 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8841
8842 logger.debug("Send WSC_NACK to AP")
fab49f61
JM
8843 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8844 msg_type=None, eap_code=2)
7511ead0
JM
8845 send_wsc_msg(hapd, addr, nack)
8846
8847 wps_wait_eap_failure(hapd, dev[0])
8848
9fd6804d 8849@remote_compatible
7511ead0
JM
8850def test_wps_ext_m2_nack_invalid_msg_type(dev, apdev):
8851 """WPS proto: M2 followed by NACK with invalid Msg Type"""
8852 pin = "12345670"
fab49f61 8853 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8854 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8855 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8856
8857 logger.debug("Receive WSC/Start from AP")
8858 msg = get_wsc_msg(hapd)
8859 if msg['wsc_opcode'] != WSC_Start:
8860 raise Exception("Unexpected Op-Code for WSC/Start")
8861
8862 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8863 uuid_e = 16*b'\x11'
8864 e_nonce = 16*b'\x22'
7511ead0
JM
8865 own_private, e_pk = wsc_dh_init()
8866
8867 logger.debug("Send M1 to AP")
8868 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8869 e_nonce, e_pk)
8870 send_wsc_msg(hapd, addr, m1)
8871
8872 logger.debug("Receive M2 from AP")
8873 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8874 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8875 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8876
fab49f61
JM
8877 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8878 r_nonce)
8879 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8880
8881 logger.debug("Send WSC_NACK to AP")
fab49f61
JM
8882 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8883 msg_type=WPS_WSC_ACK, eap_code=2)
7511ead0
JM
8884 send_wsc_msg(hapd, addr, nack)
8885
8886 wps_wait_eap_failure(hapd, dev[0])
8887
9fd6804d 8888@remote_compatible
7511ead0
JM
8889def test_wps_ext_m2_nack_e_nonce_mismatch(dev, apdev):
8890 """WPS proto: M2 followed by NACK with e-nonce mismatch"""
8891 pin = "12345670"
fab49f61 8892 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8893 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8894 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8895
8896 logger.debug("Receive WSC/Start from AP")
8897 msg = get_wsc_msg(hapd)
8898 if msg['wsc_opcode'] != WSC_Start:
8899 raise Exception("Unexpected Op-Code for WSC/Start")
8900
8901 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8902 uuid_e = 16*b'\x11'
8903 e_nonce = 16*b'\x22'
7511ead0
JM
8904 own_private, e_pk = wsc_dh_init()
8905
8906 logger.debug("Send M1 to AP")
8907 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8908 e_nonce, e_pk)
8909 send_wsc_msg(hapd, addr, m1)
8910
8911 logger.debug("Receive M2 from AP")
8912 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8913 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8914 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8915
fab49f61
JM
8916 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8917 r_nonce)
8918 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8919
8920 logger.debug("Send WSC_NACK to AP")
fab49f61
JM
8921 nack, attrs = build_nack(msg['eap_identifier'], 16*b'\x00', r_nonce,
8922 eap_code=2)
7511ead0
JM
8923 send_wsc_msg(hapd, addr, nack)
8924
8925 wps_wait_eap_failure(hapd, dev[0])
8926
9fd6804d 8927@remote_compatible
7511ead0
JM
8928def test_wps_ext_m2_nack_no_config_error(dev, apdev):
8929 """WPS proto: M2 followed by NACK without Config Error"""
8930 pin = "12345670"
fab49f61 8931 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8932 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8933 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8934
8935 logger.debug("Receive WSC/Start from AP")
8936 msg = get_wsc_msg(hapd)
8937 if msg['wsc_opcode'] != WSC_Start:
8938 raise Exception("Unexpected Op-Code for WSC/Start")
8939
8940 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8941 uuid_e = 16*b'\x11'
8942 e_nonce = 16*b'\x22'
7511ead0
JM
8943 own_private, e_pk = wsc_dh_init()
8944
8945 logger.debug("Send M1 to AP")
8946 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8947 e_nonce, e_pk)
8948 send_wsc_msg(hapd, addr, m1)
8949
8950 logger.debug("Receive M2 from AP")
8951 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8952 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8953 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8954
fab49f61
JM
8955 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8956 r_nonce)
8957 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8958
8959 logger.debug("Send WSC_NACK to AP")
fab49f61
JM
8960 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8961 config_error=None, eap_code=2)
7511ead0
JM
8962 send_wsc_msg(hapd, addr, nack)
8963
8964 wps_wait_eap_failure(hapd, dev[0])
8965
9fd6804d 8966@remote_compatible
7511ead0
JM
8967def test_wps_ext_m2_ack_invalid(dev, apdev):
8968 """WPS proto: M2 followed by invalid ACK"""
8969 pin = "12345670"
fab49f61 8970 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8971 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8972 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8973
8974 logger.debug("Receive WSC/Start from AP")
8975 msg = get_wsc_msg(hapd)
8976 if msg['wsc_opcode'] != WSC_Start:
8977 raise Exception("Unexpected Op-Code for WSC/Start")
8978
8979 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8980 uuid_e = 16*b'\x11'
8981 e_nonce = 16*b'\x22'
7511ead0
JM
8982 own_private, e_pk = wsc_dh_init()
8983
8984 logger.debug("Send M1 to AP")
8985 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8986 e_nonce, e_pk)
8987 send_wsc_msg(hapd, addr, m1)
8988
8989 logger.debug("Receive M2 from AP")
8990 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8991 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8992 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8993
fab49f61
JM
8994 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8995 r_nonce)
8996 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8997
8998 logger.debug("Send WSC_ACK to AP")
15dfcb69 8999 attrs = b'\x10\x00\x00'
7511ead0
JM
9000 ack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_ACK)
9001 send_wsc_msg(hapd, addr, ack)
9002
9003 wps_wait_eap_failure(hapd, dev[0])
9004
9fd6804d 9005@remote_compatible
7511ead0
JM
9006def test_wps_ext_m2_ack(dev, apdev):
9007 """WPS proto: M2 followed by ACK"""
9008 pin = "12345670"
fab49f61 9009 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
9010 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9011 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9012
9013 logger.debug("Receive WSC/Start from AP")
9014 msg = get_wsc_msg(hapd)
9015 if msg['wsc_opcode'] != WSC_Start:
9016 raise Exception("Unexpected Op-Code for WSC/Start")
9017
9018 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
9019 uuid_e = 16*b'\x11'
9020 e_nonce = 16*b'\x22'
7511ead0
JM
9021 own_private, e_pk = wsc_dh_init()
9022
9023 logger.debug("Send M1 to AP")
9024 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9025 e_nonce, e_pk)
9026 send_wsc_msg(hapd, addr, m1)
9027
9028 logger.debug("Receive M2 from AP")
9029 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9030 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9031 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9032
fab49f61
JM
9033 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9034 r_nonce)
9035 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
9036
9037 logger.debug("Send WSC_ACK to AP")
fab49f61 9038 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce, eap_code=2)
7511ead0
JM
9039 send_wsc_msg(hapd, addr, ack)
9040
9041 wps_wait_eap_failure(hapd, dev[0])
9042
9fd6804d 9043@remote_compatible
7511ead0
JM
9044def test_wps_ext_m2_ack_no_msg_type(dev, apdev):
9045 """WPS proto: M2 followed by ACK missing Msg Type"""
9046 pin = "12345670"
fab49f61 9047 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
9048 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9049 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9050
9051 logger.debug("Receive WSC/Start from AP")
9052 msg = get_wsc_msg(hapd)
9053 if msg['wsc_opcode'] != WSC_Start:
9054 raise Exception("Unexpected Op-Code for WSC/Start")
9055
9056 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
9057 uuid_e = 16*b'\x11'
9058 e_nonce = 16*b'\x22'
7511ead0
JM
9059 own_private, e_pk = wsc_dh_init()
9060
9061 logger.debug("Send M1 to AP")
9062 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9063 e_nonce, e_pk)
9064 send_wsc_msg(hapd, addr, m1)
9065
9066 logger.debug("Receive M2 from AP")
9067 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9068 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9069 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9070
fab49f61
JM
9071 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9072 r_nonce)
9073 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
9074
9075 logger.debug("Send WSC_ACK to AP")
fab49f61
JM
9076 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
9077 msg_type=None, eap_code=2)
7511ead0
JM
9078 send_wsc_msg(hapd, addr, ack)
9079
9080 wps_wait_eap_failure(hapd, dev[0])
9081
9fd6804d 9082@remote_compatible
7511ead0
JM
9083def test_wps_ext_m2_ack_invalid_msg_type(dev, apdev):
9084 """WPS proto: M2 followed by ACK with invalid Msg Type"""
9085 pin = "12345670"
fab49f61 9086 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
9087 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9088 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9089
9090 logger.debug("Receive WSC/Start from AP")
9091 msg = get_wsc_msg(hapd)
9092 if msg['wsc_opcode'] != WSC_Start:
9093 raise Exception("Unexpected Op-Code for WSC/Start")
9094
9095 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
9096 uuid_e = 16*b'\x11'
9097 e_nonce = 16*b'\x22'
7511ead0
JM
9098 own_private, e_pk = wsc_dh_init()
9099
9100 logger.debug("Send M1 to AP")
9101 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9102 e_nonce, e_pk)
9103 send_wsc_msg(hapd, addr, m1)
9104
9105 logger.debug("Receive M2 from AP")
9106 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9107 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9108 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9109
fab49f61
JM
9110 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9111 r_nonce)
9112 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
9113
9114 logger.debug("Send WSC_ACK to AP")
fab49f61 9115 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
7511ead0
JM
9116 msg_type=WPS_WSC_NACK, eap_code=2)
9117 send_wsc_msg(hapd, addr, ack)
9118
9119 wps_wait_eap_failure(hapd, dev[0])
9120
9fd6804d 9121@remote_compatible
7511ead0
JM
9122def test_wps_ext_m2_ack_e_nonce_mismatch(dev, apdev):
9123 """WPS proto: M2 followed by ACK with e-nonce mismatch"""
9124 pin = "12345670"
fab49f61 9125 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
9126 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9127 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9128
9129 logger.debug("Receive WSC/Start from AP")
9130 msg = get_wsc_msg(hapd)
9131 if msg['wsc_opcode'] != WSC_Start:
9132 raise Exception("Unexpected Op-Code for WSC/Start")
9133
9134 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
9135 uuid_e = 16*b'\x11'
9136 e_nonce = 16*b'\x22'
7511ead0
JM
9137 own_private, e_pk = wsc_dh_init()
9138
9139 logger.debug("Send M1 to AP")
9140 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9141 e_nonce, e_pk)
9142 send_wsc_msg(hapd, addr, m1)
9143
9144 logger.debug("Receive M2 from AP")
9145 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9146 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9147 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9148
fab49f61
JM
9149 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9150 r_nonce)
9151 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
9152
9153 logger.debug("Send WSC_ACK to AP")
fab49f61
JM
9154 ack, attrs = build_ack(msg['eap_identifier'], 16*b'\x00', r_nonce,
9155 eap_code=2)
7511ead0
JM
9156 send_wsc_msg(hapd, addr, ack)
9157
9158 wps_wait_eap_failure(hapd, dev[0])
9159
9fd6804d 9160@remote_compatible
7511ead0
JM
9161def test_wps_ext_m1_invalid(dev, apdev):
9162 """WPS proto: M1 failing parsing"""
9163 pin = "12345670"
fab49f61 9164 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
9165 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9166 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9167
9168 logger.debug("Receive WSC/Start from AP")
9169 msg = get_wsc_msg(hapd)
9170 if msg['wsc_opcode'] != WSC_Start:
9171 raise Exception("Unexpected Op-Code for WSC/Start")
9172
9173 logger.debug("Send M1 to AP")
15dfcb69 9174 attrs = b'\x10\x00\x00'
7511ead0
JM
9175 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9176 send_wsc_msg(hapd, addr, m1)
9177
9178 wps_wait_eap_failure(hapd, dev[0])
9179
9180def test_wps_ext_m1_missing_msg_type(dev, apdev):
9181 """WPS proto: M1 missing Msg Type"""
9182 pin = "12345670"
fab49f61 9183 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
9184 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9185 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9186
9187 logger.debug("Receive WSC/Start from AP")
9188 msg = get_wsc_msg(hapd)
9189 if msg['wsc_opcode'] != WSC_Start:
9190 raise Exception("Unexpected Op-Code for WSC/Start")
9191
9192 logger.debug("Send M1 to AP")
9193 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9194 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9195 send_wsc_msg(hapd, addr, m1)
9196
15dfcb69 9197 wps_wait_ap_nack(hapd, dev[0], 16*b'\x00', 16*b'\x00')
7511ead0
JM
9198
9199def wps_ext_wsc_done(dev, apdev):
9200 pin = "12345670"
fab49f61 9201 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
9202 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9203 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9204
9205 logger.debug("Receive WSC/Start from AP")
9206 msg = get_wsc_msg(hapd)
9207 if msg['wsc_opcode'] != WSC_Start:
9208 raise Exception("Unexpected Op-Code for WSC/Start")
9209
9210 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
9211 uuid_e = 16*b'\x11'
9212 e_nonce = 16*b'\x22'
7511ead0
JM
9213 own_private, e_pk = wsc_dh_init()
9214
9215 logger.debug("Send M1 to AP")
9216 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9217 e_nonce, e_pk)
9218 send_wsc_msg(hapd, addr, m1)
9219
9220 logger.debug("Receive M2 from AP")
9221 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9222 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9223 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9224
fab49f61
JM
9225 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9226 r_nonce)
9227 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
9228
9229 logger.debug("Send M3 to AP")
9230 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9231 attrs += build_attr_msg_type(WPS_M3)
9232 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9233 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9234 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9235 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9236 raw_m3_attrs = attrs
9237 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9238 send_wsc_msg(hapd, addr, m3)
9239
9240 logger.debug("Receive M4 from AP")
9241 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9242
9243 logger.debug("Send M5 to AP")
9244 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9245 attrs += build_attr_msg_type(WPS_M5)
9246 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9247 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9248 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9249 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9250 raw_m5_attrs = attrs
9251 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9252 send_wsc_msg(hapd, addr, m5)
9253
9254 logger.debug("Receive M6 from AP")
9255 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9256
9257 logger.debug("Send M7 to AP")
9258 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9259 attrs += build_attr_msg_type(WPS_M7)
9260 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9261 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9262 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9263 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9264 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9265 raw_m7_attrs = attrs
9266 send_wsc_msg(hapd, addr, m7)
9267
9268 logger.debug("Receive M8 from AP")
9269 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
9270 return hapd, msg, e_nonce, r_nonce
9271
9fd6804d 9272@remote_compatible
7511ead0
JM
9273def test_wps_ext_wsc_done_invalid(dev, apdev):
9274 """WPS proto: invalid WSC_Done"""
9275 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9276
9277 logger.debug("Send WSC_Done to AP")
15dfcb69 9278 attrs = b'\x10\x00\x00'
7511ead0
JM
9279 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9280 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9281
9282 wps_wait_eap_failure(hapd, dev[0])
9283
9fd6804d 9284@remote_compatible
7511ead0
JM
9285def test_wps_ext_wsc_done_no_msg_type(dev, apdev):
9286 """WPS proto: invalid WSC_Done"""
9287 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9288
9289 logger.debug("Send WSC_Done to AP")
9290 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9291 #attrs += build_attr_msg_type(WPS_WSC_DONE)
9292 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9293 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9294 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9295 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9296
9297 wps_wait_eap_failure(hapd, dev[0])
9298
9fd6804d 9299@remote_compatible
7511ead0
JM
9300def test_wps_ext_wsc_done_wrong_msg_type(dev, apdev):
9301 """WPS proto: WSC_Done with wrong Msg Type"""
9302 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9303
9304 logger.debug("Send WSC_Done to AP")
9305 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9306 attrs += build_attr_msg_type(WPS_WSC_ACK)
9307 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9308 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9309 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9310 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9311
9312 wps_wait_eap_failure(hapd, dev[0])
9313
9fd6804d 9314@remote_compatible
7511ead0
JM
9315def test_wps_ext_wsc_done_no_e_nonce(dev, apdev):
9316 """WPS proto: WSC_Done without e_nonce"""
9317 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9318
9319 logger.debug("Send WSC_Done to AP")
9320 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9321 attrs += build_attr_msg_type(WPS_WSC_DONE)
9322 #attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9323 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9324 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9325 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9326
9327 wps_wait_eap_failure(hapd, dev[0])
9328
9329def test_wps_ext_wsc_done_no_r_nonce(dev, apdev):
9330 """WPS proto: WSC_Done without r_nonce"""
9331 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9332
9333 logger.debug("Send WSC_Done to AP")
9334 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9335 attrs += build_attr_msg_type(WPS_WSC_DONE)
9336 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9337 #attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9338 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9339 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9340
9341 wps_wait_eap_failure(hapd, dev[0])
9342
9fd6804d 9343@remote_compatible
7511ead0
JM
9344def test_wps_ext_m7_no_encr_settings(dev, apdev):
9345 """WPS proto: M7 without Encr Settings"""
9346 pin = "12345670"
fab49f61 9347 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
9348 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9349 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9350
9351 logger.debug("Receive WSC/Start from AP")
9352 msg = get_wsc_msg(hapd)
9353 if msg['wsc_opcode'] != WSC_Start:
9354 raise Exception("Unexpected Op-Code for WSC/Start")
9355
9356 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
9357 uuid_e = 16*b'\x11'
9358 e_nonce = 16*b'\x22'
7511ead0
JM
9359 own_private, e_pk = wsc_dh_init()
9360
9361 logger.debug("Send M1 to AP")
9362 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9363 e_nonce, e_pk)
9364 send_wsc_msg(hapd, addr, m1)
9365
9366 logger.debug("Receive M2 from AP")
9367 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9368 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9369 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9370
fab49f61
JM
9371 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9372 r_nonce)
9373 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
9374
9375 logger.debug("Send M3 to AP")
9376 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9377 attrs += build_attr_msg_type(WPS_M3)
9378 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9379 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9380 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9381 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9382 raw_m3_attrs = attrs
9383 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9384 send_wsc_msg(hapd, addr, m3)
9385
9386 logger.debug("Receive M4 from AP")
9387 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9388
9389 logger.debug("Send M5 to AP")
9390 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9391 attrs += build_attr_msg_type(WPS_M5)
9392 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9393 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9394 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9395 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9396 raw_m5_attrs = attrs
9397 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9398 send_wsc_msg(hapd, addr, m5)
9399
9400 logger.debug("Receive M6 from AP")
9401 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9402
9403 logger.debug("Send M7 to AP")
9404 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9405 attrs += build_attr_msg_type(WPS_M7)
9406 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9407 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9408 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9409 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9410 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9411 raw_m7_attrs = attrs
9412 send_wsc_msg(hapd, addr, m7)
9413
9414 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
9415
9fd6804d 9416@remote_compatible
7511ead0
JM
9417def test_wps_ext_m1_workaround(dev, apdev):
9418 """WPS proto: M1 Manufacturer/Model workaround"""
9419 pin = "12345670"
fab49f61 9420 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
9421 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9422 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9423
9424 logger.debug("Receive WSC/Start from AP")
9425 msg = get_wsc_msg(hapd)
9426 if msg['wsc_opcode'] != WSC_Start:
9427 raise Exception("Unexpected Op-Code for WSC/Start")
9428
9429 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
9430 uuid_e = 16*b'\x11'
9431 e_nonce = 16*b'\x22'
7511ead0
JM
9432 own_private, e_pk = wsc_dh_init()
9433
9434 logger.debug("Send M1 to AP")
9435 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9436 e_nonce, e_pk, manufacturer='Apple TEST',
15dfcb69 9437 model_name='AirPort', config_methods=b'\xff\xff')
7511ead0
JM
9438 send_wsc_msg(hapd, addr, m1)
9439
9440 logger.debug("Receive M2 from AP")
9441 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
53bd8653 9442
9fd6804d 9443@remote_compatible
53bd8653
JM
9444def test_ap_wps_disable_enable(dev, apdev):
9445 """WPS and DISABLE/ENABLE AP"""
9446 hapd = wps_start_ap(apdev[0])
9447 hapd.disable()
9448 hapd.enable()
9449 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
dd124ee8
JM
9450
9451def test_ap_wps_upnp_web_oom(dev, apdev, params):
9452 """hostapd WPS UPnP web OOM"""
9453 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 9454 hapd = add_ssdp_ap(apdev[0], ap_uuid)
dd124ee8
JM
9455
9456 location = ssdp_get_location(ap_uuid)
9c06eda0 9457 url = urlparse(location)
dd124ee8 9458 urls = upnp_get_urls(location)
9c06eda0
MH
9459 eventurl = urlparse(urls['event_sub_url'])
9460 ctrlurl = urlparse(urls['control_url'])
dd124ee8 9461
9c06eda0 9462 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9463 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9464 conn.request("GET", "/wps_device.xml")
9465 try:
9466 resp = conn.getresponse()
9467 except:
9468 pass
9469
9c06eda0 9470 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9471 conn.request("GET", "/unknown")
9472 resp = conn.getresponse()
9473 if resp.status != 404:
9474 raise Exception("Unexpected HTTP result for unknown URL: %d" + resp.status)
9475
9476 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9477 conn.request("GET", "/unknown")
9478 try:
9479 resp = conn.getresponse()
89896c00 9480 print(resp.status)
dd124ee8
JM
9481 except:
9482 pass
9483
9c06eda0 9484 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9485 conn.request("GET", "/wps_device.xml")
9486 resp = conn.getresponse()
9487 if resp.status != 200:
9488 raise Exception("GET /wps_device.xml failed")
9489
9c06eda0 9490 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9491 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9492 if resp.status != 200:
9493 raise Exception("GetDeviceInfo failed")
9494
9495 with alloc_fail(hapd, 1, "web_process_get_device_info"):
9c06eda0 9496 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9497 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9498 if resp.status != 500:
9499 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9500
9501 with alloc_fail(hapd, 1, "wps_build_m1;web_process_get_device_info"):
9c06eda0 9502 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9503 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9504 if resp.status != 500:
9505 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9506
9507 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_send_reply"):
9c06eda0 9508 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9509 try:
9510 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9511 except:
9512 pass
9513
9c06eda0 9514 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9515 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9516 if resp.status != 200:
9517 raise Exception("GetDeviceInfo failed")
9518
9519 # No NewWLANEventType in PutWLANResponse NewMessage
9c06eda0 9520 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9521 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse", newmsg="foo")
9522 if resp.status != 600:
9523 raise Exception("Unexpected HTTP response: %d" % resp.status)
9524
9525 # No NewWLANEventMAC in PutWLANResponse NewMessage
9c06eda0 9526 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9527 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9528 newmsg="foo", neweventtype="1")
9529 if resp.status != 600:
9530 raise Exception("Unexpected HTTP response: %d" % resp.status)
9531
9532 # Invalid NewWLANEventMAC in PutWLANResponse NewMessage
9c06eda0 9533 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9534 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9535 newmsg="foo", neweventtype="1",
9536 neweventmac="foo")
9537 if resp.status != 600:
9538 raise Exception("Unexpected HTTP response: %d" % resp.status)
9539
9540 # Workaround for NewWLANEventMAC in PutWLANResponse NewMessage
9541 # Ignored unexpected PutWLANResponse WLANEventType 1
9c06eda0 9542 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9543 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9544 newmsg="foo", neweventtype="1",
9545 neweventmac="00.11.22.33.44.55")
9546 if resp.status != 500:
9547 raise Exception("Unexpected HTTP response: %d" % resp.status)
9548
9549 # PutWLANResponse NewMessage with invalid EAP message
9c06eda0 9550 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9551 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9552 newmsg="foo", neweventtype="2",
9553 neweventmac="00:11:22:33:44:55")
9554 if resp.status != 200:
9555 raise Exception("Unexpected HTTP response: %d" % resp.status)
9556
9557 with alloc_fail(hapd, 1, "web_connection_parse_subscribe"):
9c06eda0 9558 conn = HTTPConnection(url.netloc)
fab49f61
JM
9559 headers = {"callback": '<http://127.0.0.1:12345/event>',
9560 "NT": "upnp:event",
9561 "timeout": "Second-1234"}
dd124ee8
JM
9562 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9563 try:
9564 resp = conn.getresponse()
9565 except:
9566 pass
9567
9568 with alloc_fail(hapd, 1, "dup_binstr;web_connection_parse_subscribe"):
9c06eda0 9569 conn = HTTPConnection(url.netloc)
fab49f61
JM
9570 headers = {"callback": '<http://127.0.0.1:12345/event>',
9571 "NT": "upnp:event",
9572 "timeout": "Second-1234"}
dd124ee8
JM
9573 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9574 resp = conn.getresponse()
9575 if resp.status != 500:
9576 raise Exception("Unexpected HTTP response: %d" % resp.status)
9577
9578 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_parse_unsubscribe"):
9c06eda0 9579 conn = HTTPConnection(url.netloc)
fab49f61
JM
9580 headers = {"callback": '<http://127.0.0.1:12345/event>',
9581 "NT": "upnp:event",
9582 "timeout": "Second-1234"}
dd124ee8
JM
9583 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9584 try:
9585 resp = conn.getresponse()
9586 except:
9587 pass
9588
9589 with alloc_fail(hapd, 1, "web_connection_unimplemented"):
9c06eda0 9590 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9591 conn.request("HEAD", "/wps_device.xml")
9592 try:
9593 resp = conn.getresponse()
9594 except:
9595 pass
d1341917
JM
9596
9597def test_ap_wps_frag_ack_oom(dev, apdev):
9598 """WPS and fragment ack OOM"""
9599 dev[0].request("SET wps_fragment_size 50")
9600 hapd = wps_start_ap(apdev[0])
9601 with alloc_fail(hapd, 1, "eap_wsc_build_frag_ack"):
9602 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
1e35aa15
JM
9603
9604def wait_scan_stopped(dev):
9605 dev.request("ABORT_SCAN")
9606 for i in range(50):
9607 res = dev.get_driver_status_field("scan_state")
9608 if "SCAN_STARTED" not in res and "SCAN_REQUESTED" not in res:
9609 break
9610 logger.debug("Waiting for scan to complete")
9611 time.sleep(0.1)
9612
9fd6804d 9613@remote_compatible
1e35aa15
JM
9614def test_ap_wps_eap_wsc_errors(dev, apdev):
9615 """WPS and EAP-WSC error cases"""
9616 ssid = "test-wps-conf-pin"
9617 appin = "12345670"
fab49f61
JM
9618 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9619 "wpa_passphrase": "12345678", "wpa": "2",
9620 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9621 "fragment_size": "300", "ap_pin": appin}
8b8a1864 9622 hapd = hostapd.add_ap(apdev[0], params)
1e35aa15
JM
9623 bssid = apdev[0]['bssid']
9624
9625 pin = dev[0].wps_read_pin()
9626 hapd.request("WPS_PIN any " + pin)
9627 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9628 dev[0].dump_monitor()
9629
9630 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK", "CCMP",
9631 "new passphrase", no_wait=True)
9632 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9633 if ev is None:
9634 raise Exception("WPS-FAIL not reported")
9635 dev[0].request("WPS_CANCEL")
9636 dev[0].wait_disconnected()
9637 wait_scan_stopped(dev[0])
9638 dev[0].dump_monitor()
9639
9640 dev[0].wps_reg(bssid, appin, "new ssid", "FOO", "CCMP",
9641 "new passphrase", no_wait=True)
9642 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9643 if ev is None:
9644 raise Exception("WPS-FAIL not reported")
9645 dev[0].request("WPS_CANCEL")
9646 dev[0].wait_disconnected()
9647 wait_scan_stopped(dev[0])
9648 dev[0].dump_monitor()
9649
9650 dev[0].wps_reg(bssid, appin, "new ssid", "WPA2PSK", "FOO",
9651 "new passphrase", no_wait=True)
9652 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9653 if ev is None:
9654 raise Exception("WPS-FAIL not reported")
9655 dev[0].request("WPS_CANCEL")
9656 dev[0].wait_disconnected()
9657 wait_scan_stopped(dev[0])
9658 dev[0].dump_monitor()
9659
9660 dev[0].wps_reg(bssid, appin + "new_key=a", "new ssid", "WPA2PSK", "CCMP",
9661 "new passphrase", no_wait=True)
9662 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9663 if ev is None:
9664 raise Exception("WPS-FAIL not reported")
9665 dev[0].request("WPS_CANCEL")
9666 dev[0].wait_disconnected()
9667 wait_scan_stopped(dev[0])
9668 dev[0].dump_monitor()
9669
fab49f61
JM
9670 tests = ["eap_wsc_init",
9671 "eap_msg_alloc;eap_wsc_build_msg",
9672 "wpabuf_alloc;eap_wsc_process_fragment"]
1e35aa15
JM
9673 for func in tests:
9674 with alloc_fail(dev[0], 1, func):
9675 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
9676 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9677 dev[0].request("WPS_CANCEL")
9678 dev[0].wait_disconnected()
0a9ff381
JM
9679 wait_scan_stopped(dev[0])
9680 dev[0].dump_monitor()
9681
9682 tests = [(1, "wps_decrypt_encr_settings"),
9683 (2, "hmac_sha256;wps_derive_psk")]
9684 for count, func in tests:
9685 hapd.request("WPS_PIN any " + pin)
9686 with fail_test(dev[0], count, func):
9687 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
9688 wait_fail_trigger(dev[0], "GET_FAIL")
9689 dev[0].request("WPS_CANCEL")
9690 dev[0].wait_disconnected()
1e35aa15
JM
9691 wait_scan_stopped(dev[0])
9692 dev[0].dump_monitor()
d8e5a55f 9693
bd3948c0
JM
9694 with alloc_fail(dev[0], 1, "eap_msg_alloc;eap_sm_build_expanded_nak"):
9695 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK",
9696 "CCMP", "new passphrase", no_wait=True)
9697 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9698 dev[0].request("WPS_CANCEL")
9699 dev[0].wait_disconnected()
9700 wait_scan_stopped(dev[0])
9701 dev[0].dump_monitor()
9702
d8e5a55f
JM
9703def test_ap_wps_eap_wsc(dev, apdev):
9704 """WPS and EAP-WSC in network profile"""
9705 params = int_eap_server_params()
9706 params["wps_state"] = "2"
8b8a1864 9707 hapd = hostapd.add_ap(apdev[0], params)
d8e5a55f
JM
9708 bssid = apdev[0]['bssid']
9709
9710 logger.info("Unexpected identity")
9711 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9712 eap="WSC", identity="WFA-SimpleConfig-Enrollee-unexpected",
9713 wait_connect=False)
9714 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9715 if ev is None:
9716 raise Exception("No EAP-Failure seen")
9717 dev[0].request("REMOVE_NETWORK all")
9718 dev[0].wait_disconnected()
9719
9720 logger.info("No phase1 parameter")
9721 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9722 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9723 wait_connect=False)
9724 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9725 if ev is None:
9726 raise Exception("Timeout on EAP method start")
9727 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9728 if ev is None:
9729 raise Exception("No EAP-Failure seen")
9730 dev[0].request("REMOVE_NETWORK all")
9731 dev[0].wait_disconnected()
9732
9733 logger.info("No PIN/PBC in phase1")
9734 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9735 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9736 phase1="foo", wait_connect=False)
9737 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9738 if ev is None:
9739 raise Exception("Timeout on EAP method start")
9740 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9741 if ev is None:
9742 raise Exception("No EAP-Failure seen")
9743 dev[0].request("REMOVE_NETWORK all")
9744 dev[0].wait_disconnected()
9745
9746 logger.info("Invalid pkhash in phase1")
9747 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9748 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9749 phase1="foo pkhash=q pbc=1", wait_connect=False)
9750 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9751 if ev is None:
9752 raise Exception("Timeout on EAP method start")
9753 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9754 if ev is None:
9755 raise Exception("No EAP-Failure seen")
9756 dev[0].request("REMOVE_NETWORK all")
9757 dev[0].wait_disconnected()
9758
9759 logger.info("Zero fragment_size")
9760 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9761 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9762 fragment_size="0", phase1="pin=12345670", wait_connect=False)
9763 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9764 if ev is None:
9765 raise Exception("Timeout on EAP method start")
9766 ev = dev[0].wait_event(["WPS-M2D"], timeout=5)
9767 if ev is None:
9768 raise Exception("No M2D seen")
9769 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9770 if ev is None:
9771 raise Exception("No EAP-Failure seen")
9772 dev[0].request("REMOVE_NETWORK all")
9773 dev[0].wait_disconnected()
9774
9775 logger.info("Missing new_auth")
9776 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9777 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9778 phase1="pin=12345670 new_ssid=aa", wait_connect=False)
9779 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9780 if ev is None:
9781 raise Exception("Timeout on EAP method start")
9782 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9783 if ev is None:
9784 raise Exception("No EAP-Failure seen")
9785 dev[0].request("REMOVE_NETWORK all")
9786 dev[0].wait_disconnected()
9787
9788 logger.info("Missing new_encr")
9789 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9790 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9791 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa", wait_connect=False)
9792 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9793 if ev is None:
9794 raise Exception("Timeout on EAP method start")
9795 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9796 if ev is None:
9797 raise Exception("No EAP-Failure seen")
9798 dev[0].request("REMOVE_NETWORK all")
9799 dev[0].wait_disconnected()
9800
9801 logger.info("Missing new_key")
9802 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9803 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9804 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa new_encr=CCMP",
9805 wait_connect=False)
9806 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9807 if ev is None:
9808 raise Exception("Timeout on EAP method start")
9809 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9810 if ev is None:
9811 raise Exception("No EAP-Failure seen")
9812 dev[0].request("REMOVE_NETWORK all")
9813 dev[0].wait_disconnected()
4425b1ed
JM
9814
9815def test_ap_wps_and_bss_limit(dev, apdev):
9816 """WPS and wpa_supplicant BSS entry limit"""
9817 try:
9818 _test_ap_wps_and_bss_limit(dev, apdev)
9819 finally:
9820 dev[0].request("SET bss_max_count 200")
9821 pass
9822
9823def _test_ap_wps_and_bss_limit(dev, apdev):
fab49f61
JM
9824 params = {"ssid": "test-wps", "eap_server": "1", "wps_state": "2",
9825 "wpa_passphrase": "12345678", "wpa": "2",
9826 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
4425b1ed
JM
9827 hapd = hostapd.add_ap(apdev[0], params)
9828
fab49f61
JM
9829 params = {"ssid": "test-wps-2", "eap_server": "1", "wps_state": "2",
9830 "wpa_passphrase": "1234567890", "wpa": "2",
9831 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
4425b1ed
JM
9832 hapd2 = hostapd.add_ap(apdev[1], params)
9833
9834 id = dev[1].add_network()
9835 dev[1].set_network(id, "mode", "2")
9836 dev[1].set_network_quoted(id, "ssid", "wpas-ap-no-wps")
9837 dev[1].set_network_quoted(id, "psk", "12345678")
9838 dev[1].set_network(id, "frequency", "2462")
9839 dev[1].set_network(id, "scan_freq", "2462")
9840 dev[1].set_network(id, "wps_disabled", "1")
9841 dev[1].select_network(id)
9842
9843 id = dev[2].add_network()
9844 dev[2].set_network(id, "mode", "2")
9845 dev[2].set_network_quoted(id, "ssid", "wpas-ap")
9846 dev[2].set_network_quoted(id, "psk", "12345678")
9847 dev[2].set_network(id, "frequency", "2437")
9848 dev[2].set_network(id, "scan_freq", "2437")
9849 dev[2].select_network(id)
9850
9851 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9852 wpas.interface_add("wlan5")
9853 id = wpas.add_network()
9854 wpas.set_network(id, "mode", "2")
9855 wpas.set_network_quoted(id, "ssid", "wpas-ap")
9856 wpas.set_network_quoted(id, "psk", "12345678")
9857 wpas.set_network(id, "frequency", "2437")
9858 wpas.set_network(id, "scan_freq", "2437")
9859 wpas.select_network(id)
9860
9861 dev[1].wait_connected()
9862 dev[2].wait_connected()
9863 wpas.wait_connected()
9864 wpas.request("WPS_PIN any 12345670")
9865
9866 hapd.request("WPS_PBC")
9867 hapd2.request("WPS_PBC")
9868
9869 dev[0].request("SET bss_max_count 1")
9870
9871 id = dev[0].add_network()
9872 dev[0].set_network_quoted(id, "ssid", "testing")
9873
9874 id = dev[0].add_network()
9875 dev[0].set_network_quoted(id, "ssid", "testing")
9876 dev[0].set_network(id, "key_mgmt", "WPS")
9877
9878 dev[0].request("WPS_PBC")
9879 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
9880 dev[0].request("WPS_CANCEL")
9881
9882 id = dev[0].add_network()
9883 dev[0].set_network_quoted(id, "ssid", "testing")
9884 dev[0].set_network(id, "key_mgmt", "WPS")
9885
9886 dev[0].scan(freq="2412")
74b23faf
JM
9887
9888def test_ap_wps_pbc_2ap(dev, apdev):
9889 """WPS PBC with two APs advertising same SSID"""
fab49f61
JM
9890 params = {"ssid": "wps", "eap_server": "1", "wps_state": "2",
9891 "wpa_passphrase": "12345678", "wpa": "2",
9892 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9893 "wps_independent": "1"}
74b23faf 9894 hapd = hostapd.add_ap(apdev[0], params)
fab49f61
JM
9895 params = {"ssid": "wps", "eap_server": "1", "wps_state": "2",
9896 "wpa_passphrase": "123456789", "wpa": "2",
9897 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9898 "wps_independent": "1"}
74b23faf
JM
9899 hapd2 = hostapd.add_ap(apdev[1], params)
9900 hapd.request("WPS_PBC")
9901
9902 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9903 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
9904 wpas.dump_monitor()
8b944cf7 9905 wpas.flush_scan_cache()
74b23faf
JM
9906
9907 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
9908 wpas.scan_for_bss(apdev[1]['bssid'], freq="2412")
9909 wpas.request("WPS_PBC")
9910 wpas.wait_connected()
9911 wpas.request("DISCONNECT")
9912 hapd.request("DISABLE")
9913 hapd2.request("DISABLE")
9914 wpas.flush_scan_cache()
aed9e23a
JM
9915
9916def test_ap_wps_er_enrollee_to_conf_ap(dev, apdev):
9917 """WPS ER enrolling a new device to a configured AP"""
9918 try:
9919 _test_ap_wps_er_enrollee_to_conf_ap(dev, apdev)
9920 finally:
9921 dev[0].request("WPS_ER_STOP")
9922
9923def _test_ap_wps_er_enrollee_to_conf_ap(dev, apdev):
9924 ssid = "wps-er-enrollee-to-conf-ap"
9925 ap_pin = "12345670"
9926 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
fab49f61
JM
9927 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9928 "wpa_passphrase": "12345678", "wpa": "2",
9929 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9930 "device_name": "Wireless AP", "manufacturer": "Company",
9931 "model_name": "WAP", "model_number": "123",
9932 "serial_number": "12345", "device_type": "6-0050F204-1",
9933 "os_version": "01020300",
9934 "config_methods": "label push_button",
9935 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
aed9e23a
JM
9936 hapd = hostapd.add_ap(apdev[0], params)
9937 bssid = hapd.own_addr()
9938
9939 id = dev[0].connect(ssid, psk="12345678", scan_freq="2412")
9940 dev[0].dump_monitor()
9941
9942 dev[0].request("WPS_ER_START ifname=lo")
9943 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
9944 if ev is None:
9945 raise Exception("AP discovery timed out")
9946 if ap_uuid not in ev:
9947 raise Exception("Expected AP UUID not found")
9948
9949 pin = dev[2].wps_read_pin()
9950 addr2 = dev[2].own_addr()
9951 dev[0].dump_monitor()
9952 dev[2].scan_for_bss(bssid, freq=2412)
9953 dev[2].dump_monitor()
9954 dev[2].request("WPS_PIN %s %s" % (bssid, pin))
9955
9956 for i in range(3):
9957 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
9958 if ev is None:
9959 raise Exception("Enrollee not seen")
9960 if addr2 in ev:
9961 break
9962 if addr2 not in ev:
9963 raise Exception("Unexpected Enrollee MAC address")
9964 dev[0].dump_monitor()
9965
9966 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " " + str(id))
9967 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
9968 dev[2].wait_connected(timeout=30)
9969 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
9970 if ev is None:
9971 raise Exception("WPS ER did not report success")
9972
9973def test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev):
9974 """WPS ER enrolling a new device to a configured AP (2)"""
9975 try:
9976 _test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev)
9977 finally:
9978 dev[0].request("WPS_ER_STOP")
9979
9980def _test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev):
9981 ssid = "wps-er-enrollee-to-conf-ap"
9982 ap_pin = "12345670"
9983 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
fab49f61
JM
9984 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9985 "wpa_passphrase": "12345678", "wpa": "2",
9986 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9987 "device_name": "Wireless AP", "manufacturer": "Company",
9988 "model_name": "WAP", "model_number": "123",
9989 "serial_number": "12345", "device_type": "6-0050F204-1",
9990 "os_version": "01020300",
9991 "config_methods": "label push_button",
9992 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
aed9e23a
JM
9993 hapd = hostapd.add_ap(apdev[0], params)
9994 bssid = hapd.own_addr()
9995
9996 id = dev[0].connect(ssid, psk="12345678", scan_freq="2412")
9997 dev[0].dump_monitor()
9998
9999 dev[0].request("WPS_ER_START ifname=lo")
10000 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
10001 if ev is None:
10002 raise Exception("AP discovery timed out")
10003 if ap_uuid not in ev:
10004 raise Exception("Expected AP UUID not found")
10005
10006 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
10007 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
10008 if ev is None:
10009 raise Exception("AP learn timed out")
10010 if ap_uuid not in ev:
10011 raise Exception("Expected AP UUID not in settings")
10012 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
10013 if ev is None:
10014 raise Exception("WPS-FAIL after AP learn timed out")
10015 time.sleep(0.1)
10016
10017 pin = dev[1].wps_read_pin()
10018 addr1 = dev[1].own_addr()
10019 dev[0].dump_monitor()
10020 dev[0].request("WPS_ER_PIN any " + pin)
10021 time.sleep(0.1)
10022 dev[1].scan_for_bss(bssid, freq=2412)
10023 dev[1].request("WPS_PIN any %s" % pin)
10024 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
10025 if ev is None:
10026 raise Exception("Enrollee did not report success")
10027 dev[1].wait_connected(timeout=15)
10028 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
10029 if ev is None:
10030 raise Exception("WPS ER did not report success")
5026406d
JM
10031
10032def test_ap_wps_ignore_broadcast_ssid(dev, apdev):
10033 """WPS AP trying to ignore broadcast SSID"""
10034 ssid = "test-wps"
10035 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
10036 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
10037 "ignore_broadcast_ssid": "1"})
5026406d
JM
10038 if "FAIL" not in hapd.request("WPS_PBC"):
10039 raise Exception("WPS unexpectedly enabled")
10040
10041def test_ap_wps_wep(dev, apdev):
10042 """WPS AP trying to enable WEP"""
200c7693 10043 check_wep_capa(dev[0])
5026406d
JM
10044 ssid = "test-wps"
10045 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
10046 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
10047 "ieee80211n": "0", "wep_key0": '"hello"'})
5026406d
JM
10048 if "FAIL" not in hapd.request("WPS_PBC"):
10049 raise Exception("WPS unexpectedly enabled")
10050
10051def test_ap_wps_tkip(dev, apdev):
10052 """WPS AP trying to enable TKIP"""
10053 ssid = "test-wps"
10054 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
10055 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
10056 "ieee80211n": "0", "wpa": '1',
10057 "wpa_key_mgmt": "WPA-PSK",
10058 "wpa_passphrase": "12345678"})
5026406d
JM
10059 if "FAIL" not in hapd.request("WPS_PBC"):
10060 raise Exception("WPS unexpectedly enabled")
454b66d2
JM
10061
10062def test_ap_wps_conf_dummy_cred(dev, apdev):
10063 """WPS PIN provisioning with configured AP using dummy cred"""
10064 ssid = "test-wps-conf"
10065 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
10066 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10067 "wpa_passphrase": "12345678", "wpa": "2",
10068 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
454b66d2
JM
10069 hapd.request("WPS_PIN any 12345670")
10070 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10071 dev[0].dump_monitor()
10072 try:
10073 hapd.set("wps_testing_dummy_cred", "1")
10074 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
10075 for i in range(1, 3):
10076 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
10077 if ev is None:
10078 raise Exception("WPS credential %d not received" % i)
10079 dev[0].wait_connected(timeout=30)
10080 finally:
10081 hapd.set("wps_testing_dummy_cred", "0")
cde2143c
JM
10082
10083def test_ap_wps_rf_bands(dev, apdev):
10084 """WPS and wps_rf_bands configuration"""
10085 ssid = "test-wps-conf"
fab49f61
JM
10086 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10087 "wpa_passphrase": "12345678", "wpa": "2",
10088 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
10089 "wps_rf_bands": "ag"}
cde2143c
JM
10090
10091 hapd = hostapd.add_ap(apdev[0], params)
10092 bssid = hapd.own_addr()
10093 hapd.request("WPS_PBC")
10094 dev[0].scan_for_bss(bssid, freq="2412")
10095 dev[0].dump_monitor()
10096 dev[0].request("WPS_PBC " + bssid)
10097 dev[0].wait_connected(timeout=30)
10098 bss = dev[0].get_bss(bssid)
10099 logger.info("BSS: " + str(bss))
10100 if "103c000103" not in bss['ie']:
10101 raise Exception("RF Bands attribute with expected values not found")
10102 dev[0].request("DISCONNECT")
10103 dev[0].wait_disconnected()
10104 hapd.set("wps_rf_bands", "ad")
10105 hapd.set("wps_rf_bands", "a")
10106 hapd.set("wps_rf_bands", "g")
10107 hapd.set("wps_rf_bands", "b")
10108 hapd.set("wps_rf_bands", "ga")
10109 hapd.disable()
10110 dev[0].dump_monitor()
10111 dev[0].flush_scan_cache()
93b85d44
JM
10112
10113def test_ap_wps_pbc_in_m1(dev, apdev):
10114 """WPS and pbc_in_m1"""
10115 ssid = "test-wps-conf"
fab49f61
JM
10116 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10117 "wpa_passphrase": "12345678", "wpa": "2",
10118 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
10119 "config_methods": "virtual_push_button virtual_display",
10120 "pbc_in_m1": "1"}
93b85d44
JM
10121
10122 hapd = hostapd.add_ap(apdev[0], params)
10123 bssid = hapd.own_addr()
10124 hapd.request("WPS_PBC")
10125 dev[0].scan_for_bss(bssid, freq="2412")
10126 dev[0].dump_monitor()
10127 dev[0].request("WPS_PBC " + bssid)
10128 dev[0].wait_connected(timeout=30)
10129 dev[0].request("DISCONNECT")
10130 dev[0].wait_disconnected()
10131 hapd.disable()
10132 dev[0].dump_monitor()
10133 dev[0].flush_scan_cache()
35320d7a 10134
97d2d7ac
MK
10135def test_ap_wps_pbc_mac_addr_change(dev, apdev, params):
10136 """WPS M1 with MAC address change"""
10137 ssid = "test-wps-mac-addr-change"
10138 hapd = hostapd.add_ap(apdev[0],
10139 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
10140 hapd.request("WPS_PBC")
10141 if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
10142 raise Exception("PBC status not shown correctly")
10143 dev[0].flush_scan_cache()
10144
10145 test_addr = '02:11:22:33:44:55'
10146 addr = dev[0].get_status_field("address")
10147 if addr == test_addr:
10148 raise Exception("Unexpected initial MAC address")
10149
10150 try:
10151 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'down'])
10152 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'address',
10153 test_addr])
10154 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'up'])
10155 addr1 = dev[0].get_status_field("address")
10156 if addr1 != test_addr:
10157 raise Exception("Failed to change MAC address")
10158
10159 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
10160 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
10161 dev[0].wait_connected(timeout=30)
10162 status = dev[0].get_status()
10163 if status['wpa_state'] != 'COMPLETED' or \
10164 status['bssid'] != apdev[0]['bssid']:
10165 raise Exception("Not fully connected")
10166
10167 out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
10168 "wps.message_type == 0x04",
10169 display=["wps.mac_address"])
10170 res = out.splitlines()
10171
10172 if len(res) < 1:
10173 raise Exception("No M1 message with MAC address found")
10174 if res[0] != addr1:
10175 raise Exception("Wrong M1 MAC address")
10176 dev[0].request("DISCONNECT")
10177 dev[0].wait_disconnected()
10178 hapd.disable()
10179 dev[0].dump_monitor()
10180 dev[0].flush_scan_cache()
10181 finally:
10182 # Restore MAC address
10183 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'down'])
10184 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'address',
10185 addr])
10186 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'up'])
10187
35320d7a
JM
10188def test_ap_wps_pin_start_failure(dev, apdev):
10189 """WPS_PIN start failure"""
10190 with alloc_fail(dev[0], 1, "wpas_wps_start_dev_pw"):
10191 if "FAIL" not in dev[0].request("WPS_PIN any 12345670"):
10192 raise Exception("WPS_PIN not rejected during OOM")
10193 with alloc_fail(dev[0], 1, "wpas_wps_start_dev_pw"):
10194 if "FAIL" not in dev[0].request("WPS_PIN any"):
10195 raise Exception("WPS_PIN not rejected during OOM")
cc5bf65f
JM
10196
10197def test_ap_wps_ap_pin_failure(dev, apdev):
10198 """WPS_AP_PIN failure"""
10199 id = dev[0].add_network()
10200 dev[0].set_network(id, "mode", "2")
10201 dev[0].set_network_quoted(id, "ssid", "wpas-ap-wps")
10202 dev[0].set_network_quoted(id, "psk", "1234567890")
10203 dev[0].set_network(id, "frequency", "2412")
10204 dev[0].set_network(id, "scan_freq", "2412")
10205 dev[0].select_network(id)
10206 dev[0].wait_connected()
10207
10208 with fail_test(dev[0], 1,
10209 "os_get_random;wpa_supplicant_ctrl_iface_wps_ap_pin"):
10210 if "FAIL" not in dev[0].request("WPS_AP_PIN random"):
10211 raise Exception("WPS_AP_PIN random accepted")
10212 with alloc_fail(dev[0], 1, "wpas_wps_ap_pin_set"):
10213 if "FAIL" not in dev[0].request("WPS_AP_PIN set 12345670"):
10214 raise Exception("WPS_AP_PIN set accepted")
10215
10216 dev[0].request("DISCONNECT")
10217 dev[0].wait_disconnected()
2087feb6
JM
10218
10219def test_ap_wps_random_uuid(dev, apdev, params):
10220 """WPS and random UUID on Enrollee"""
10221 ssid = "test-wps-conf"
10222 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
10223 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10224 "wpa_passphrase": "12345678", "wpa": "2",
10225 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2087feb6
JM
10226
10227 config = os.path.join(params['logdir'], 'ap_wps_random_uuid.conf')
10228 with open(config, "w") as f:
10229 f.write("auto_uuid=1\n")
10230
10231 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
10232
10233 uuid = []
10234 for i in range(3):
10235 wpas.interface_add("wlan5", config=config)
10236
10237 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
10238 wpas.dump_monitor()
10239 wpas.request("WPS_PBC " + apdev[0]['bssid'])
10240
10241 ev = hapd.wait_event(["WPS-ENROLLEE-SEEN"], timeout=10)
10242 if ev is None:
10243 raise Exception("Enrollee not seen")
10244 uuid.append(ev.split(' ')[2])
10245 wpas.request("WPS_CANCEL")
10246 wpas.dump_monitor()
10247
10248 wpas.interface_remove("wlan5")
10249
10250 hapd.dump_monitor()
10251
10252 logger.info("Seen UUIDs: " + str(uuid))
10253 if uuid[0] == uuid[1] or uuid[0] == uuid[2] or uuid[1] == uuid[2]:
10254 raise Exception("Same UUID used multiple times")
1fb0c105
JM
10255
10256def test_ap_wps_conf_pin_gcmp_128(dev, apdev):
10257 """WPS PIN provisioning with configured AP using GCMP-128"""
10258 run_ap_wps_conf_pin_cipher(dev, apdev, "GCMP")
10259
10260def test_ap_wps_conf_pin_gcmp_256(dev, apdev):
10261 """WPS PIN provisioning with configured AP using GCMP-256"""
10262 run_ap_wps_conf_pin_cipher(dev, apdev, "GCMP-256")
10263
10264def test_ap_wps_conf_pin_ccmp_256(dev, apdev):
10265 """WPS PIN provisioning with configured AP using CCMP-256"""
10266 run_ap_wps_conf_pin_cipher(dev, apdev, "CCMP-256")
10267
10268def run_ap_wps_conf_pin_cipher(dev, apdev, cipher):
10269 if cipher not in dev[0].get_capability("pairwise"):
10270 raise HwsimSkip("Cipher %s not supported" % cipher)
10271 ssid = "test-wps-conf-pin"
10272 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
10273 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10274 "wpa_passphrase": "12345678", "wpa": "2",
10275 "wpa_key_mgmt": "WPA-PSK",
10276 "rsn_pairwise": cipher})
1fb0c105
JM
10277 logger.info("WPS provisioning step")
10278 pin = dev[0].wps_read_pin()
10279 hapd.request("WPS_PIN any " + pin)
cc7f85ca 10280 dev[0].flush_scan_cache()
1fb0c105
JM
10281 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10282 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
10283 dev[0].wait_connected(timeout=15)
dc0f727c
JM
10284
10285def test_ap_wps_and_sae(dev, apdev):
10286 """Initial AP configuration with first WPS Enrollee and adding SAE"""
10287 try:
10288 run_ap_wps_and_sae(dev, apdev)
10289 finally:
10290 dev[0].set("wps_cred_add_sae", "0")
10291
10292def run_ap_wps_and_sae(dev, apdev):
4c0af8ad 10293 check_sae_capab(dev[0])
dc0f727c
JM
10294 ssid = "test-wps-sae"
10295 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
10296 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
10297 "wps_cred_add_sae": "1"})
dc0f727c
JM
10298 logger.info("WPS provisioning step")
10299 pin = dev[0].wps_read_pin()
10300 hapd.request("WPS_PIN any " + pin)
10301
10302 dev[0].set("wps_cred_add_sae", "1")
96ad141e 10303 dev[0].request("SET sae_groups ")
dc0f727c
JM
10304 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
10305 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
10306 dev[0].wait_connected(timeout=30)
10307 status = dev[0].get_status()
10308 if status['key_mgmt'] != "SAE":
10309 raise Exception("SAE not used")
10310 if 'pmf' not in status or status['pmf'] != "1":
10311 raise Exception("PMF not enabled")
10312
10313 pin = dev[1].wps_read_pin()
10314 hapd.request("WPS_PIN any " + pin)
10315 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
10316 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
10317 dev[1].wait_connected(timeout=30)
10318 status = dev[1].get_status()
10319 if status['key_mgmt'] != "WPA2-PSK":
10320 raise Exception("WPA2-PSK not used")
10321 if 'pmf' in status:
10322 raise Exception("PMF enabled")
10323
10324def test_ap_wps_conf_and_sae(dev, apdev):
10325 """WPS PBC provisioning with configured AP using PSK+SAE"""
10326 try:
10327 run_ap_wps_conf_and_sae(dev, apdev)
10328 finally:
10329 dev[0].set("wps_cred_add_sae", "0")
10330
10331def run_ap_wps_conf_and_sae(dev, apdev):
4c0af8ad 10332 check_sae_capab(dev[0])
dc0f727c
JM
10333 ssid = "test-wps-conf-sae"
10334 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
10335 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10336 "wpa_passphrase": "12345678", "wpa": "2",
10337 "ieee80211w": "1", "sae_require_mfp": "1",
10338 "wpa_key_mgmt": "WPA-PSK SAE",
10339 "rsn_pairwise": "CCMP"})
dc0f727c
JM
10340
10341 dev[0].set("wps_cred_add_sae", "1")
96ad141e 10342 dev[0].request("SET sae_groups ")
dc0f727c
JM
10343 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10344 pin = dev[0].wps_read_pin()
10345 hapd.request("WPS_PIN any " + pin)
10346 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
10347 dev[0].wait_connected(timeout=30)
10348 status = dev[0].get_status()
10349 if status['key_mgmt'] != "SAE":
10350 raise Exception("SAE not used")
10351 if 'pmf' not in status or status['pmf'] != "1":
10352 raise Exception("PMF not enabled")
10353
10354 dev[1].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
10355 key_mgmt="WPA-PSK", ieee80211w="0")
10356
10357def test_ap_wps_reg_config_and_sae(dev, apdev):
10358 """WPS registrar configuring an AP using AP PIN and using PSK+SAE"""
10359 try:
10360 run_ap_wps_reg_config_and_sae(dev, apdev)
10361 finally:
10362 dev[0].set("wps_cred_add_sae", "0")
10363
10364def run_ap_wps_reg_config_and_sae(dev, apdev):
4c0af8ad 10365 check_sae_capab(dev[0])
dc0f727c
JM
10366 ssid = "test-wps-init-ap-pin-sae"
10367 appin = "12345670"
10368 hostapd.add_ap(apdev[0],
fab49f61
JM
10369 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10370 "ap_pin": appin, "wps_cred_add_sae": "1"})
dc0f727c 10371 logger.info("WPS configuration step")
41532439 10372 dev[0].flush_scan_cache()
dc0f727c 10373 dev[0].set("wps_cred_add_sae", "1")
96ad141e 10374 dev[0].request("SET sae_groups ")
dc0f727c
JM
10375 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
10376 dev[0].dump_monitor()
10377 new_ssid = "wps-new-ssid"
10378 new_passphrase = "1234567890"
10379 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
10380 new_passphrase)
10381 status = dev[0].get_status()
10382 if status['key_mgmt'] != "SAE":
10383 raise Exception("SAE not used")
10384 if 'pmf' not in status or status['pmf'] != "1":
10385 raise Exception("PMF not enabled")
10386
10387 dev[1].connect(new_ssid, psk=new_passphrase, scan_freq="2412", proto="WPA2",
10388 key_mgmt="WPA-PSK", ieee80211w="0")
754cd71b
JM
10389
10390def test_ap_wps_appl_ext(dev, apdev):
10391 """WPS Application Extension attribute"""
10392 ssid = "test-wps-conf"
10393 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10394 "wps_application_ext": 16*"11" + 5*"ee",
10395 "wpa_passphrase": "12345678", "wpa": "2",
10396 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
10397 hapd = hostapd.add_ap(apdev[0], params)
10398 pin = dev[0].wps_read_pin()
10399 hapd.request("WPS_PIN any " + pin)
10400 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10401 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
10402 dev[0].wait_connected(timeout=30)
72fd30c4
JM
10403
10404def test_ap_wps_pbc_ap_timeout(dev, apdev, params):
10405 """WPS PBC timeout on AP [long]"""
10406 if not params['long']:
10407 raise HwsimSkip("Skip test case with long duration due to --long not specified")
10408 run_ap_wps_ap_timeout(dev, apdev, "WPS_PBC")
10409
10410def test_ap_wps_pin_ap_timeout(dev, apdev, params):
10411 """WPS PIN timeout on AP [long]"""
10412 if not params['long']:
10413 raise HwsimSkip("Skip test case with long duration due to --long not specified")
10414 run_ap_wps_ap_timeout(dev, apdev, "WPS_PIN any 12345670 10")
10415
10416def run_ap_wps_ap_timeout(dev, apdev, cmd):
10417 ssid = "test-wps-conf"
10418 hapd = hostapd.add_ap(apdev[0],
10419 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10420 "wpa_passphrase": "12345678", "wpa": "2",
10421 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
10422 bssid = hapd.own_addr()
10423 hapd.request(cmd)
10424 time.sleep(1)
10425 dev[0].scan_for_bss(bssid, freq="2412")
10426 bss = dev[0].get_bss(bssid)
10427 logger.info("BSS during active Registrar: " + str(bss))
10428 if not bss['ie'].endswith("0106ffffffffffff"):
10429 raise Exception("Authorized MAC not included")
10430 ev = hapd.wait_event(["WPS-TIMEOUT"], timeout=130)
10431 if ev is None and "PBC" in cmd:
10432 raise Exception("WPS-TIMEOUT not reported")
10433 time.sleep(5)
10434 dev[0].flush_scan_cache()
10435 dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
10436 bss = dev[0].get_bss(bssid)
10437 logger.info("BSS after timeout: " + str(bss))
10438 if bss['ie'].endswith("0106ffffffffffff"):
10439 raise Exception("Authorized MAC not removed")