]> git.ipfire.org Git - thirdparty/hostap.git/blame - tests/hwsim/test_ap_wps.py
tests: OWE: allow hex integers from tshark
[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
302b7a1b 47
24b7f282 48def wps_start_ap(apdev, ssid="test-wps-conf"):
fab49f61
JM
49 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
50 "wpa_passphrase": "12345678", "wpa": "2",
51 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
afc26df2 52 return hostapd.add_ap(apdev, params)
24b7f282 53
9fd6804d 54@remote_compatible
ae3ad328 55def test_ap_wps_init(dev, apdev):
302b7a1b
JM
56 """Initial AP configuration with first WPS Enrollee"""
57 ssid = "test-wps"
6f334bf7 58 hapd = hostapd.add_ap(apdev[0],
fab49f61 59 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
302b7a1b
JM
60 logger.info("WPS provisioning step")
61 hapd.request("WPS_PBC")
d671a420
JM
62 if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
63 raise Exception("PBC status not shown correctly")
b9018833
JM
64
65 id = dev[0].add_network()
66 dev[0].set_network_quoted(id, "ssid", "home")
67 dev[0].set_network_quoted(id, "psk", "12345678")
68 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
69
70 id = dev[0].add_network()
71 dev[0].set_network_quoted(id, "ssid", "home2")
72 dev[0].set_network(id, "bssid", "00:11:22:33:44:55")
73 dev[0].set_network(id, "key_mgmt", "NONE")
74 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
75
302b7a1b 76 dev[0].request("WPS_PBC")
5f35a5e2 77 dev[0].wait_connected(timeout=30)
302b7a1b 78 status = dev[0].get_status()
ae3ad328 79 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
80 raise Exception("Not fully connected")
81 if status['ssid'] != ssid:
82 raise Exception("Unexpected SSID")
83 if status['pairwise_cipher'] != 'CCMP':
84 raise Exception("Unexpected encryption configuration")
85 if status['key_mgmt'] != 'WPA2-PSK':
86 raise Exception("Unexpected key_mgmt")
87
d671a420
JM
88 status = hapd.request("WPS_GET_STATUS")
89 if "PBC Status: Disabled" not in status:
90 raise Exception("PBC status not shown correctly")
91 if "Last WPS result: Success" not in status:
92 raise Exception("Last WPS result not shown correctly")
93 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
94 raise Exception("Peer address not shown correctly")
75b25ece
JM
95 conf = hapd.request("GET_CONFIG")
96 if "wps_state=configured" not in conf:
97 raise Exception("AP not in WPS configured state")
742408af
JM
98 if "wpa=3" not in conf:
99 raise Exception("AP not in WPA+WPA2 configuration")
75b25ece
JM
100 if "rsn_pairwise_cipher=CCMP TKIP" not in conf:
101 raise Exception("Unexpected rsn_pairwise_cipher")
102 if "wpa_pairwise_cipher=CCMP TKIP" not in conf:
103 raise Exception("Unexpected wpa_pairwise_cipher")
104 if "group_cipher=TKIP" not in conf:
105 raise Exception("Unexpected group_cipher")
d671a420 106
b9018833
JM
107 if len(dev[0].list_networks()) != 3:
108 raise Exception("Unexpected number of network blocks")
109
18030dc0
JM
110def test_ap_wps_init_2ap_pbc(dev, apdev):
111 """Initial two-radio AP configuration with first WPS PBC Enrollee"""
112 ssid = "test-wps"
fab49f61 113 params = {"ssid": ssid, "eap_server": "1", "wps_state": "1"}
6f334bf7 114 hapd = hostapd.add_ap(apdev[0], params)
8b8a1864 115 hostapd.add_ap(apdev[1], params)
18030dc0
JM
116 logger.info("WPS provisioning step")
117 hapd.request("WPS_PBC")
84a40841
JM
118 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
119 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
120 bss = dev[0].get_bss(apdev[0]['bssid'])
121 if "[WPS-PBC]" not in bss['flags']:
122 raise Exception("WPS-PBC flag missing from AP1")
123 bss = dev[0].get_bss(apdev[1]['bssid'])
124 if "[WPS-PBC]" not in bss['flags']:
125 raise Exception("WPS-PBC flag missing from AP2")
126 dev[0].dump_monitor()
f19d87f1 127 dev[0].request("SET wps_cred_processing 2")
18030dc0 128 dev[0].request("WPS_PBC")
f19d87f1
JM
129 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=30)
130 dev[0].request("SET wps_cred_processing 0")
131 if ev is None:
132 raise Exception("WPS cred event not seen")
133 if "100e" not in ev:
134 raise Exception("WPS attributes not included in the cred event")
5f35a5e2 135 dev[0].wait_connected(timeout=30)
18030dc0 136
84a40841
JM
137 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
138 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
139 bss = dev[1].get_bss(apdev[0]['bssid'])
140 if "[WPS-PBC]" in bss['flags']:
141 raise Exception("WPS-PBC flag not cleared from AP1")
142 bss = dev[1].get_bss(apdev[1]['bssid'])
143 if "[WPS-PBC]" in bss['flags']:
0bde923c 144 raise Exception("WPS-PBC flag not cleared from AP2")
18030dc0
JM
145
146def test_ap_wps_init_2ap_pin(dev, apdev):
147 """Initial two-radio AP configuration with first WPS PIN Enrollee"""
148 ssid = "test-wps"
fab49f61 149 params = {"ssid": ssid, "eap_server": "1", "wps_state": "1"}
6f334bf7 150 hapd = hostapd.add_ap(apdev[0], params)
8b8a1864 151 hostapd.add_ap(apdev[1], params)
18030dc0
JM
152 logger.info("WPS provisioning step")
153 pin = dev[0].wps_read_pin()
154 hapd.request("WPS_PIN any " + pin)
84a40841
JM
155 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
156 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
157 bss = dev[0].get_bss(apdev[0]['bssid'])
158 if "[WPS-AUTH]" not in bss['flags']:
159 raise Exception("WPS-AUTH flag missing from AP1")
160 bss = dev[0].get_bss(apdev[1]['bssid'])
161 if "[WPS-AUTH]" not in bss['flags']:
162 raise Exception("WPS-AUTH flag missing from AP2")
163 dev[0].dump_monitor()
164 dev[0].request("WPS_PIN any " + pin)
5f35a5e2 165 dev[0].wait_connected(timeout=30)
18030dc0 166
84a40841
JM
167 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
168 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
169 bss = dev[1].get_bss(apdev[0]['bssid'])
170 if "[WPS-AUTH]" in bss['flags']:
171 raise Exception("WPS-AUTH flag not cleared from AP1")
172 bss = dev[1].get_bss(apdev[1]['bssid'])
173 if "[WPS-AUTH]" in bss['flags']:
0bde923c 174 raise Exception("WPS-AUTH flag not cleared from AP2")
18030dc0 175
9fd6804d 176@remote_compatible
35831e94
JM
177def test_ap_wps_init_through_wps_config(dev, apdev):
178 """Initial AP configuration using wps_config command"""
179 ssid = "test-wps-init-config"
6f334bf7 180 hapd = hostapd.add_ap(apdev[0],
fab49f61 181 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
54c58f29 182 if "FAIL" in hapd.request("WPS_CONFIG " + binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(b"12345678").decode()):
35831e94 183 raise Exception("WPS_CONFIG command failed")
180cd73d
JM
184 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
185 if ev is None:
186 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
187 # It takes some time for the AP to update Beacon and Probe Response frames,
188 # so wait here before requesting the scan to be started to avoid adding
189 # extra five second wait to the test due to fetching obsolete scan results.
190 hapd.ping()
191 time.sleep(0.2)
35831e94
JM
192 dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
193 pairwise="CCMP", group="CCMP")
194
82358a2a
JM
195 if "FAIL" not in hapd.request("WPS_CONFIG foo"):
196 raise Exception("Invalid WPS_CONFIG accepted")
197
9fd6804d 198@remote_compatible
fbf6b717
JM
199def test_ap_wps_init_through_wps_config_2(dev, apdev):
200 """AP configuration using wps_config and wps_cred_processing=2"""
201 ssid = "test-wps-init-config"
6f334bf7 202 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
203 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
204 "wps_cred_processing": "2"})
54c58f29 205 if "FAIL" in hapd.request("WPS_CONFIG " + binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(b"12345678").decode()):
fbf6b717
JM
206 raise Exception("WPS_CONFIG command failed")
207 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
208 if ev is None:
209 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
210 if "100e" not in ev:
211 raise Exception("WPS-NEW-AP-SETTINGS did not include Credential")
212
9fd6804d 213@remote_compatible
e1eb0e9e
JM
214def test_ap_wps_invalid_wps_config_passphrase(dev, apdev):
215 """AP configuration using wps_config command with invalid passphrase"""
216 ssid = "test-wps-init-config"
6f334bf7 217 hapd = hostapd.add_ap(apdev[0],
fab49f61 218 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
54c58f29 219 if "FAIL" not in hapd.request("WPS_CONFIG " + binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(b"1234567").decode()):
e1eb0e9e
JM
220 raise Exception("Invalid WPS_CONFIG command accepted")
221
ae3ad328 222def test_ap_wps_conf(dev, apdev):
302b7a1b
JM
223 """WPS PBC provisioning with configured AP"""
224 ssid = "test-wps-conf"
6f334bf7 225 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
226 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
227 "wpa_passphrase": "12345678", "wpa": "2",
228 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
302b7a1b
JM
229 logger.info("WPS provisioning step")
230 hapd.request("WPS_PBC")
33d0b157 231 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 232 dev[0].dump_monitor()
33d0b157 233 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 234 dev[0].wait_connected(timeout=30)
302b7a1b 235 status = dev[0].get_status()
ae3ad328 236 if status['wpa_state'] != 'COMPLETED':
302b7a1b 237 raise Exception("Not fully connected")
ae3ad328
JM
238 if status['bssid'] != apdev[0]['bssid']:
239 raise Exception("Unexpected BSSID")
302b7a1b
JM
240 if status['ssid'] != ssid:
241 raise Exception("Unexpected SSID")
242 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
243 raise Exception("Unexpected encryption configuration")
244 if status['key_mgmt'] != 'WPA2-PSK':
245 raise Exception("Unexpected key_mgmt")
246
097cd9cd
JM
247 sta = hapd.get_sta(dev[0].p2p_interface_addr())
248 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
249 raise Exception("Device name not available in STA command")
250
daad14cc
JM
251def test_ap_wps_conf_5ghz(dev, apdev):
252 """WPS PBC provisioning with configured AP on 5 GHz band"""
253 try:
9d7fdac5 254 hapd = None
daad14cc 255 ssid = "test-wps-conf"
fab49f61
JM
256 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
257 "wpa_passphrase": "12345678", "wpa": "2",
258 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
259 "country_code": "FI", "hw_mode": "a", "channel": "36"}
8b8a1864 260 hapd = hostapd.add_ap(apdev[0], params)
daad14cc
JM
261 logger.info("WPS provisioning step")
262 hapd.request("WPS_PBC")
33d0b157
JM
263 dev[0].scan_for_bss(apdev[0]['bssid'], freq="5180")
264 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 265 dev[0].wait_connected(timeout=30)
daad14cc
JM
266
267 sta = hapd.get_sta(dev[0].p2p_interface_addr())
268 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
269 raise Exception("Device name not available in STA command")
270 finally:
9d7fdac5 271 dev[0].request("DISCONNECT")
cb5f7f55 272 clear_regdom(hapd, dev)
daad14cc
JM
273
274def test_ap_wps_conf_chan14(dev, apdev):
275 """WPS PBC provisioning with configured AP on channel 14"""
276 try:
9d7fdac5 277 hapd = None
daad14cc 278 ssid = "test-wps-conf"
fab49f61
JM
279 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
280 "wpa_passphrase": "12345678", "wpa": "2",
281 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
282 "country_code": "JP", "hw_mode": "b", "channel": "14"}
8b8a1864 283 hapd = hostapd.add_ap(apdev[0], params)
daad14cc
JM
284 logger.info("WPS provisioning step")
285 hapd.request("WPS_PBC")
286 dev[0].request("WPS_PBC")
5f35a5e2 287 dev[0].wait_connected(timeout=30)
daad14cc
JM
288
289 sta = hapd.get_sta(dev[0].p2p_interface_addr())
290 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
291 raise Exception("Device name not available in STA command")
292 finally:
9d7fdac5 293 dev[0].request("DISCONNECT")
207fe29d 294 clear_regdom(hapd, dev)
daad14cc 295
9fd6804d 296@remote_compatible
04e62788
JM
297def test_ap_wps_twice(dev, apdev):
298 """WPS provisioning with twice to change passphrase"""
299 ssid = "test-wps-twice"
fab49f61
JM
300 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
301 "wpa_passphrase": "12345678", "wpa": "2",
302 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
01703a9f 303 hapd = hostapd.add_ap(apdev[0], params)
04e62788
JM
304 logger.info("WPS provisioning step")
305 hapd.request("WPS_PBC")
33d0b157 306 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
04e62788 307 dev[0].dump_monitor()
33d0b157 308 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 309 dev[0].wait_connected(timeout=30)
04e62788
JM
310 dev[0].request("DISCONNECT")
311
312 logger.info("Restart AP with different passphrase and re-run WPS")
01703a9f 313 hostapd.remove_bss(apdev[0])
04e62788 314 params['wpa_passphrase'] = 'another passphrase'
01703a9f 315 hapd = hostapd.add_ap(apdev[0], params)
04e62788
JM
316 logger.info("WPS provisioning step")
317 hapd.request("WPS_PBC")
318 dev[0].dump_monitor()
33d0b157 319 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 320 dev[0].wait_connected(timeout=30)
04e62788
JM
321 networks = dev[0].list_networks()
322 if len(networks) > 1:
323 raise Exception("Unexpected duplicated network block present")
324
9fd6804d 325@remote_compatible
d658205a
JM
326def test_ap_wps_incorrect_pin(dev, apdev):
327 """WPS PIN provisioning with incorrect PIN"""
328 ssid = "test-wps-incorrect-pin"
6f334bf7 329 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
330 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
331 "wpa_passphrase": "12345678", "wpa": "2",
332 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
d658205a
JM
333
334 logger.info("WPS provisioning attempt 1")
335 hapd.request("WPS_PIN any 12345670")
33d0b157 336 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
d658205a 337 dev[0].dump_monitor()
33d0b157 338 dev[0].request("WPS_PIN %s 55554444" % apdev[0]['bssid'])
d658205a
JM
339 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
340 if ev is None:
341 raise Exception("WPS operation timed out")
342 if "config_error=18" not in ev:
343 raise Exception("Incorrect config_error reported")
344 if "msg=8" not in ev:
345 raise Exception("PIN error detected on incorrect message")
5f35a5e2 346 dev[0].wait_disconnected(timeout=10)
d658205a
JM
347 dev[0].request("WPS_CANCEL")
348 # if a scan was in progress, wait for it to complete before trying WPS again
349 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
350
d671a420
JM
351 status = hapd.request("WPS_GET_STATUS")
352 if "Last WPS result: Failed" not in status:
353 raise Exception("WPS failure result not shown correctly")
354
d658205a
JM
355 logger.info("WPS provisioning attempt 2")
356 hapd.request("WPS_PIN any 12345670")
357 dev[0].dump_monitor()
33d0b157 358 dev[0].request("WPS_PIN %s 12344444" % apdev[0]['bssid'])
d658205a
JM
359 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
360 if ev is None:
361 raise Exception("WPS operation timed out")
362 if "config_error=18" not in ev:
363 raise Exception("Incorrect config_error reported")
364 if "msg=10" not in ev:
365 raise Exception("PIN error detected on incorrect message")
5f35a5e2 366 dev[0].wait_disconnected(timeout=10)
d658205a 367
9fd6804d 368@remote_compatible
ae3ad328 369def test_ap_wps_conf_pin(dev, apdev):
302b7a1b
JM
370 """WPS PIN provisioning with configured AP"""
371 ssid = "test-wps-conf-pin"
6f334bf7 372 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
373 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
374 "wpa_passphrase": "12345678", "wpa": "2",
375 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
302b7a1b
JM
376 logger.info("WPS provisioning step")
377 pin = dev[0].wps_read_pin()
378 hapd.request("WPS_PIN any " + pin)
33d0b157 379 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 380 dev[0].dump_monitor()
33d0b157 381 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 382 dev[0].wait_connected(timeout=30)
302b7a1b 383 status = dev[0].get_status()
ae3ad328 384 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
385 raise Exception("Not fully connected")
386 if status['ssid'] != ssid:
387 raise Exception("Unexpected SSID")
388 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
389 raise Exception("Unexpected encryption configuration")
390 if status['key_mgmt'] != 'WPA2-PSK':
391 raise Exception("Unexpected key_mgmt")
392
84a40841 393 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
362ba6de
JM
394 bss = dev[1].get_bss(apdev[0]['bssid'])
395 if "[WPS-AUTH]" in bss['flags']:
396 raise Exception("WPS-AUTH flag not cleared")
a60a6d6b 397 logger.info("Try to connect from another station using the same PIN")
33d0b157 398 pin = dev[1].request("WPS_PIN " + apdev[0]['bssid'])
fab49f61 399 ev = dev[1].wait_event(["WPS-M2D", "CTRL-EVENT-CONNECTED"], timeout=30)
a60a6d6b
JM
400 if ev is None:
401 raise Exception("Operation timed out")
402 if "WPS-M2D" not in ev:
403 raise Exception("Unexpected WPS operation started")
6e12eaa4 404 hapd.request("WPS_PIN any " + pin)
5f35a5e2 405 dev[1].wait_connected(timeout=30)
362ba6de 406
ff518fbd
JM
407def test_ap_wps_conf_pin_mixed_mode(dev, apdev):
408 """WPS PIN provisioning with configured AP (WPA+WPA2)"""
409 ssid = "test-wps-conf-pin-mixed"
6f334bf7 410 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
411 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
412 "wpa_passphrase": "12345678", "wpa": "3",
413 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
414 "wpa_pairwise": "TKIP"})
ff518fbd
JM
415
416 logger.info("WPS provisioning step")
417 pin = dev[0].wps_read_pin()
418 hapd.request("WPS_PIN any " + pin)
419 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
420 dev[0].dump_monitor()
421 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
422 dev[0].wait_connected(timeout=30)
423 status = dev[0].get_status()
424 dev[0].request("REMOVE_NETWORK all")
425 dev[0].wait_disconnected()
426 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
427 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
428
429 logger.info("WPS provisioning step (auth_types=0x1b)")
430 if "OK" not in dev[0].request("SET wps_force_auth_types 0x1b"):
431 raise Exception("Failed to set wps_force_auth_types 0x1b")
432 pin = dev[0].wps_read_pin()
433 hapd.request("WPS_PIN any " + pin)
434 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
435 dev[0].dump_monitor()
436 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
437 dev[0].wait_connected(timeout=30)
438 status = dev[0].get_status()
439 dev[0].request("REMOVE_NETWORK all")
440 dev[0].wait_disconnected()
441 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
442 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
443
444 logger.info("WPS provisioning step (auth_types=0 encr_types=0)")
445 if "OK" not in dev[0].request("SET wps_force_auth_types 0"):
446 raise Exception("Failed to set wps_force_auth_types 0")
447 if "OK" not in dev[0].request("SET wps_force_encr_types 0"):
448 raise Exception("Failed to set wps_force_encr_types 0")
449 pin = dev[0].wps_read_pin()
450 hapd.request("WPS_PIN any " + pin)
451 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
452 dev[0].dump_monitor()
453 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
454 dev[0].wait_connected(timeout=30)
455 status = dev[0].get_status()
456 dev[0].request("REMOVE_NETWORK all")
457 dev[0].wait_disconnected()
458 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
459 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
460
461 dev[0].request("SET wps_force_auth_types ")
462 dev[0].request("SET wps_force_encr_types ")
463
9fd6804d 464@remote_compatible
6257f9c0
JM
465def test_ap_wps_conf_pin_v1(dev, apdev):
466 """WPS PIN provisioning with configured WPS v1.0 AP"""
467 ssid = "test-wps-conf-pin-v1"
6f334bf7 468 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
469 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
470 "wpa_passphrase": "12345678", "wpa": "2",
471 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
6257f9c0
JM
472 logger.info("WPS provisioning step")
473 pin = dev[0].wps_read_pin()
474 hapd.request("SET wps_version_number 0x10")
475 hapd.request("WPS_PIN any " + pin)
476 found = False
477 for i in range(0, 10):
478 dev[0].scan(freq="2412")
479 if "[WPS-PIN]" in dev[0].request("SCAN_RESULTS"):
480 found = True
481 break
482 if not found:
483 hapd.request("SET wps_version_number 0x20")
484 raise Exception("WPS-PIN flag not seen in scan results")
485 dev[0].dump_monitor()
33d0b157 486 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 487 dev[0].wait_connected(timeout=30)
6257f9c0 488 hapd.request("SET wps_version_number 0x20")
6257f9c0 489
9fd6804d 490@remote_compatible
e9129860
JM
491def test_ap_wps_conf_pin_2sta(dev, apdev):
492 """Two stations trying to use WPS PIN at the same time"""
493 ssid = "test-wps-conf-pin2"
6f334bf7 494 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
495 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
496 "wpa_passphrase": "12345678", "wpa": "2",
497 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e9129860
JM
498 logger.info("WPS provisioning step")
499 pin = "12345670"
500 pin2 = "55554444"
501 hapd.request("WPS_PIN " + dev[0].get_status_field("uuid") + " " + pin)
502 hapd.request("WPS_PIN " + dev[1].get_status_field("uuid") + " " + pin)
e9129860 503 dev[0].dump_monitor()
e9129860 504 dev[1].dump_monitor()
33d0b157
JM
505 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
506 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
507 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
508 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2
JM
509 dev[0].wait_connected(timeout=30)
510 dev[1].wait_connected(timeout=30)
0489e880 511
9fd6804d 512@remote_compatible
0489e880
JM
513def test_ap_wps_conf_pin_timeout(dev, apdev):
514 """WPS PIN provisioning with configured AP timing out PIN"""
515 ssid = "test-wps-conf-pin"
6f334bf7 516 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
517 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
518 "wpa_passphrase": "12345678", "wpa": "2",
519 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
0489e880
JM
520 addr = dev[0].p2p_interface_addr()
521 pin = dev[0].wps_read_pin()
522 if "FAIL" not in hapd.request("WPS_PIN "):
523 raise Exception("Unexpected success on invalid WPS_PIN")
524 hapd.request("WPS_PIN any " + pin + " 1")
33d0b157 525 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
0489e880 526 time.sleep(1.1)
33d0b157 527 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
0489e880
JM
528 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=20)
529 if ev is None:
530 raise Exception("WPS-PIN-NEEDED event timed out")
531 ev = dev[0].wait_event(["WPS-M2D"])
532 if ev is None:
533 raise Exception("M2D not reported")
534 dev[0].request("WPS_CANCEL")
535
536 hapd.request("WPS_PIN any " + pin + " 20 " + addr)
33d0b157 537 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 538 dev[0].wait_connected(timeout=30)
e9129860 539
ae3ad328 540def test_ap_wps_reg_connect(dev, apdev):
302b7a1b 541 """WPS registrar using AP PIN to connect"""
803edd1c 542 ssid = "test-wps-reg-ap-pin"
302b7a1b 543 appin = "12345670"
8b8a1864 544 hostapd.add_ap(apdev[0],
fab49f61
JM
545 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
546 "wpa_passphrase": "12345678", "wpa": "2",
547 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
548 "ap_pin": appin})
302b7a1b 549 logger.info("WPS provisioning step")
302b7a1b 550 dev[0].dump_monitor()
33d0b157 551 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 552 dev[0].wps_reg(apdev[0]['bssid'], appin)
302b7a1b 553 status = dev[0].get_status()
ae3ad328 554 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
555 raise Exception("Not fully connected")
556 if status['ssid'] != ssid:
557 raise Exception("Unexpected SSID")
558 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
559 raise Exception("Unexpected encryption configuration")
560 if status['key_mgmt'] != 'WPA2-PSK':
561 raise Exception("Unexpected key_mgmt")
562
d33222d1
JM
563def test_ap_wps_reg_connect_zero_len_ap_pin(dev, apdev):
564 """hostapd with zero length ap_pin parameter"""
565 ssid = "test-wps-reg-ap-pin"
566 appin = ""
567 hostapd.add_ap(apdev[0],
fab49f61
JM
568 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
569 "wpa_passphrase": "12345678", "wpa": "2",
570 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
571 "ap_pin": appin})
d33222d1
JM
572 logger.info("WPS provisioning step")
573 dev[0].dump_monitor()
574 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
575 dev[0].wps_reg(apdev[0]['bssid'], appin, no_wait=True)
576 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
577 if ev is None:
578 raise Exception("No WPS-FAIL reported")
579 if "msg=5 config_error=15" not in ev:
580 raise Exception("Unexpected WPS-FAIL: " + ev)
581
e60be3b3
JM
582def test_ap_wps_reg_connect_mixed_mode(dev, apdev):
583 """WPS registrar using AP PIN to connect (WPA+WPA2)"""
584 ssid = "test-wps-reg-ap-pin"
585 appin = "12345670"
8b8a1864 586 hostapd.add_ap(apdev[0],
fab49f61
JM
587 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
588 "wpa_passphrase": "12345678", "wpa": "3",
589 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
590 "wpa_pairwise": "TKIP", "ap_pin": appin})
e60be3b3
JM
591 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
592 dev[0].wps_reg(apdev[0]['bssid'], appin)
593 status = dev[0].get_status()
594 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
595 raise Exception("Not fully connected")
596 if status['ssid'] != ssid:
597 raise Exception("Unexpected SSID")
598 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
599 raise Exception("Unexpected encryption configuration")
600 if status['key_mgmt'] != 'WPA2-PSK':
601 raise Exception("Unexpected key_mgmt")
602
7511ead0
JM
603def test_ap_wps_reg_override_ap_settings(dev, apdev):
604 """WPS registrar and ap_settings override"""
605 ap_settings = "/tmp/ap_wps_reg_override_ap_settings"
606 try:
607 os.remove(ap_settings)
608 except:
609 pass
610 # Override AP Settings with values that point to another AP
15dfcb69
MH
611 data = build_wsc_attr(ATTR_NETWORK_INDEX, b'\x01')
612 data += build_wsc_attr(ATTR_SSID, b"test")
613 data += build_wsc_attr(ATTR_AUTH_TYPE, b'\x00\x01')
614 data += build_wsc_attr(ATTR_ENCR_TYPE, b'\x00\x01')
615 data += build_wsc_attr(ATTR_NETWORK_KEY, b'')
7511ead0 616 data += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[1]['bssid'].replace(':', '')))
4aa2336e 617 with open(ap_settings, "wb") as f:
7511ead0
JM
618 f.write(data)
619 ssid = "test-wps-reg-ap-pin"
620 appin = "12345670"
8b8a1864 621 hostapd.add_ap(apdev[0],
fab49f61
JM
622 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
623 "wpa_passphrase": "12345678", "wpa": "2",
624 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
625 "ap_pin": appin, "ap_settings": ap_settings})
626 hapd2 = hostapd.add_ap(apdev[1], {"ssid": "test"})
7511ead0
JM
627 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
628 dev[0].scan_for_bss(apdev[1]['bssid'], freq=2412)
629 dev[0].wps_reg(apdev[0]['bssid'], appin)
630 ev = hapd2.wait_event(['AP-STA-CONNECTED'], timeout=10)
631 os.remove(ap_settings)
632 if ev is None:
633 raise Exception("No connection with the other AP")
634
9488858f
JM
635def check_wps_reg_failure(dev, ap, appin):
636 dev.request("WPS_REG " + ap['bssid'] + " " + appin)
637 ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
638 if ev is None:
639 raise Exception("WPS operation timed out")
640 if "WPS-SUCCESS" in ev:
641 raise Exception("WPS operation succeeded unexpectedly")
642 if "config_error=15" not in ev:
643 raise Exception("WPS setup locked state was not reported correctly")
644
e4357b19
JM
645def test_ap_wps_random_ap_pin(dev, apdev):
646 """WPS registrar using random AP PIN"""
647 ssid = "test-wps-reg-random-ap-pin"
648 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
fab49f61
JM
649 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
650 "wpa_passphrase": "12345678", "wpa": "2",
651 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
652 "device_name": "Wireless AP", "manufacturer": "Company",
653 "model_name": "WAP", "model_number": "123",
654 "serial_number": "12345", "device_type": "6-0050F204-1",
655 "os_version": "01020300",
656 "config_methods": "label push_button",
657 "uuid": ap_uuid, "upnp_iface": "lo"}
6f334bf7 658 hapd = hostapd.add_ap(apdev[0], params)
e4357b19
JM
659 appin = hapd.request("WPS_AP_PIN random")
660 if "FAIL" in appin:
661 raise Exception("Could not generate random AP PIN")
662 if appin not in hapd.request("WPS_AP_PIN get"):
663 raise Exception("Could not fetch current AP PIN")
664 logger.info("WPS provisioning step")
33d0b157 665 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
e4357b19
JM
666 dev[0].wps_reg(apdev[0]['bssid'], appin)
667
668 hapd.request("WPS_AP_PIN disable")
669 logger.info("WPS provisioning step with AP PIN disabled")
33d0b157 670 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
9488858f
JM
671 check_wps_reg_failure(dev[1], apdev[0], appin)
672
673 logger.info("WPS provisioning step with AP PIN reset")
674 appin = "12345670"
675 hapd.request("WPS_AP_PIN set " + appin)
676 dev[1].wps_reg(apdev[0]['bssid'], appin)
677 dev[0].request("REMOVE_NETWORK all")
678 dev[1].request("REMOVE_NETWORK all")
5f35a5e2
JM
679 dev[0].wait_disconnected(timeout=10)
680 dev[1].wait_disconnected(timeout=10)
9488858f
JM
681
682 logger.info("WPS provisioning step after AP PIN timeout")
683 hapd.request("WPS_AP_PIN disable")
684 appin = hapd.request("WPS_AP_PIN random 1")
685 time.sleep(1.1)
686 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
687 raise Exception("AP PIN unexpectedly still enabled")
688 check_wps_reg_failure(dev[0], apdev[0], appin)
689
690 logger.info("WPS provisioning step after AP PIN timeout(2)")
691 hapd.request("WPS_AP_PIN disable")
692 appin = "12345670"
693 hapd.request("WPS_AP_PIN set " + appin + " 1")
694 time.sleep(1.1)
695 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
696 raise Exception("AP PIN unexpectedly still enabled")
697 check_wps_reg_failure(dev[1], apdev[0], appin)
e4357b19 698
24b7f282 699 with fail_test(hapd, 1, "os_get_random;wps_generate_pin"):
20c48fd9 700 hapd.request("WPS_AP_PIN random 1")
24b7f282
JM
701 hapd.request("WPS_AP_PIN disable")
702
703 with alloc_fail(hapd, 1, "upnp_wps_set_ap_pin"):
704 hapd.request("WPS_AP_PIN set 12345670")
705 hapd.request("WPS_AP_PIN disable")
706
82358a2a
JM
707 if "FAIL" not in hapd.request("WPS_AP_PIN set"):
708 raise Exception("Invalid WPS_AP_PIN accepted")
709 if "FAIL" not in hapd.request("WPS_AP_PIN foo"):
710 raise Exception("Invalid WPS_AP_PIN accepted")
711
ae3ad328 712def test_ap_wps_reg_config(dev, apdev):
4b727c5c 713 """WPS registrar configuring an AP using AP PIN"""
302b7a1b
JM
714 ssid = "test-wps-init-ap-pin"
715 appin = "12345670"
8b8a1864 716 hostapd.add_ap(apdev[0],
fab49f61
JM
717 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
718 "ap_pin": appin})
302b7a1b 719 logger.info("WPS configuration step")
33d0b157 720 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
302b7a1b
JM
721 dev[0].dump_monitor()
722 new_ssid = "wps-new-ssid"
723 new_passphrase = "1234567890"
6edaee9c
JM
724 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
725 new_passphrase)
302b7a1b 726 status = dev[0].get_status()
ae3ad328 727 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
728 raise Exception("Not fully connected")
729 if status['ssid'] != new_ssid:
730 raise Exception("Unexpected SSID")
731 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
732 raise Exception("Unexpected encryption configuration")
733 if status['key_mgmt'] != 'WPA2-PSK':
734 raise Exception("Unexpected key_mgmt")
735
375afd7c
JM
736 logger.info("Re-configure back to open")
737 dev[0].request("REMOVE_NETWORK all")
243dcc4a 738 dev[0].flush_scan_cache()
375afd7c
JM
739 dev[0].dump_monitor()
740 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-open", "OPEN", "NONE", "")
741 status = dev[0].get_status()
742 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
743 raise Exception("Not fully connected")
744 if status['ssid'] != "wps-open":
745 raise Exception("Unexpected SSID")
746 if status['key_mgmt'] != 'NONE':
747 raise Exception("Unexpected key_mgmt")
748
4b727c5c
JM
749def test_ap_wps_reg_config_ext_processing(dev, apdev):
750 """WPS registrar configuring an AP with external config processing"""
751 ssid = "test-wps-init-ap-pin"
752 appin = "12345670"
fab49f61
JM
753 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
754 "wps_cred_processing": "1", "ap_pin": appin}
8b8a1864 755 hapd = hostapd.add_ap(apdev[0], params)
33d0b157 756 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
4b727c5c
JM
757 new_ssid = "wps-new-ssid"
758 new_passphrase = "1234567890"
759 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
760 new_passphrase, no_wait=True)
761 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
762 if ev is None:
763 raise Exception("WPS registrar operation timed out")
764 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=15)
765 if ev is None:
766 raise Exception("WPS configuration timed out")
767 if "1026" not in ev:
768 raise Exception("AP Settings missing from event")
769 hapd.request("SET wps_cred_processing 0")
54c58f29 770 if "FAIL" in hapd.request("WPS_CONFIG " + binascii.hexlify(new_ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(new_passphrase.encode()).decode()):
4b727c5c 771 raise Exception("WPS_CONFIG command failed")
5f35a5e2 772 dev[0].wait_connected(timeout=15)
4b727c5c 773
eeefe187
JM
774def test_ap_wps_reg_config_tkip(dev, apdev):
775 """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
a1eabc74 776 skip_with_fips(dev[0])
eeefe187
JM
777 ssid = "test-wps-init-ap"
778 appin = "12345670"
8b8a1864 779 hostapd.add_ap(apdev[0],
fab49f61
JM
780 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
781 "ap_pin": appin})
eeefe187 782 logger.info("WPS configuration step")
eeefe187 783 dev[0].request("SET wps_version_number 0x10")
33d0b157 784 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
eeefe187
JM
785 dev[0].dump_monitor()
786 new_ssid = "wps-new-ssid-with-tkip"
787 new_passphrase = "1234567890"
788 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
789 new_passphrase)
790 logger.info("Re-connect to verify WPA2 mixed mode")
791 dev[0].request("DISCONNECT")
792 id = 0
793 dev[0].set_network(id, "pairwise", "CCMP")
794 dev[0].set_network(id, "proto", "RSN")
795 dev[0].connect_network(id)
796 status = dev[0].get_status()
797 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
3c086180 798 raise Exception("Not fully connected: wpa_state={} bssid={}".format(status['wpa_state'], status['bssid']))
eeefe187
JM
799 if status['ssid'] != new_ssid:
800 raise Exception("Unexpected SSID")
801 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
802 raise Exception("Unexpected encryption configuration")
803 if status['key_mgmt'] != 'WPA2-PSK':
804 raise Exception("Unexpected key_mgmt")
805
6645ff50
JM
806def test_ap_wps_setup_locked(dev, apdev):
807 """WPS registrar locking up AP setup on AP PIN failures"""
808 ssid = "test-wps-incorrect-ap-pin"
809 appin = "12345670"
6f334bf7 810 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
811 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
812 "wpa_passphrase": "12345678", "wpa": "2",
813 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
814 "ap_pin": appin})
6645ff50
JM
815 new_ssid = "wps-new-ssid-test"
816 new_passphrase = "1234567890"
817
33d0b157 818 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
fab49f61 819 ap_setup_locked = False
6645ff50
JM
820 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
821 dev[0].dump_monitor()
822 logger.info("Try incorrect AP PIN - attempt " + pin)
823 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
824 "CCMP", new_passphrase, no_wait=True)
825 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
826 if ev is None:
827 raise Exception("Timeout on receiving WPS operation failure event")
828 if "CTRL-EVENT-CONNECTED" in ev:
829 raise Exception("Unexpected connection")
830 if "config_error=15" in ev:
831 logger.info("AP Setup Locked")
fab49f61 832 ap_setup_locked = True
6645ff50
JM
833 elif "config_error=18" not in ev:
834 raise Exception("config_error=18 not reported")
5f35a5e2 835 dev[0].wait_disconnected(timeout=10)
6645ff50
JM
836 time.sleep(0.1)
837 if not ap_setup_locked:
838 raise Exception("AP setup was not locked")
24b7f282
JM
839 dev[0].request("WPS_CANCEL")
840 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True,
841 only_new=True)
842 bss = dev[0].get_bss(apdev[0]['bssid'])
843 if 'wps_ap_setup_locked' not in bss or bss['wps_ap_setup_locked'] != '1':
844 logger.info("BSS: " + str(bss))
845 raise Exception("AP Setup Locked not indicated in scan results")
6645ff50 846
d671a420
JM
847 status = hapd.request("WPS_GET_STATUS")
848 if "Last WPS result: Failed" not in status:
849 raise Exception("WPS failure result not shown correctly")
850 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
851 raise Exception("Peer address not shown correctly")
852
6645ff50
JM
853 time.sleep(0.5)
854 dev[0].dump_monitor()
855 logger.info("WPS provisioning step")
856 pin = dev[0].wps_read_pin()
6645ff50 857 hapd.request("WPS_PIN any " + pin)
33d0b157 858 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
6645ff50
JM
859 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
860 if ev is None:
861 raise Exception("WPS success was not reported")
5f35a5e2 862 dev[0].wait_connected(timeout=30)
6645ff50 863
c1cec68b
JM
864 appin = hapd.request("WPS_AP_PIN random")
865 if "FAIL" in appin:
866 raise Exception("Could not generate random AP PIN")
867 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=10)
868 if ev is None:
869 raise Exception("Failed to unlock AP PIN")
870
33c9b8d8
JM
871def test_ap_wps_setup_locked_timeout(dev, apdev):
872 """WPS re-enabling AP PIN after timeout"""
873 ssid = "test-wps-incorrect-ap-pin"
874 appin = "12345670"
6f334bf7 875 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
876 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
877 "wpa_passphrase": "12345678", "wpa": "2",
878 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
879 "ap_pin": appin})
33c9b8d8
JM
880 new_ssid = "wps-new-ssid-test"
881 new_passphrase = "1234567890"
882
33d0b157 883 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
fab49f61 884 ap_setup_locked = False
33c9b8d8
JM
885 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
886 dev[0].dump_monitor()
887 logger.info("Try incorrect AP PIN - attempt " + pin)
888 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
889 "CCMP", new_passphrase, no_wait=True)
9ed53f5e 890 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"], timeout=15)
33c9b8d8
JM
891 if ev is None:
892 raise Exception("Timeout on receiving WPS operation failure event")
893 if "CTRL-EVENT-CONNECTED" in ev:
894 raise Exception("Unexpected connection")
895 if "config_error=15" in ev:
896 logger.info("AP Setup Locked")
fab49f61 897 ap_setup_locked = True
33c9b8d8
JM
898 break
899 elif "config_error=18" not in ev:
900 raise Exception("config_error=18 not reported")
5f35a5e2 901 dev[0].wait_disconnected(timeout=10)
33c9b8d8
JM
902 time.sleep(0.1)
903 if not ap_setup_locked:
904 raise Exception("AP setup was not locked")
33c9b8d8
JM
905 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=80)
906 if ev is None:
907 raise Exception("AP PIN did not get unlocked on 60 second timeout")
908
4c355e3e
JM
909def test_ap_wps_setup_locked_2(dev, apdev):
910 """WPS AP configured for special ap_setup_locked=2 mode"""
911 ssid = "test-wps-ap-pin"
912 appin = "12345670"
fab49f61
JM
913 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
914 "wpa_passphrase": "12345678", "wpa": "2",
915 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
916 "ap_pin": appin, "ap_setup_locked": "2"}
8b8a1864 917 hapd = hostapd.add_ap(apdev[0], params)
4c355e3e
JM
918 new_ssid = "wps-new-ssid-test"
919 new_passphrase = "1234567890"
920
921 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
922 dev[0].wps_reg(apdev[0]['bssid'], appin)
923 dev[0].request("REMOVE_NETWORK all")
924 dev[0].wait_disconnected()
925
926 hapd.dump_monitor()
927 dev[0].dump_monitor()
928 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK",
929 "CCMP", new_passphrase, no_wait=True)
930
931 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
932 if ev is None:
933 raise Exception("hostapd did not report WPS failure")
934 if "msg=12 config_error=15" not in ev:
935 raise Exception("Unexpected failure reason (AP): " + ev)
936
937 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
938 if ev is None:
939 raise Exception("Timeout on receiving WPS operation failure event")
940 if "CTRL-EVENT-CONNECTED" in ev:
941 raise Exception("Unexpected connection")
942 if "config_error=15" not in ev:
943 raise Exception("Unexpected failure reason (STA): " + ev)
944 dev[0].request("WPS_CANCEL")
945 dev[0].wait_disconnected()
946
9fd6804d 947@remote_compatible
ae3ad328 948def test_ap_wps_pbc_overlap_2ap(dev, apdev):
302b7a1b 949 """WPS PBC session overlap with two active APs"""
fab49f61
JM
950 params = {"ssid": "wps1", "eap_server": "1", "wps_state": "2",
951 "wpa_passphrase": "12345678", "wpa": "2",
952 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
953 "wps_independent": "1"}
6f334bf7 954 hapd = hostapd.add_ap(apdev[0], params)
fab49f61
JM
955 params = {"ssid": "wps2", "eap_server": "1", "wps_state": "2",
956 "wpa_passphrase": "123456789", "wpa": "2",
957 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
958 "wps_independent": "1"}
6f334bf7 959 hapd2 = hostapd.add_ap(apdev[1], params)
302b7a1b 960 hapd.request("WPS_PBC")
302b7a1b
JM
961 hapd2.request("WPS_PBC")
962 logger.info("WPS provisioning step")
84a40841
JM
963 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
964 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
302b7a1b
JM
965 dev[0].request("WPS_PBC")
966 ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
967 if ev is None:
968 raise Exception("PBC session overlap not detected")
492c3a91
JM
969 hapd.request("DISABLE")
970 hapd2.request("DISABLE")
971 dev[0].flush_scan_cache()
302b7a1b 972
9fd6804d 973@remote_compatible
ae3ad328 974def test_ap_wps_pbc_overlap_2sta(dev, apdev):
302b7a1b
JM
975 """WPS PBC session overlap with two active STAs"""
976 ssid = "test-wps-pbc-overlap"
6f334bf7 977 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
978 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
979 "wpa_passphrase": "12345678", "wpa": "2",
980 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
302b7a1b
JM
981 logger.info("WPS provisioning step")
982 hapd.request("WPS_PBC")
33d0b157 983 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 984 dev[0].dump_monitor()
33d0b157 985 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 986 dev[1].dump_monitor()
33d0b157
JM
987 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
988 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
302b7a1b
JM
989 ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
990 if ev is None:
991 raise Exception("PBC session overlap not detected (dev0)")
992 if "config_error=12" not in ev:
993 raise Exception("PBC session overlap not correctly reported (dev0)")
492c3a91
JM
994 dev[0].request("WPS_CANCEL")
995 dev[0].request("DISCONNECT")
302b7a1b
JM
996 ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
997 if ev is None:
998 raise Exception("PBC session overlap not detected (dev1)")
999 if "config_error=12" not in ev:
1000 raise Exception("PBC session overlap not correctly reported (dev1)")
492c3a91
JM
1001 dev[1].request("WPS_CANCEL")
1002 dev[1].request("DISCONNECT")
11e7eeba
JM
1003 hapd.request("WPS_CANCEL")
1004 ret = hapd.request("WPS_PBC")
1005 if "FAIL" not in ret:
1006 raise Exception("PBC mode allowed to be started while PBC overlap still active")
492c3a91
JM
1007 hapd.request("DISABLE")
1008 dev[0].flush_scan_cache()
1009 dev[1].flush_scan_cache()
6edaee9c 1010
9fd6804d 1011@remote_compatible
71afe834
JM
1012def test_ap_wps_cancel(dev, apdev):
1013 """WPS AP cancelling enabled config method"""
1014 ssid = "test-wps-ap-cancel"
6f334bf7 1015 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
1016 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1017 "wpa_passphrase": "12345678", "wpa": "2",
1018 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
71afe834 1019 bssid = apdev[0]['bssid']
71afe834
JM
1020
1021 logger.info("Verify PBC enable/cancel")
1022 hapd.request("WPS_PBC")
71afe834 1023 dev[0].scan(freq="2412")
84a40841 1024 dev[0].scan(freq="2412")
71afe834
JM
1025 bss = dev[0].get_bss(apdev[0]['bssid'])
1026 if "[WPS-PBC]" not in bss['flags']:
1027 raise Exception("WPS-PBC flag missing")
1028 if "FAIL" in hapd.request("WPS_CANCEL"):
1029 raise Exception("WPS_CANCEL failed")
1030 dev[0].scan(freq="2412")
84a40841 1031 dev[0].scan(freq="2412")
71afe834
JM
1032 bss = dev[0].get_bss(apdev[0]['bssid'])
1033 if "[WPS-PBC]" in bss['flags']:
1034 raise Exception("WPS-PBC flag not cleared")
1035
1036 logger.info("Verify PIN enable/cancel")
1037 hapd.request("WPS_PIN any 12345670")
1038 dev[0].scan(freq="2412")
84a40841 1039 dev[0].scan(freq="2412")
71afe834
JM
1040 bss = dev[0].get_bss(apdev[0]['bssid'])
1041 if "[WPS-AUTH]" not in bss['flags']:
1042 raise Exception("WPS-AUTH flag missing")
1043 if "FAIL" in hapd.request("WPS_CANCEL"):
1044 raise Exception("WPS_CANCEL failed")
1045 dev[0].scan(freq="2412")
84a40841 1046 dev[0].scan(freq="2412")
71afe834
JM
1047 bss = dev[0].get_bss(apdev[0]['bssid'])
1048 if "[WPS-AUTH]" in bss['flags']:
1049 raise Exception("WPS-AUTH flag not cleared")
1050
6edaee9c
JM
1051def test_ap_wps_er_add_enrollee(dev, apdev):
1052 """WPS ER configuring AP and adding a new enrollee using PIN"""
be9f1562
JM
1053 try:
1054 _test_ap_wps_er_add_enrollee(dev, apdev)
1055 finally:
1056 dev[0].request("WPS_ER_STOP")
1057
1058def _test_ap_wps_er_add_enrollee(dev, apdev):
6edaee9c
JM
1059 ssid = "wps-er-add-enrollee"
1060 ap_pin = "12345670"
1061 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1062 hostapd.add_ap(apdev[0],
fab49f61
JM
1063 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
1064 "device_name": "Wireless AP", "manufacturer": "Company",
1065 "model_name": "WAP", "model_number": "123",
1066 "serial_number": "12345", "device_type": "6-0050F204-1",
1067 "os_version": "01020300",
1068 'friendly_name': "WPS AP - <>&'\" - TEST",
1069 "config_methods": "label push_button",
1070 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
6edaee9c
JM
1071 logger.info("WPS configuration step")
1072 new_passphrase = "1234567890"
1073 dev[0].dump_monitor()
33d0b157 1074 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c
JM
1075 dev[0].wps_reg(apdev[0]['bssid'], ap_pin, ssid, "WPA2PSK", "CCMP",
1076 new_passphrase)
1077 status = dev[0].get_status()
1078 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1079 raise Exception("Not fully connected")
1080 if status['ssid'] != ssid:
1081 raise Exception("Unexpected SSID")
1082 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
1083 raise Exception("Unexpected encryption configuration")
1084 if status['key_mgmt'] != 'WPA2-PSK':
1085 raise Exception("Unexpected key_mgmt")
1086
1087 logger.info("Start ER")
1088 dev[0].request("WPS_ER_START ifname=lo")
1089 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1090 if ev is None:
1091 raise Exception("AP discovery timed out")
1092 if ap_uuid not in ev:
1093 raise Exception("Expected AP UUID not found")
24b7f282
JM
1094 if "|WPS AP - &lt;&gt;&amp;&apos;&quot; - TEST|Company|" not in ev:
1095 raise Exception("Expected friendly name not found")
6edaee9c
JM
1096
1097 logger.info("Learn AP configuration through UPnP")
1098 dev[0].dump_monitor()
1099 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1100 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1101 if ev is None:
1102 raise Exception("AP learn timed out")
1103 if ap_uuid not in ev:
1104 raise Exception("Expected AP UUID not in settings")
1105 if "ssid=" + ssid not in ev:
1106 raise Exception("Expected SSID not in settings")
1107 if "key=" + new_passphrase not in ev:
1108 raise Exception("Expected passphrase not in settings")
33d0b157
JM
1109 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1110 if ev is None:
1111 raise Exception("WPS-FAIL after AP learn timed out")
1112 time.sleep(0.1)
6edaee9c
JM
1113
1114 logger.info("Add Enrollee using ER")
1115 pin = dev[1].wps_read_pin()
1116 dev[0].dump_monitor()
1117 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
33d0b157 1118 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 1119 dev[1].dump_monitor()
33d0b157 1120 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
846be889 1121 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
6edaee9c
JM
1122 if ev is None:
1123 raise Exception("Enrollee did not report success")
5f35a5e2 1124 dev[1].wait_connected(timeout=15)
6edaee9c
JM
1125 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1126 if ev is None:
1127 raise Exception("WPS ER did not report success")
1128 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1129
11c26f1b
JM
1130 logger.info("Add a specific Enrollee using ER")
1131 pin = dev[2].wps_read_pin()
1132 addr2 = dev[2].p2p_interface_addr()
1133 dev[0].dump_monitor()
33d0b157 1134 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
11c26f1b 1135 dev[2].dump_monitor()
33d0b157 1136 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
11c26f1b
JM
1137 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1138 if ev is None:
1139 raise Exception("Enrollee not seen")
1140 if addr2 not in ev:
1141 raise Exception("Unexpected Enrollee MAC address")
1142 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
5f35a5e2 1143 dev[2].wait_connected(timeout=30)
11c26f1b
JM
1144 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1145 if ev is None:
1146 raise Exception("WPS ER did not report success")
1147
38ae43de
JM
1148 logger.info("Verify registrar selection behavior")
1149 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1150 dev[1].request("DISCONNECT")
5f35a5e2 1151 dev[1].wait_disconnected(timeout=10)
84a40841 1152 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
38ae43de
JM
1153 dev[1].scan(freq="2412")
1154 bss = dev[1].get_bss(apdev[0]['bssid'])
1155 if "[WPS-AUTH]" not in bss['flags']:
321c7f60
JM
1156 # It is possible for scan to miss an update especially when running
1157 # tests under load with multiple VMs, so allow another attempt.
1158 dev[1].scan(freq="2412")
1159 bss = dev[1].get_bss(apdev[0]['bssid'])
1160 if "[WPS-AUTH]" not in bss['flags']:
1161 raise Exception("WPS-AUTH flag missing")
38ae43de
JM
1162
1163 logger.info("Stop ER")
1164 dev[0].dump_monitor()
1165 dev[0].request("WPS_ER_STOP")
1166 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
1167 if ev is None:
1168 raise Exception("WPS ER unsubscription timed out")
8697cbc0 1169 # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
befd671c 1170 # a bit before verifying that the scan results have changed.
8697cbc0 1171 time.sleep(0.2)
38ae43de 1172
befd671c
JM
1173 for i in range(0, 10):
1174 dev[1].request("BSS_FLUSH 0")
1175 dev[1].scan(freq="2412", only_new=True)
1176 bss = dev[1].get_bss(apdev[0]['bssid'])
1177 if bss and 'flags' in bss and "[WPS-AUTH]" not in bss['flags']:
1178 break
1179 logger.debug("WPS-AUTH flag was still in place - wait a bit longer")
1180 time.sleep(0.1)
38ae43de
JM
1181 if "[WPS-AUTH]" in bss['flags']:
1182 raise Exception("WPS-AUTH flag not removed")
1183
c965ae03
JM
1184def test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1185 """WPS ER adding a new enrollee identified by UUID"""
1186 try:
1187 _test_ap_wps_er_add_enrollee_uuid(dev, apdev)
1188 finally:
1189 dev[0].request("WPS_ER_STOP")
1190
1191def _test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1192 ssid = "wps-er-add-enrollee"
1193 ap_pin = "12345670"
1194 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1195 hostapd.add_ap(apdev[0],
fab49f61
JM
1196 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1197 "wpa_passphrase": "12345678", "wpa": "2",
1198 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1199 "device_name": "Wireless AP", "manufacturer": "Company",
1200 "model_name": "WAP", "model_number": "123",
1201 "serial_number": "12345", "device_type": "6-0050F204-1",
1202 "os_version": "01020300",
1203 "config_methods": "label push_button",
1204 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
c965ae03
JM
1205 logger.info("WPS configuration step")
1206 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1207 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1208
1209 logger.info("Start ER")
1210 dev[0].request("WPS_ER_START ifname=lo")
1211 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1212 if ev is None:
1213 raise Exception("AP discovery timed out")
1214 if ap_uuid not in ev:
1215 raise Exception("Expected AP UUID not found")
1216
1217 logger.info("Learn AP configuration through UPnP")
1218 dev[0].dump_monitor()
1219 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1220 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1221 if ev is None:
1222 raise Exception("AP learn timed out")
1223 if ap_uuid not in ev:
1224 raise Exception("Expected AP UUID not in settings")
1225 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1226 if ev is None:
1227 raise Exception("WPS-FAIL after AP learn timed out")
1228 time.sleep(0.1)
1229
1230 logger.info("Add a specific Enrollee using ER (PBC/UUID)")
1231 addr1 = dev[1].p2p_interface_addr()
1232 dev[0].dump_monitor()
1233 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1234 dev[1].dump_monitor()
1235 dev[1].request("WPS_PBC %s" % apdev[0]['bssid'])
1236 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1237 if ev is None:
1238 raise Exception("Enrollee not seen")
1239 if addr1 not in ev:
1240 raise Exception("Unexpected Enrollee MAC address")
1241 uuid = ev.split(' ')[1]
1242 dev[0].request("WPS_ER_PBC " + uuid)
1243 dev[1].wait_connected(timeout=30)
1244 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1245 if ev is None:
1246 raise Exception("WPS ER did not report success")
1247
1248 logger.info("Add a specific Enrollee using ER (PIN/UUID)")
1249 pin = dev[2].wps_read_pin()
1250 addr2 = dev[2].p2p_interface_addr()
1251 dev[0].dump_monitor()
1252 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1253 dev[2].dump_monitor()
1254 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1255 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1256 if ev is None:
1257 raise Exception("Enrollee not seen")
1258 if addr2 not in ev:
1259 raise Exception("Unexpected Enrollee MAC address")
1260 uuid = ev.split(' ')[1]
1261 dev[0].request("WPS_ER_PIN " + uuid + " " + pin)
1262 dev[2].wait_connected(timeout=30)
1263 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1264 if ev is None:
1265 raise Exception("WPS ER did not report success")
1266
ea982de1
JM
1267 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-REMOVE"], timeout=15)
1268 if ev is None:
1269 raise Exception("No Enrollee STA entry timeout seen")
1270
c965ae03
JM
1271 logger.info("Stop ER")
1272 dev[0].dump_monitor()
1273 dev[0].request("WPS_ER_STOP")
1274
61c3d464
JM
1275def test_ap_wps_er_multi_add_enrollee(dev, apdev):
1276 """Multiple WPS ERs adding a new enrollee using PIN"""
1277 try:
1278 _test_ap_wps_er_multi_add_enrollee(dev, apdev)
1279 finally:
d887ed3f
JM
1280 for i in range(2):
1281 dev[i].request("WPS_ER_STOP")
61c3d464
JM
1282
1283def _test_ap_wps_er_multi_add_enrollee(dev, apdev):
1284 ssid = "wps-er-add-enrollee"
1285 ap_pin = "12345670"
1286 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1287 hostapd.add_ap(apdev[0],
fab49f61
JM
1288 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1289 "wpa_passphrase": "12345678", "wpa": "2",
1290 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1291 "device_name": "Wireless AP", "manufacturer": "Company",
1292 "model_name": "WAP", "model_number": "123",
1293 "serial_number": "12345", "device_type": "6-0050F204-1",
1294 "os_version": "01020300",
1295 'friendly_name': "WPS AP",
1296 "config_methods": "label push_button",
1297 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
61c3d464
JM
1298
1299 for i in range(2):
1300 dev[i].scan_for_bss(apdev[0]['bssid'], freq=2412)
1301 dev[i].wps_reg(apdev[0]['bssid'], ap_pin)
6a5f578c 1302 for i in range(2):
61c3d464
JM
1303 dev[i].request("WPS_ER_START ifname=lo")
1304 for i in range(2):
1305 ev = dev[i].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1306 if ev is None:
1307 raise Exception("AP discovery timed out")
1308 dev[i].dump_monitor()
6a5f578c 1309 for i in range(2):
61c3d464 1310 dev[i].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
6a5f578c 1311 for i in range(2):
61c3d464
JM
1312 ev = dev[i].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1313 if ev is None:
1314 raise Exception("AP learn timed out")
1315 ev = dev[i].wait_event(["WPS-FAIL"], timeout=15)
1316 if ev is None:
1317 raise Exception("WPS-FAIL after AP learn timed out")
1318
1319 time.sleep(0.1)
1320
1321 pin = dev[2].wps_read_pin()
1322 addr = dev[2].own_addr()
1323 dev[0].dump_monitor()
1324 dev[0].request("WPS_ER_PIN any " + pin + " " + addr)
1325 dev[1].dump_monitor()
1326 dev[1].request("WPS_ER_PIN any " + pin + " " + addr)
1327
1328 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1329 dev[2].dump_monitor()
1330 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1331 ev = dev[2].wait_event(["WPS-SUCCESS"], timeout=30)
1332 if ev is None:
1333 raise Exception("Enrollee did not report success")
1334 dev[2].wait_connected(timeout=15)
1335
6edaee9c
JM
1336def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1337 """WPS ER connected to AP and adding a new enrollee using PBC"""
be9f1562
JM
1338 try:
1339 _test_ap_wps_er_add_enrollee_pbc(dev, apdev)
1340 finally:
1341 dev[0].request("WPS_ER_STOP")
1342
1343def _test_ap_wps_er_add_enrollee_pbc(dev, apdev):
6edaee9c
JM
1344 ssid = "wps-er-add-enrollee-pbc"
1345 ap_pin = "12345670"
1346 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1347 hostapd.add_ap(apdev[0],
fab49f61
JM
1348 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1349 "wpa_passphrase": "12345678", "wpa": "2",
1350 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1351 "device_name": "Wireless AP", "manufacturer": "Company",
1352 "model_name": "WAP", "model_number": "123",
1353 "serial_number": "12345", "device_type": "6-0050F204-1",
1354 "os_version": "01020300",
1355 "config_methods": "label push_button",
1356 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
6edaee9c 1357 logger.info("Learn AP configuration")
33d0b157 1358 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 1359 dev[0].dump_monitor()
6edaee9c
JM
1360 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1361 status = dev[0].get_status()
1362 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1363 raise Exception("Not fully connected")
1364
1365 logger.info("Start ER")
1366 dev[0].request("WPS_ER_START ifname=lo")
1367 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1368 if ev is None:
1369 raise Exception("AP discovery timed out")
1370 if ap_uuid not in ev:
1371 raise Exception("Expected AP UUID not found")
1372
d6b916c9
JM
1373 enrollee = dev[1].p2p_interface_addr()
1374
1375 if "FAIL-UNKNOWN-UUID" not in dev[0].request("WPS_ER_PBC " + enrollee):
1376 raise Exception("Unknown UUID not reported")
6edaee9c
JM
1377
1378 logger.info("Add Enrollee using ER and PBC")
1379 dev[0].dump_monitor()
6edaee9c
JM
1380 dev[1].dump_monitor()
1381 dev[1].request("WPS_PBC")
1382
8674c022
JM
1383 for i in range(0, 2):
1384 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1385 if ev is None:
1386 raise Exception("Enrollee discovery timed out")
1387 if enrollee in ev:
1388 break
1389 if i == 1:
1390 raise Exception("Expected Enrollee not found")
d6b916c9
JM
1391 if "FAIL-NO-AP-SETTINGS" not in dev[0].request("WPS_ER_PBC " + enrollee):
1392 raise Exception("Unknown UUID not reported")
1393 logger.info("Use learned network configuration on ER")
1394 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1395 if "OK" not in dev[0].request("WPS_ER_PBC " + enrollee):
1396 raise Exception("WPS_ER_PBC failed")
6edaee9c
JM
1397
1398 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
1399 if ev is None:
1400 raise Exception("Enrollee did not report success")
5f35a5e2 1401 dev[1].wait_connected(timeout=15)
6edaee9c
JM
1402 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1403 if ev is None:
1404 raise Exception("WPS ER did not report success")
1405 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
bff3ac5b 1406
d6b916c9
JM
1407def test_ap_wps_er_pbc_overlap(dev, apdev):
1408 """WPS ER connected to AP and PBC session overlap"""
be9f1562
JM
1409 try:
1410 _test_ap_wps_er_pbc_overlap(dev, apdev)
1411 finally:
1412 dev[0].request("WPS_ER_STOP")
1413
1414def _test_ap_wps_er_pbc_overlap(dev, apdev):
d6b916c9
JM
1415 ssid = "wps-er-add-enrollee-pbc"
1416 ap_pin = "12345670"
1417 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1418 hostapd.add_ap(apdev[0],
fab49f61
JM
1419 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1420 "wpa_passphrase": "12345678", "wpa": "2",
1421 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1422 "device_name": "Wireless AP", "manufacturer": "Company",
1423 "model_name": "WAP", "model_number": "123",
1424 "serial_number": "12345", "device_type": "6-0050F204-1",
1425 "os_version": "01020300",
1426 "config_methods": "label push_button",
1427 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
d6b916c9
JM
1428 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1429 dev[0].dump_monitor()
1430 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1431
fba25c99
JM
1432 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1433 dev[2].scan_for_bss(apdev[0]['bssid'], freq="2412")
1434 # avoid leaving dev 1 or 2 as the last Probe Request to the AP
1435 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True)
1436
d6b916c9
JM
1437 dev[0].dump_monitor()
1438 dev[0].request("WPS_ER_START ifname=lo")
1439
1440 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1441 if ev is None:
1442 raise Exception("AP discovery timed out")
1443 if ap_uuid not in ev:
1444 raise Exception("Expected AP UUID not found")
1445
800bcf4e
JM
1446 # verify BSSID selection of the AP instead of UUID
1447 if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
1448 raise Exception("Could not select AP based on BSSID")
1449
fba25c99 1450 dev[0].dump_monitor()
d6b916c9
JM
1451 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1452 dev[2].request("WPS_PBC " + apdev[0]['bssid'])
1453 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1454 if ev is None:
1455 raise Exception("PBC scan failed")
1456 ev = dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1457 if ev is None:
1458 raise Exception("PBC scan failed")
fba25c99
JM
1459 found1 = False
1460 found2 = False
1461 addr1 = dev[1].own_addr()
1462 addr2 = dev[2].own_addr()
1463 for i in range(3):
d6b916c9
JM
1464 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1465 if ev is None:
1466 raise Exception("Enrollee discovery timed out")
fba25c99
JM
1467 if addr1 in ev:
1468 found1 = True
1469 if found2:
1470 break
1471 if addr2 in ev:
1472 found2 = True
1473 if found1:
1474 break
d6b916c9
JM
1475 if dev[0].request("WPS_ER_PBC " + ap_uuid) != "FAIL-PBC-OVERLAP\n":
1476 raise Exception("PBC overlap not reported")
1477 dev[1].request("WPS_CANCEL")
1478 dev[2].request("WPS_CANCEL")
1479 if dev[0].request("WPS_ER_PBC foo") != "FAIL\n":
1480 raise Exception("Invalid WPS_ER_PBC accepted")
1481
1f020f5e
JM
1482def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1483 """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
be9f1562
JM
1484 try:
1485 _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev)
1486 finally:
1487 dev[0].request("WPS_ER_STOP")
1488
1489def _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1f020f5e
JM
1490 ssid = "wps-er-add-enrollee-pbc"
1491 ap_pin = "12345670"
1492 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1493 hostapd.add_ap(apdev[0],
fab49f61
JM
1494 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1495 "wpa_passphrase": "12345678", "wpa": "2",
1496 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1497 "device_name": "Wireless AP", "manufacturer": "Company",
1498 "model_name": "WAP", "model_number": "123",
1499 "serial_number": "12345", "device_type": "6-0050F204-1",
1500 "os_version": "01020300",
1501 "config_methods": "label push_button",
1502 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1f020f5e
JM
1503 logger.info("Learn AP configuration")
1504 dev[0].request("SET wps_version_number 0x10")
33d0b157 1505 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1f020f5e
JM
1506 dev[0].dump_monitor()
1507 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1508 status = dev[0].get_status()
1509 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1510 raise Exception("Not fully connected")
1511
1512 logger.info("Start ER")
1513 dev[0].request("WPS_ER_START ifname=lo")
1514 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1515 if ev is None:
1516 raise Exception("AP discovery timed out")
1517 if ap_uuid not in ev:
1518 raise Exception("Expected AP UUID not found")
1519
1520 logger.info("Use learned network configuration on ER")
1521 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1522
1523 logger.info("Add Enrollee using ER and PIN")
1524 enrollee = dev[1].p2p_interface_addr()
1525 pin = dev[1].wps_read_pin()
1526 dev[0].dump_monitor()
1527 dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
33d0b157 1528 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1f020f5e 1529 dev[1].dump_monitor()
33d0b157 1530 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 1531 dev[1].wait_connected(timeout=30)
1f020f5e
JM
1532 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1533 if ev is None:
1534 raise Exception("WPS ER did not report success")
1535
9fd6804d 1536@remote_compatible
be923570
JM
1537def test_ap_wps_er_config_ap(dev, apdev):
1538 """WPS ER configuring AP over UPnP"""
be9f1562
JM
1539 try:
1540 _test_ap_wps_er_config_ap(dev, apdev)
1541 finally:
1542 dev[0].request("WPS_ER_STOP")
1543
1544def _test_ap_wps_er_config_ap(dev, apdev):
be923570
JM
1545 ssid = "wps-er-ap-config"
1546 ap_pin = "12345670"
1547 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1548 hostapd.add_ap(apdev[0],
fab49f61
JM
1549 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1550 "wpa_passphrase": "12345678", "wpa": "2",
1551 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1552 "device_name": "Wireless AP", "manufacturer": "Company",
1553 "model_name": "WAP", "model_number": "123",
1554 "serial_number": "12345", "device_type": "6-0050F204-1",
1555 "os_version": "01020300",
1556 "config_methods": "label push_button",
1557 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
be923570
JM
1558
1559 logger.info("Connect ER to the AP")
1560 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
1561
1562 logger.info("WPS configuration step")
1563 dev[0].request("WPS_ER_START ifname=lo")
1564 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1565 if ev is None:
1566 raise Exception("AP discovery timed out")
1567 if ap_uuid not in ev:
1568 raise Exception("Expected AP UUID not found")
1569 new_passphrase = "1234567890"
1570 dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
54c58f29
MH
1571 binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " +
1572 binascii.hexlify(new_passphrase.encode()).decode())
be923570
JM
1573 ev = dev[0].wait_event(["WPS-SUCCESS"])
1574 if ev is None:
1575 raise Exception("WPS ER configuration operation timed out")
5f35a5e2 1576 dev[0].wait_disconnected(timeout=10)
be923570
JM
1577 dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
1578
8f8c2fe8
JM
1579 logger.info("WPS ER restart")
1580 dev[0].request("WPS_ER_START")
1581 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1582 if ev is None:
1583 raise Exception("AP discovery timed out on ER restart")
1584 if ap_uuid not in ev:
1585 raise Exception("Expected AP UUID not found on ER restart")
1586 if "OK" not in dev[0].request("WPS_ER_STOP"):
1587 raise Exception("WPS_ER_STOP failed")
1588 if "OK" not in dev[0].request("WPS_ER_STOP"):
1589 raise Exception("WPS_ER_STOP failed")
1590
9fd6804d 1591@remote_compatible
6aaa661a
JM
1592def test_ap_wps_er_cache_ap_settings(dev, apdev):
1593 """WPS ER caching AP settings"""
1594 try:
1595 _test_ap_wps_er_cache_ap_settings(dev, apdev)
1596 finally:
1597 dev[0].request("WPS_ER_STOP")
1598
1599def _test_ap_wps_er_cache_ap_settings(dev, apdev):
1600 ssid = "wps-er-add-enrollee"
1601 ap_pin = "12345670"
1602 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
fab49f61
JM
1603 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1604 "wpa_passphrase": "12345678", "wpa": "2",
1605 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1606 "device_name": "Wireless AP", "manufacturer": "Company",
1607 "model_name": "WAP", "model_number": "123",
1608 "serial_number": "12345", "device_type": "6-0050F204-1",
1609 "os_version": "01020300",
1610 "config_methods": "label push_button",
1611 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
8b8a1864 1612 hapd = hostapd.add_ap(apdev[0], params)
6aaa661a
JM
1613 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1614 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1615 id = int(dev[0].list_networks()[0]['id'])
1616 dev[0].set_network(id, "scan_freq", "2412")
1617
1618 dev[0].request("WPS_ER_START ifname=lo")
1619 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1620 if ev is None:
1621 raise Exception("AP discovery timed out")
1622 if ap_uuid not in ev:
1623 raise Exception("Expected AP UUID not found")
1624
1625 dev[0].dump_monitor()
1626 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1627 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1628 if ev is None:
1629 raise Exception("AP learn timed out")
1630 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1631 if ev is None:
1632 raise Exception("WPS-FAIL after AP learn timed out")
1633 time.sleep(0.1)
1634
1635 hapd.disable()
1636
1637 for i in range(2):
fab49f61 1638 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE", "CTRL-EVENT-DISCONNECTED"],
6aaa661a
JM
1639 timeout=15)
1640 if ev is None:
1641 raise Exception("AP removal or disconnection timed out")
1642
8b8a1864 1643 hapd = hostapd.add_ap(apdev[0], params)
6aaa661a 1644 for i in range(2):
fab49f61 1645 ev = dev[0].wait_event(["WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED"],
6aaa661a
JM
1646 timeout=15)
1647 if ev is None:
1648 raise Exception("AP discovery or connection timed out")
1649
1650 pin = dev[1].wps_read_pin()
1651 dev[0].dump_monitor()
1652 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1653
1654 time.sleep(0.2)
1655
1656 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1657 dev[1].dump_monitor()
1658 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1659 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
1660 if ev is None:
1661 raise Exception("Enrollee did not report success")
1662 dev[1].wait_connected(timeout=15)
1663 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1664 if ev is None:
1665 raise Exception("WPS ER did not report success")
1666
1667 dev[0].dump_monitor()
1668 dev[0].request("WPS_ER_STOP")
1669
d840350a
JM
1670def test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1671 """WPS ER caching AP settings (OOM)"""
1672 try:
1673 _test_ap_wps_er_cache_ap_settings_oom(dev, apdev)
1674 finally:
1675 dev[0].request("WPS_ER_STOP")
1676
1677def _test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1678 ssid = "wps-er-add-enrollee"
1679 ap_pin = "12345670"
1680 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
fab49f61
JM
1681 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1682 "wpa_passphrase": "12345678", "wpa": "2",
1683 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1684 "device_name": "Wireless AP", "manufacturer": "Company",
1685 "model_name": "WAP", "model_number": "123",
1686 "serial_number": "12345", "device_type": "6-0050F204-1",
1687 "os_version": "01020300",
1688 "config_methods": "label push_button",
1689 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
8b8a1864 1690 hapd = hostapd.add_ap(apdev[0], params)
d840350a
JM
1691 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1692 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1693 id = int(dev[0].list_networks()[0]['id'])
1694 dev[0].set_network(id, "scan_freq", "2412")
1695
1696 dev[0].request("WPS_ER_START ifname=lo")
1697 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1698 if ev is None:
1699 raise Exception("AP discovery timed out")
1700 if ap_uuid not in ev:
1701 raise Exception("Expected AP UUID not found")
1702
1703 dev[0].dump_monitor()
1704 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1705 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1706 if ev is None:
1707 raise Exception("AP learn timed out")
1708 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1709 if ev is None:
1710 raise Exception("WPS-FAIL after AP learn timed out")
1711 time.sleep(0.1)
1712
1713 with alloc_fail(dev[0], 1, "=wps_er_ap_use_cached_settings"):
1714 hapd.disable()
1715
1716 for i in range(2):
fab49f61
JM
1717 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE",
1718 "CTRL-EVENT-DISCONNECTED"],
d840350a
JM
1719 timeout=15)
1720 if ev is None:
1721 raise Exception("AP removal or disconnection timed out")
1722
8b8a1864 1723 hapd = hostapd.add_ap(apdev[0], params)
d840350a 1724 for i in range(2):
fab49f61 1725 ev = dev[0].wait_event(["WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED"],
d840350a
JM
1726 timeout=15)
1727 if ev is None:
1728 raise Exception("AP discovery or connection timed out")
1729
1730 dev[0].request("WPS_ER_STOP")
1731
1732def test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1733 """WPS ER caching AP settings (OOM 2)"""
1734 try:
1735 _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev)
1736 finally:
1737 dev[0].request("WPS_ER_STOP")
1738
1739def _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1740 ssid = "wps-er-add-enrollee"
1741 ap_pin = "12345670"
1742 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
fab49f61
JM
1743 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1744 "wpa_passphrase": "12345678", "wpa": "2",
1745 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1746 "device_name": "Wireless AP", "manufacturer": "Company",
1747 "model_name": "WAP", "model_number": "123",
1748 "serial_number": "12345", "device_type": "6-0050F204-1",
1749 "os_version": "01020300",
1750 "config_methods": "label push_button",
1751 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
8b8a1864 1752 hapd = hostapd.add_ap(apdev[0], params)
d840350a
JM
1753 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1754 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1755 id = int(dev[0].list_networks()[0]['id'])
1756 dev[0].set_network(id, "scan_freq", "2412")
1757
1758 dev[0].request("WPS_ER_START ifname=lo")
1759 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1760 if ev is None:
1761 raise Exception("AP discovery timed out")
1762 if ap_uuid not in ev:
1763 raise Exception("Expected AP UUID not found")
1764
1765 dev[0].dump_monitor()
1766 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1767 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1768 if ev is None:
1769 raise Exception("AP learn timed out")
1770 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1771 if ev is None:
1772 raise Exception("WPS-FAIL after AP learn timed out")
1773 time.sleep(0.1)
1774
1775 with alloc_fail(dev[0], 1, "=wps_er_ap_cache_settings"):
1776 hapd.disable()
1777
1778 for i in range(2):
fab49f61
JM
1779 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE",
1780 "CTRL-EVENT-DISCONNECTED"],
d840350a
JM
1781 timeout=15)
1782 if ev is None:
1783 raise Exception("AP removal or disconnection timed out")
1784
8b8a1864 1785 hapd = hostapd.add_ap(apdev[0], params)
d840350a 1786 for i in range(2):
fab49f61 1787 ev = dev[0].wait_event(["WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED"],
d840350a
JM
1788 timeout=15)
1789 if ev is None:
1790 raise Exception("AP discovery or connection timed out")
1791
1792 dev[0].request("WPS_ER_STOP")
1793
eb95ced2
JM
1794def test_ap_wps_er_subscribe_oom(dev, apdev):
1795 """WPS ER subscribe OOM"""
1796 try:
1797 _test_ap_wps_er_subscribe_oom(dev, apdev)
1798 finally:
1799 dev[0].request("WPS_ER_STOP")
1800
1801def _test_ap_wps_er_subscribe_oom(dev, apdev):
1802 ssid = "wps-er-add-enrollee"
1803 ap_pin = "12345670"
1804 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
fab49f61
JM
1805 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1806 "wpa_passphrase": "12345678", "wpa": "2",
1807 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1808 "device_name": "Wireless AP", "manufacturer": "Company",
1809 "model_name": "WAP", "model_number": "123",
1810 "serial_number": "12345", "device_type": "6-0050F204-1",
1811 "os_version": "01020300",
1812 "config_methods": "label push_button",
1813 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
8b8a1864 1814 hapd = hostapd.add_ap(apdev[0], params)
eb95ced2
JM
1815 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1816 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1817 id = int(dev[0].list_networks()[0]['id'])
1818 dev[0].set_network(id, "scan_freq", "2412")
1819
1820 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_subscribe"):
1821 dev[0].request("WPS_ER_START ifname=lo")
1822 for i in range(50):
1823 res = dev[0].request("GET_ALLOC_FAIL")
1824 if res.startswith("0:"):
1825 break
1826 time.sleep(0.1)
1827 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=0)
1828 if ev:
1829 raise Exception("Unexpected AP discovery during OOM")
1830
1831 dev[0].request("WPS_ER_STOP")
1832
db9c88eb
JM
1833def test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1834 """WPS ER SetSelectedRegistrar OOM"""
1835 try:
1836 _test_ap_wps_er_set_sel_reg_oom(dev, apdev)
1837 finally:
1838 dev[0].request("WPS_ER_STOP")
1839
1840def _test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1841 ssid = "wps-er-add-enrollee"
1842 ap_pin = "12345670"
1843 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
fab49f61
JM
1844 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1845 "wpa_passphrase": "12345678", "wpa": "2",
1846 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1847 "device_name": "Wireless AP", "manufacturer": "Company",
1848 "model_name": "WAP", "model_number": "123",
1849 "serial_number": "12345", "device_type": "6-0050F204-1",
1850 "os_version": "01020300",
1851 "config_methods": "label push_button",
1852 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
8b8a1864 1853 hapd = hostapd.add_ap(apdev[0], params)
db9c88eb
JM
1854 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1855 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1856
1857 dev[0].request("WPS_ER_START ifname=lo")
1858 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1859 if ev is None:
1860 raise Exception("AP not discovered")
1861
1862 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1863 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1864 if ev is None:
1865 raise Exception("AP learn timed out")
1866 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1867 if ev is None:
1868 raise Exception("WPS-FAIL timed out")
1869 time.sleep(0.1)
1870
fab49f61
JM
1871 for func in ["http_client_url_parse;wps_er_send_set_sel_reg",
1872 "wps_er_soap_hdr;wps_er_send_set_sel_reg",
1873 "http_client_addr;wps_er_send_set_sel_reg",
1874 "wpabuf_alloc;wps_er_set_sel_reg"]:
db9c88eb
JM
1875 with alloc_fail(dev[0], 1, func):
1876 if "OK" not in dev[0].request("WPS_ER_PBC " + ap_uuid):
1877 raise Exception("WPS_ER_PBC failed")
1878 ev = dev[0].wait_event(["WPS-PBC-ACTIVE"], timeout=3)
1879 if ev is None:
1880 raise Exception("WPS-PBC-ACTIVE not seen")
1881
1882 dev[0].request("WPS_ER_STOP")
1883
9fd6804d 1884@remote_compatible
ae3eacf7
JM
1885def test_ap_wps_er_learn_oom(dev, apdev):
1886 """WPS ER learn OOM"""
1887 try:
1888 _test_ap_wps_er_learn_oom(dev, apdev)
1889 finally:
1890 dev[0].request("WPS_ER_STOP")
1891
1892def _test_ap_wps_er_learn_oom(dev, apdev):
1893 ssid = "wps-er-add-enrollee"
1894 ap_pin = "12345670"
1895 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
fab49f61
JM
1896 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1897 "wpa_passphrase": "12345678", "wpa": "2",
1898 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1899 "device_name": "Wireless AP", "manufacturer": "Company",
1900 "model_name": "WAP", "model_number": "123",
1901 "serial_number": "12345", "device_type": "6-0050F204-1",
1902 "os_version": "01020300",
1903 "config_methods": "label push_button",
1904 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
8b8a1864 1905 hapd = hostapd.add_ap(apdev[0], params)
ae3eacf7
JM
1906 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1907 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1908
1909 dev[0].request("WPS_ER_START ifname=lo")
1910 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1911 if ev is None:
1912 raise Exception("AP not discovered")
1913
fab49f61
JM
1914 for func in ["wps_er_http_put_message_cb",
1915 "xml_get_base64_item;wps_er_http_put_message_cb",
1916 "http_client_url_parse;wps_er_ap_put_message",
1917 "wps_er_soap_hdr;wps_er_ap_put_message",
1918 "http_client_addr;wps_er_ap_put_message"]:
ae3eacf7
JM
1919 with alloc_fail(dev[0], 1, func):
1920 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1921 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=1)
1922 if ev is not None:
1923 raise Exception("AP learn succeeded during OOM")
1924
1925 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1926 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=10)
1927 if ev is None:
1928 raise Exception("AP learn did not succeed")
1929
1930 if "FAIL" not in dev[0].request("WPS_ER_LEARN 00000000-9e5c-4e73-bd82-f89cbcd10d7e " + ap_pin):
1931 raise Exception("WPS_ER_LEARN for unknown AP accepted")
1932
1933 dev[0].request("WPS_ER_STOP")
1934
bff3ac5b
JM
1935def test_ap_wps_fragmentation(dev, apdev):
1936 """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
1937 ssid = "test-wps-fragmentation"
9602b355 1938 appin = "12345670"
6f334bf7 1939 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
1940 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1941 "wpa_passphrase": "12345678", "wpa": "3",
1942 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1943 "wpa_pairwise": "TKIP", "ap_pin": appin,
1944 "fragment_size": "50"})
9602b355 1945 logger.info("WPS provisioning step (PBC)")
bff3ac5b 1946 hapd.request("WPS_PBC")
33d0b157 1947 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
bff3ac5b
JM
1948 dev[0].dump_monitor()
1949 dev[0].request("SET wps_fragment_size 50")
33d0b157 1950 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1951 dev[0].wait_connected(timeout=30)
bff3ac5b
JM
1952 status = dev[0].get_status()
1953 if status['wpa_state'] != 'COMPLETED':
9602b355
JM
1954 raise Exception("Not fully connected")
1955 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1956 raise Exception("Unexpected encryption configuration")
1957 if status['key_mgmt'] != 'WPA2-PSK':
1958 raise Exception("Unexpected key_mgmt")
1959
1960 logger.info("WPS provisioning step (PIN)")
1961 pin = dev[1].wps_read_pin()
1962 hapd.request("WPS_PIN any " + pin)
33d0b157 1963 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
9602b355 1964 dev[1].request("SET wps_fragment_size 50")
33d0b157 1965 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 1966 dev[1].wait_connected(timeout=30)
9602b355
JM
1967 status = dev[1].get_status()
1968 if status['wpa_state'] != 'COMPLETED':
1969 raise Exception("Not fully connected")
1970 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1971 raise Exception("Unexpected encryption configuration")
1972 if status['key_mgmt'] != 'WPA2-PSK':
1973 raise Exception("Unexpected key_mgmt")
1974
1975 logger.info("WPS connection as registrar")
33d0b157 1976 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
9602b355
JM
1977 dev[2].request("SET wps_fragment_size 50")
1978 dev[2].wps_reg(apdev[0]['bssid'], appin)
1979 status = dev[2].get_status()
1980 if status['wpa_state'] != 'COMPLETED':
bff3ac5b
JM
1981 raise Exception("Not fully connected")
1982 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1983 raise Exception("Unexpected encryption configuration")
1984 if status['key_mgmt'] != 'WPA2-PSK':
1985 raise Exception("Unexpected key_mgmt")
10ea6848 1986
9fd6804d 1987@remote_compatible
10ea6848
JM
1988def test_ap_wps_new_version_sta(dev, apdev):
1989 """WPS compatibility with new version number on the station"""
1990 ssid = "test-wps-ver"
6f334bf7 1991 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
1992 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1993 "wpa_passphrase": "12345678", "wpa": "2",
1994 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
10ea6848
JM
1995 logger.info("WPS provisioning step")
1996 hapd.request("WPS_PBC")
33d0b157 1997 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10ea6848
JM
1998 dev[0].dump_monitor()
1999 dev[0].request("SET wps_version_number 0x43")
dccafedb 2000 dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
33d0b157 2001 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2002 dev[0].wait_connected(timeout=30)
10ea6848 2003
9fd6804d 2004@remote_compatible
10ea6848
JM
2005def test_ap_wps_new_version_ap(dev, apdev):
2006 """WPS compatibility with new version number on the AP"""
2007 ssid = "test-wps-ver"
6f334bf7 2008 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
2009 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2010 "wpa_passphrase": "12345678", "wpa": "2",
2011 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
10ea6848
JM
2012 logger.info("WPS provisioning step")
2013 if "FAIL" in hapd.request("SET wps_version_number 0x43"):
2014 raise Exception("Failed to enable test functionality")
2015 hapd.request("WPS_PBC")
33d0b157 2016 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10ea6848 2017 dev[0].dump_monitor()
33d0b157 2018 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2019 dev[0].wait_connected(timeout=30)
10ea6848 2020 hapd.request("SET wps_version_number 0x20")
3bdf7d7f 2021
9fd6804d 2022@remote_compatible
3bdf7d7f
JM
2023def test_ap_wps_check_pin(dev, apdev):
2024 """Verify PIN checking through control interface"""
6f334bf7 2025 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
2026 {"ssid": "wps", "eap_server": "1", "wps_state": "2",
2027 "wpa_passphrase": "12345678", "wpa": "2",
2028 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2029 for t in [("12345670", "12345670"),
2030 ("12345678", "FAIL-CHECKSUM"),
2031 ("12345", "FAIL"),
2032 ("123456789", "FAIL"),
2033 ("1234-5670", "12345670"),
2034 ("1234 5670", "12345670"),
2035 ("1-2.3:4 5670", "12345670")]:
3bdf7d7f
JM
2036 res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
2037 res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
2038 if res != res2:
2039 raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
2040 if res != t[1]:
2041 raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
9ba1fcb0 2042
ac786d67
JM
2043 if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
2044 raise Exception("Unexpected WPS_CHECK_PIN success")
2045 if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
2046 raise Exception("Unexpected WPS_CHECK_PIN success")
2047
acd9b45a
JM
2048 for i in range(0, 10):
2049 pin = dev[0].request("WPS_PIN get")
2050 rpin = dev[0].request("WPS_CHECK_PIN " + pin).rstrip('\n')
2051 if pin != rpin:
2052 raise Exception("Random PIN validation failed for " + pin)
2053
3381d324
JM
2054def test_ap_wps_pin_get_failure(dev, apdev):
2055 """PIN generation failure"""
2056 with fail_test(dev[0], 1,
2057 "os_get_random;wpa_supplicant_ctrl_iface_wps_pin"):
2058 if "FAIL" not in dev[0].request("WPS_PIN get"):
2059 raise Exception("WPS_PIN did not report failure")
2060
9ba1fcb0
JM
2061def test_ap_wps_wep_config(dev, apdev):
2062 """WPS 2.0 AP rejecting WEP configuration"""
2063 ssid = "test-wps-config"
2064 appin = "12345670"
6f334bf7 2065 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
2066 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2067 "ap_pin": appin})
33d0b157 2068 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
9ba1fcb0
JM
2069 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
2070 "hello", no_wait=True)
2071 ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
2072 if ev is None:
2073 raise Exception("WPS-FAIL timed out")
2074 if "reason=2" not in ev:
2075 raise Exception("Unexpected reason code in WPS-FAIL")
2076 status = hapd.request("WPS_GET_STATUS")
2077 if "Last WPS result: Failed" not in status:
2078 raise Exception("WPS failure result not shown correctly")
2079 if "Failure Reason: WEP Prohibited" not in status:
2080 raise Exception("Failure reason not reported correctly")
2081 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
2082 raise Exception("Peer address not shown correctly")
1013a576 2083
11d78bb1
JM
2084def test_ap_wps_wep_enroll(dev, apdev):
2085 """WPS 2.0 STA rejecting WEP configuration"""
2086 ssid = "test-wps-wep"
fab49f61
JM
2087 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2088 "skip_cred_build": "1", "extra_cred": "wps-wep-cred"}
6f334bf7 2089 hapd = hostapd.add_ap(apdev[0], params)
11d78bb1 2090 hapd.request("WPS_PBC")
33d0b157
JM
2091 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2092 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
11d78bb1
JM
2093 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
2094 if ev is None:
2095 raise Exception("WPS-FAIL event timed out")
2096 if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
2097 raise Exception("Unexpected WPS-FAIL event: " + ev)
2098
9fd6804d 2099@remote_compatible
1013a576
JM
2100def test_ap_wps_ie_fragmentation(dev, apdev):
2101 """WPS AP using fragmented WPS IE"""
2102 ssid = "test-wps-ie-fragmentation"
fab49f61
JM
2103 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2104 "wpa_passphrase": "12345678", "wpa": "2",
2105 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2106 "device_name": "1234567890abcdef1234567890abcdef",
2107 "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
2108 "model_name": "1234567890abcdef1234567890abcdef",
2109 "model_number": "1234567890abcdef1234567890abcdef",
2110 "serial_number": "1234567890abcdef1234567890abcdef"}
6f334bf7 2111 hapd = hostapd.add_ap(apdev[0], params)
1013a576 2112 hapd.request("WPS_PBC")
33d0b157
JM
2113 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2114 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2115 dev[0].wait_connected(timeout=30)
1013a576
JM
2116 bss = dev[0].get_bss(apdev[0]['bssid'])
2117 if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
cf3f0ec8 2118 logger.info("Device Name not received correctly")
d7a68ad6 2119 logger.info(bss)
cf3f0ec8
JM
2120 # This can fail if Probe Response frame is missed and Beacon frame was
2121 # used to fill in the BSS entry. This can happen, e.g., during heavy
2122 # load every now and then and is not really an error, so try to
2123 # workaround by runnign another scan.
2124 dev[0].scan(freq="2412", only_new=True)
2125 bss = dev[0].get_bss(apdev[0]['bssid'])
84a40841 2126 if not bss or "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
cf3f0ec8
JM
2127 logger.info(bss)
2128 raise Exception("Device Name not received correctly")
1013a576
JM
2129 if len(re.findall("dd..0050f204", bss['ie'])) != 2:
2130 raise Exception("Unexpected number of WPS IEs")
44ff0400 2131
2035b170
JM
2132def get_psk(pskfile):
2133 psks = {}
2134 with open(pskfile, "r") as f:
2135 lines = f.read().splitlines()
2136 for l in lines:
2137 if l == "# WPA PSKs":
2138 continue
fab49f61 2139 (addr, psk) = l.split(' ')
2035b170
JM
2140 psks[addr] = psk
2141 return psks
2142
2143def test_ap_wps_per_station_psk(dev, apdev):
2144 """WPS PBC provisioning with per-station PSK"""
1d21a5be
B
2145 addr0 = dev[0].own_addr()
2146 addr1 = dev[1].own_addr()
2147 addr2 = dev[2].own_addr()
2035b170
JM
2148 ssid = "wps"
2149 appin = "12345670"
2150 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2151 try:
2152 os.remove(pskfile)
2153 except:
2154 pass
2155
4f524e99 2156 hapd = None
2035b170
JM
2157 try:
2158 with open(pskfile, "w") as f:
2159 f.write("# WPA PSKs\n")
2160
fab49f61
JM
2161 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2162 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2163 "rsn_pairwise": "CCMP", "ap_pin": appin,
2164 "wpa_psk_file": pskfile}
8b8a1864 2165 hapd = hostapd.add_ap(apdev[0], params)
2035b170
JM
2166
2167 logger.info("First enrollee")
2168 hapd.request("WPS_PBC")
33d0b157
JM
2169 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2170 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2171 dev[0].wait_connected(timeout=30)
2035b170
JM
2172
2173 logger.info("Second enrollee")
2174 hapd.request("WPS_PBC")
33d0b157
JM
2175 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2176 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2177 dev[1].wait_connected(timeout=30)
2035b170
JM
2178
2179 logger.info("External registrar")
33d0b157 2180 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2035b170
JM
2181 dev[2].wps_reg(apdev[0]['bssid'], appin)
2182
2183 logger.info("Verifying PSK results")
2184 psks = get_psk(pskfile)
2185 if addr0 not in psks:
2186 raise Exception("No PSK recorded for sta0")
2187 if addr1 not in psks:
2188 raise Exception("No PSK recorded for sta1")
2189 if addr2 not in psks:
2190 raise Exception("No PSK recorded for sta2")
2191 if psks[addr0] == psks[addr1]:
2192 raise Exception("Same PSK recorded for sta0 and sta1")
2193 if psks[addr0] == psks[addr2]:
2194 raise Exception("Same PSK recorded for sta0 and sta2")
2195 if psks[addr1] == psks[addr2]:
2196 raise Exception("Same PSK recorded for sta1 and sta2")
2197
2198 dev[0].request("REMOVE_NETWORK all")
2199 logger.info("Second external registrar")
33d0b157 2200 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2035b170
JM
2201 dev[0].wps_reg(apdev[0]['bssid'], appin)
2202 psks2 = get_psk(pskfile)
2203 if addr0 not in psks2:
2204 raise Exception("No PSK recorded for sta0(reg)")
2205 if psks[addr0] == psks2[addr0]:
2206 raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
2207 finally:
2208 os.remove(pskfile)
4f524e99
JM
2209 if hapd:
2210 dev[0].request("DISCONNECT")
2211 dev[1].request("DISCONNECT")
2212 dev[2].request("DISCONNECT")
2213 hapd.disable()
2214 dev[0].flush_scan_cache()
2215 dev[1].flush_scan_cache()
2216 dev[2].flush_scan_cache()
2035b170 2217
373cce55
JM
2218def test_ap_wps_per_station_psk_failure(dev, apdev):
2219 """WPS PBC provisioning with per-station PSK (file not writable)"""
2220 addr0 = dev[0].p2p_dev_addr()
2221 addr1 = dev[1].p2p_dev_addr()
2222 addr2 = dev[2].p2p_dev_addr()
2223 ssid = "wps"
2224 appin = "12345670"
2225 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2226 try:
2227 os.remove(pskfile)
2228 except:
2229 pass
2230
3615bde6 2231 hapd = None
373cce55
JM
2232 try:
2233 with open(pskfile, "w") as f:
2234 f.write("# WPA PSKs\n")
2235
fab49f61
JM
2236 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2237 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2238 "rsn_pairwise": "CCMP", "ap_pin": appin,
2239 "wpa_psk_file": pskfile}
8b8a1864 2240 hapd = hostapd.add_ap(apdev[0], params)
373cce55
JM
2241 if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
2242 raise Exception("Failed to set wpa_psk_file")
2243
2244 logger.info("First enrollee")
2245 hapd.request("WPS_PBC")
33d0b157
JM
2246 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2247 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2248 dev[0].wait_connected(timeout=30)
373cce55
JM
2249
2250 logger.info("Second enrollee")
2251 hapd.request("WPS_PBC")
33d0b157
JM
2252 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2253 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2254 dev[1].wait_connected(timeout=30)
373cce55
JM
2255
2256 logger.info("External registrar")
33d0b157 2257 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
373cce55
JM
2258 dev[2].wps_reg(apdev[0]['bssid'], appin)
2259
2260 logger.info("Verifying PSK results")
2261 psks = get_psk(pskfile)
2262 if len(psks) > 0:
2263 raise Exception("PSK recorded unexpectedly")
2264 finally:
3615bde6
JM
2265 if hapd:
2266 for i in range(3):
2267 dev[i].request("DISCONNECT")
2268 hapd.disable()
2269 for i in range(3):
2270 dev[i].flush_scan_cache()
373cce55
JM
2271 os.remove(pskfile)
2272
e8518757
JM
2273def test_ap_wps_pin_request_file(dev, apdev):
2274 """WPS PIN provisioning with configured AP"""
2275 ssid = "wps"
2276 pinfile = "/tmp/ap_wps_pin_request_file.log"
2277 if os.path.exists(pinfile):
b638f703 2278 os.remove(pinfile)
6f334bf7 2279 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
2280 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2281 "wps_pin_requests": pinfile,
2282 "wpa_passphrase": "12345678", "wpa": "2",
2283 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e8518757
JM
2284 uuid = dev[0].get_status_field("uuid")
2285 pin = dev[0].wps_read_pin()
2286 try:
33d0b157
JM
2287 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2288 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
e8518757
JM
2289 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
2290 if ev is None:
2291 raise Exception("PIN needed event not shown")
2292 if uuid not in ev:
2293 raise Exception("UUID mismatch")
2294 dev[0].request("WPS_CANCEL")
2295 success = False
2296 with open(pinfile, "r") as f:
2297 lines = f.readlines()
2298 for l in lines:
2299 if uuid in l:
2300 success = True
2301 break
2302 if not success:
2303 raise Exception("PIN request entry not in the log file")
2304 finally:
b638f703
JM
2305 try:
2306 os.remove(pinfile)
2307 except:
2308 pass
e8518757 2309
56887c35
JM
2310def test_ap_wps_auto_setup_with_config_file(dev, apdev):
2311 """WPS auto-setup with configuration file"""
2312 conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
2313 ifname = apdev[0]['ifname']
2314 try:
2315 with open(conffile, "w") as f:
2316 f.write("driver=nl80211\n")
2317 f.write("hw_mode=g\n")
2318 f.write("channel=1\n")
2319 f.write("ieee80211n=1\n")
2320 f.write("interface=%s\n" % ifname)
2321 f.write("ctrl_interface=/var/run/hostapd\n")
2322 f.write("ssid=wps\n")
2323 f.write("eap_server=1\n")
2324 f.write("wps_state=1\n")
5148b392 2325 hapd = hostapd.add_bss(apdev[0], ifname, conffile)
56887c35 2326 hapd.request("WPS_PBC")
33d0b157
JM
2327 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2328 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2329 dev[0].wait_connected(timeout=30)
56887c35
JM
2330 with open(conffile, "r") as f:
2331 lines = f.read().splitlines()
2332 vals = dict()
2333 for l in lines:
2334 try:
fab49f61 2335 [name, value] = l.split('=', 1)
56887c35 2336 vals[name] = value
bab493b9 2337 except ValueError as e:
56887c35
JM
2338 if "# WPS configuration" in l:
2339 pass
2340 else:
2341 raise Exception("Unexpected configuration line: " + l)
2342 if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
2343 raise Exception("Incorrect configuration: " + str(vals))
2344 finally:
b638f703
JM
2345 try:
2346 os.remove(conffile)
2347 except:
2348 pass
56887c35 2349
91f3cf69 2350def test_ap_wps_pbc_timeout(dev, apdev, params):
31e56b95 2351 """wpa_supplicant PBC walk time and WPS ER SelReg timeout [long]"""
91f3cf69 2352 if not params['long']:
81e787b7 2353 raise HwsimSkip("Skip test case with long duration due to --long not specified")
31e56b95 2354 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2355 hapd = add_ssdp_ap(apdev[0], ap_uuid)
31e56b95
JM
2356
2357 location = ssdp_get_location(ap_uuid)
2358 urls = upnp_get_urls(location)
9c06eda0
MH
2359 eventurl = urlparse(urls['event_sub_url'])
2360 ctrlurl = urlparse(urls['control_url'])
31e56b95 2361
9c06eda0
MH
2362 url = urlparse(location)
2363 conn = HTTPConnection(url.netloc)
31e56b95 2364
9c06eda0 2365 class WPSERHTTPServer(StreamRequestHandler):
31e56b95
JM
2366 def handle(self):
2367 data = self.rfile.readline().strip()
2368 logger.debug(data)
2369 self.wfile.write(gen_wps_event())
2370
2371 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
2372 server.timeout = 1
2373
fab49f61
JM
2374 headers = {"callback": '<http://127.0.0.1:12345/event>',
2375 "NT": "upnp:event",
2376 "timeout": "Second-1234"}
31e56b95
JM
2377 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2378 resp = conn.getresponse()
2379 if resp.status != 200:
2380 raise Exception("Unexpected HTTP response: %d" % resp.status)
2381 sid = resp.getheader("sid")
2382 logger.debug("Subscription SID " + sid)
2383
2384 msg = '''<?xml version="1.0"?>
2385<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
2386<s:Body>
2387<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
2388<NewMessage>EEoAARAQQQABARASAAIAABBTAAIxSBBJAA4ANyoAASABBv///////xBIABA2LbR7pTpRkYj7
2389VFi5hrLk
2390</NewMessage>
2391</u:SetSelectedRegistrar>
2392</s:Body>
2393</s:Envelope>'''
fab49f61 2394 headers = {"Content-type": 'text/xml; charset="utf-8"'}
31e56b95
JM
2395 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
2396 conn.request("POST", ctrlurl.path, msg, headers)
2397 resp = conn.getresponse()
2398 if resp.status != 200:
2399 raise Exception("Unexpected HTTP response: %d" % resp.status)
2400
2401 server.handle_request()
2402
91f3cf69
JM
2403 logger.info("Start WPS_PBC and wait for PBC walk time expiration")
2404 if "OK" not in dev[0].request("WPS_PBC"):
2405 raise Exception("WPS_PBC failed")
31e56b95
JM
2406
2407 start = os.times()[4]
2408
2409 server.handle_request()
2410 dev[1].request("BSS_FLUSH 0")
2411 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2412 only_new=True)
2413 bss = dev[1].get_bss(apdev[0]['bssid'])
2414 logger.debug("BSS: " + str(bss))
2415 if '[WPS-AUTH]' not in bss['flags']:
2416 raise Exception("WPS not indicated authorized")
2417
2418 server.handle_request()
2419
2420 wps_timeout_seen = False
2421
2422 while True:
2423 hapd.dump_monitor()
2424 dev[1].dump_monitor()
2425 if not wps_timeout_seen:
2426 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=0)
2427 if ev is not None:
2428 logger.info("PBC timeout seen")
2429 wps_timeout_seen = True
2430 else:
2431 dev[0].dump_monitor()
2432 now = os.times()[4]
2433 if now - start > 130:
2434 raise Exception("Selected registration information not removed")
2435 dev[1].request("BSS_FLUSH 0")
2436 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2437 only_new=True)
2438 bss = dev[1].get_bss(apdev[0]['bssid'])
2439 logger.debug("BSS: " + str(bss))
2440 if '[WPS-AUTH]' not in bss['flags']:
2441 break
2442 server.handle_request()
2443
2444 server.server_close()
2445
2446 if wps_timeout_seen:
2447 return
2448
2449 now = os.times()[4]
2450 if now < start + 150:
2451 dur = start + 150 - now
2452 else:
2453 dur = 1
2454 logger.info("Continue waiting for PBC timeout (%d sec)" % dur)
2455 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=dur)
91f3cf69
JM
2456 if ev is None:
2457 raise Exception("WPS-TIMEOUT not reported")
2458
21aa8b7e 2459def add_ssdp_ap(ap, ap_uuid):
44ff0400
JM
2460 ssid = "wps-ssdp"
2461 ap_pin = "12345670"
fab49f61
JM
2462 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2463 "wpa_passphrase": "12345678", "wpa": "2",
2464 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2465 "device_name": "Wireless AP", "manufacturer": "Company",
2466 "model_name": "WAP", "model_number": "123",
2467 "serial_number": "12345", "device_type": "6-0050F204-1",
2468 "os_version": "01020300",
2469 "config_methods": "label push_button",
2470 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
2471 "friendly_name": "WPS Access Point",
2472 "manufacturer_url": "http://www.example.com/",
2473 "model_description": "Wireless Access Point",
2474 "model_url": "http://www.example.com/model/",
2475 "upc": "123456789012"}
21aa8b7e 2476 return hostapd.add_ap(ap, params)
44ff0400
JM
2477
2478def ssdp_send(msg, no_recv=False):
2479 socket.setdefaulttimeout(1)
2480 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2481 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2482 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2483 sock.bind(("127.0.0.1", 0))
cc02ce96 2484 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2485 if no_recv:
2486 return None
cc02ce96 2487 return sock.recv(1000).decode()
44ff0400 2488
96038a5f 2489def ssdp_send_msearch(st, no_recv=False):
44ff0400
JM
2490 msg = '\r\n'.join([
2491 'M-SEARCH * HTTP/1.1',
2492 'HOST: 239.255.255.250:1900',
2493 'MX: 1',
2494 'MAN: "ssdp:discover"',
2495 'ST: ' + st,
2496 '', ''])
96038a5f 2497 return ssdp_send(msg, no_recv=no_recv)
44ff0400
JM
2498
2499def test_ap_wps_ssdp_msearch(dev, apdev):
2500 """WPS AP and SSDP M-SEARCH messages"""
2501 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2502 add_ssdp_ap(apdev[0], ap_uuid)
44ff0400
JM
2503
2504 msg = '\r\n'.join([
2505 'M-SEARCH * HTTP/1.1',
2506 'Host: 239.255.255.250:1900',
2507 'Mx: 1',
2508 'Man: "ssdp:discover"',
2509 'St: urn:schemas-wifialliance-org:device:WFADevice:1',
2510 '', ''])
2511 ssdp_send(msg)
2512
2513 msg = '\r\n'.join([
2514 'M-SEARCH * HTTP/1.1',
2515 'host:\t239.255.255.250:1900\t\t\t\t \t\t',
2516 'mx: \t1\t\t ',
2517 'man: \t \t "ssdp:discover" ',
2518 'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
2519 '', ''])
2520 ssdp_send(msg)
2521
2522 ssdp_send_msearch("ssdp:all")
2523 ssdp_send_msearch("upnp:rootdevice")
2524 ssdp_send_msearch("uuid:" + ap_uuid)
2525 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
bc6e3288 2526 ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1")
44ff0400
JM
2527
2528 msg = '\r\n'.join([
2529 'M-SEARCH * HTTP/1.1',
2530 'HOST:\t239.255.255.250:1900',
2531 'MAN: "ssdp:discover"',
2532 'MX: 130',
2533 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2534 '', ''])
2535 ssdp_send(msg, no_recv=True)
2536
2537def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
2538 """WPS AP and invalid SSDP M-SEARCH messages"""
2539 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2540 add_ssdp_ap(apdev[0], ap_uuid)
44ff0400
JM
2541
2542 socket.setdefaulttimeout(1)
2543 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2544 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2545 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2546 sock.bind(("127.0.0.1", 0))
2547
2548 logger.debug("Missing MX")
2549 msg = '\r\n'.join([
2550 'M-SEARCH * HTTP/1.1',
2551 'HOST: 239.255.255.250:1900',
2552 'MAN: "ssdp:discover"',
2553 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2554 '', ''])
cc02ce96 2555 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2556
2557 logger.debug("Negative MX")
2558 msg = '\r\n'.join([
2559 'M-SEARCH * HTTP/1.1',
2560 'HOST: 239.255.255.250:1900',
2561 'MX: -1',
2562 'MAN: "ssdp:discover"',
2563 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2564 '', ''])
cc02ce96 2565 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2566
2567 logger.debug("Invalid MX")
2568 msg = '\r\n'.join([
2569 'M-SEARCH * HTTP/1.1',
2570 'HOST: 239.255.255.250:1900',
2571 'MX; 1',
2572 'MAN: "ssdp:discover"',
2573 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2574 '', ''])
cc02ce96 2575 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2576
2577 logger.debug("Missing MAN")
2578 msg = '\r\n'.join([
2579 'M-SEARCH * HTTP/1.1',
2580 'HOST: 239.255.255.250:1900',
2581 'MX: 1',
2582 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2583 '', ''])
cc02ce96 2584 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2585
2586 logger.debug("Invalid MAN")
2587 msg = '\r\n'.join([
2588 'M-SEARCH * HTTP/1.1',
2589 'HOST: 239.255.255.250:1900',
2590 'MX: 1',
2591 'MAN: foo',
2592 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2593 '', ''])
cc02ce96 2594 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2595 msg = '\r\n'.join([
2596 'M-SEARCH * HTTP/1.1',
2597 'HOST: 239.255.255.250:1900',
2598 'MX: 1',
2599 'MAN; "ssdp:discover"',
2600 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2601 '', ''])
cc02ce96 2602 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2603
2604 logger.debug("Missing HOST")
2605 msg = '\r\n'.join([
2606 'M-SEARCH * HTTP/1.1',
2607 'MAN: "ssdp:discover"',
2608 'MX: 1',
2609 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2610 '', ''])
cc02ce96 2611 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2612
2613 logger.debug("Missing ST")
2614 msg = '\r\n'.join([
2615 'M-SEARCH * HTTP/1.1',
2616 'HOST: 239.255.255.250:1900',
2617 'MAN: "ssdp:discover"',
2618 'MX: 1',
2619 '', ''])
cc02ce96 2620 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2621
2622 logger.debug("Mismatching ST")
2623 msg = '\r\n'.join([
2624 'M-SEARCH * HTTP/1.1',
2625 'HOST: 239.255.255.250:1900',
2626 'MAN: "ssdp:discover"',
2627 'MX: 1',
2628 'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
2629 '', ''])
cc02ce96 2630 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2631 msg = '\r\n'.join([
2632 'M-SEARCH * HTTP/1.1',
2633 'HOST: 239.255.255.250:1900',
2634 'MAN: "ssdp:discover"',
2635 'MX: 1',
2636 'ST: foo:bar',
2637 '', ''])
cc02ce96 2638 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2639 msg = '\r\n'.join([
2640 'M-SEARCH * HTTP/1.1',
2641 'HOST: 239.255.255.250:1900',
2642 'MAN: "ssdp:discover"',
2643 'MX: 1',
2644 'ST: foobar',
2645 '', ''])
cc02ce96 2646 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2647
2648 logger.debug("Invalid ST")
2649 msg = '\r\n'.join([
2650 'M-SEARCH * HTTP/1.1',
2651 'HOST: 239.255.255.250:1900',
2652 'MAN: "ssdp:discover"',
2653 'MX: 1',
2654 'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
2655 '', ''])
cc02ce96 2656 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2657
2658 logger.debug("Invalid M-SEARCH")
2659 msg = '\r\n'.join([
2660 'M+SEARCH * HTTP/1.1',
2661 'HOST: 239.255.255.250:1900',
2662 'MAN: "ssdp:discover"',
2663 'MX: 1',
2664 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2665 '', ''])
cc02ce96 2666 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2667 msg = '\r\n'.join([
2668 'M-SEARCH-* HTTP/1.1',
2669 'HOST: 239.255.255.250:1900',
2670 'MAN: "ssdp:discover"',
2671 'MX: 1',
2672 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2673 '', ''])
cc02ce96 2674 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2675
2676 logger.debug("Invalid message format")
cc02ce96 2677 sock.sendto(b"NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
44ff0400
JM
2678 msg = '\r'.join([
2679 'M-SEARCH * HTTP/1.1',
2680 'HOST: 239.255.255.250:1900',
2681 'MAN: "ssdp:discover"',
2682 'MX: 1',
2683 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2684 '', ''])
cc02ce96 2685 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2686
2687 try:
2688 r = sock.recv(1000)
2689 raise Exception("Unexpected M-SEARCH response: " + r)
2690 except socket.timeout:
2691 pass
2692
2693 logger.debug("Valid M-SEARCH")
2694 msg = '\r\n'.join([
2695 'M-SEARCH * HTTP/1.1',
2696 'HOST: 239.255.255.250:1900',
2697 'MAN: "ssdp:discover"',
2698 'MX: 1',
2699 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2700 '', ''])
cc02ce96 2701 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2702
2703 try:
2704 r = sock.recv(1000)
2705 pass
2706 except socket.timeout:
2707 raise Exception("No SSDP response")
2708
2709def test_ap_wps_ssdp_burst(dev, apdev):
2710 """WPS AP and SSDP burst"""
2711 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2712 add_ssdp_ap(apdev[0], ap_uuid)
44ff0400
JM
2713
2714 msg = '\r\n'.join([
2715 'M-SEARCH * HTTP/1.1',
2716 'HOST: 239.255.255.250:1900',
2717 'MAN: "ssdp:discover"',
2718 'MX: 1',
2719 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2720 '', ''])
2721 socket.setdefaulttimeout(1)
2722 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2723 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2724 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2725 sock.bind(("127.0.0.1", 0))
2726 for i in range(0, 25):
cc02ce96 2727 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2728 resp = 0
2729 while True:
2730 try:
cc02ce96 2731 r = sock.recv(1000).decode()
44ff0400
JM
2732 if not r.startswith("HTTP/1.1 200 OK\r\n"):
2733 raise Exception("Unexpected message: " + r)
2734 resp += 1
2735 except socket.timeout:
2736 break
2737 if resp < 20:
2738 raise Exception("Too few SSDP responses")
2739
2740 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2741 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2742 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2743 sock.bind(("127.0.0.1", 0))
2744 for i in range(0, 25):
cc02ce96 2745 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
44ff0400
JM
2746 while True:
2747 try:
cc02ce96 2748 r = sock.recv(1000).decode()
44ff0400
JM
2749 if ap_uuid in r:
2750 break
2751 except socket.timeout:
2752 raise Exception("No SSDP response")
47c549fd
JM
2753
2754def ssdp_get_location(uuid):
2755 res = ssdp_send_msearch("uuid:" + uuid)
2756 location = None
2757 for l in res.splitlines():
2758 if l.lower().startswith("location:"):
2759 location = l.split(':', 1)[1].strip()
2760 break
2761 if location is None:
2762 raise Exception("No UPnP location found")
2763 return location
2764
2765def upnp_get_urls(location):
308ecbc1
MH
2766 if sys.version_info[0] > 2:
2767 conn = urlopen(location)
2768 else:
2769 conn = urlopen(location, proxies={})
47c549fd
JM
2770 tree = ET.parse(conn)
2771 root = tree.getroot()
2772 urn = '{urn:schemas-upnp-org:device-1-0}'
2773 service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
2774 res = {}
9c06eda0
MH
2775 res['scpd_url'] = urljoin(location, service.find(urn + 'SCPDURL').text)
2776 res['control_url'] = urljoin(location,
2777 service.find(urn + 'controlURL').text)
2778 res['event_sub_url'] = urljoin(location,
2779 service.find(urn + 'eventSubURL').text)
47c549fd
JM
2780 return res
2781
dd124ee8
JM
2782def upnp_soap_action(conn, path, action, include_soap_action=True,
2783 soap_action_override=None, newmsg=None, neweventtype=None,
2784 neweventmac=None):
47c549fd
JM
2785 soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
2786 wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
2787 ET.register_namespace('soapenv', soapns)
2788 ET.register_namespace('wfa', wpsns)
2789 attrib = {}
2790 attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
2791 root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
2792 body = ET.SubElement(root, "{%s}Body" % soapns)
2793 act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
dd124ee8
JM
2794 if newmsg:
2795 msg = ET.SubElement(act, "NewMessage")
c4e333fa 2796 msg.text = base64.b64encode(newmsg.encode()).decode()
dd124ee8
JM
2797 if neweventtype:
2798 msg = ET.SubElement(act, "NewWLANEventType")
2799 msg.text = neweventtype
2800 if neweventmac:
2801 msg = ET.SubElement(act, "NewWLANEventMAC")
2802 msg.text = neweventmac
47c549fd 2803
fab49f61 2804 headers = {"Content-type": 'text/xml; charset="utf-8"'}
47c549fd
JM
2805 if include_soap_action:
2806 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
2807 elif soap_action_override:
2808 headers["SOAPAction"] = soap_action_override
69f58282
MH
2809 decl = b'<?xml version=\'1.0\' encoding=\'utf8\'?>\n'
2810 conn.request("POST", path, decl + ET.tostring(root), headers)
47c549fd
JM
2811 return conn.getresponse()
2812
2813def test_ap_wps_upnp(dev, apdev):
2814 """WPS AP and UPnP operations"""
2815 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2816 add_ssdp_ap(apdev[0], ap_uuid)
47c549fd
JM
2817
2818 location = ssdp_get_location(ap_uuid)
2819 urls = upnp_get_urls(location)
2820
308ecbc1
MH
2821 if sys.version_info[0] > 2:
2822 conn = urlopen(urls['scpd_url'])
2823 else:
2824 conn = urlopen(urls['scpd_url'], proxies={})
47c549fd
JM
2825 scpd = conn.read()
2826
308ecbc1
MH
2827 if sys.version_info[0] > 2:
2828 try:
2829 conn = urlopen(urljoin(location, "unknown.html"))
2830 raise Exception("Unexpected HTTP response to GET unknown URL")
2831 except HTTPError as e:
2832 if e.code != 404:
2833 raise Exception("Unexpected HTTP response to GET unknown URL")
2834 else:
2835 conn = urlopen(urljoin(location, "unknown.html"), proxies={})
2836 if conn.getcode() != 404:
2837 raise Exception("Unexpected HTTP response to GET unknown URL")
47c549fd 2838
9c06eda0
MH
2839 url = urlparse(location)
2840 conn = HTTPConnection(url.netloc)
47c549fd 2841 #conn.set_debuglevel(1)
fab49f61
JM
2842 headers = {"Content-type": 'text/xml; charset="utf-8"',
2843 "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"'}
47c549fd
JM
2844 conn.request("POST", "hello", "\r\n\r\n", headers)
2845 resp = conn.getresponse()
2846 if resp.status != 404:
5c267d71 2847 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2848
2849 conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
2850 resp = conn.getresponse()
2851 if resp.status != 501:
5c267d71 2852 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd 2853
fab49f61
JM
2854 headers = {"Content-type": 'text/xml; charset="utf-8"',
2855 "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"'}
9c06eda0 2856 ctrlurl = urlparse(urls['control_url'])
47c549fd
JM
2857 conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
2858 resp = conn.getresponse()
2859 if resp.status != 401:
5c267d71 2860 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2861
2862 logger.debug("GetDeviceInfo without SOAPAction header")
2863 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2864 include_soap_action=False)
2865 if resp.status != 401:
5c267d71 2866 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2867
2868 logger.debug("GetDeviceInfo with invalid SOAPAction header")
fab49f61
JM
2869 for act in ["foo",
2870 "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
2871 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
2872 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
47c549fd
JM
2873 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2874 include_soap_action=False,
2875 soap_action_override=act)
2876 if resp.status != 401:
5c267d71 2877 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2878
2879 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
2880 if resp.status != 200:
5c267d71 2881 raise Exception("Unexpected HTTP response: %d" % resp.status)
732b7613 2882 dev = resp.read().decode()
47c549fd
JM
2883 if "NewDeviceInfo" not in dev:
2884 raise Exception("Unexpected GetDeviceInfo response")
2885
2886 logger.debug("PutMessage without required parameters")
2887 resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
2888 if resp.status != 600:
5c267d71 2889 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2890
2891 logger.debug("PutWLANResponse without required parameters")
2892 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
2893 if resp.status != 600:
5c267d71 2894 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2895
2896 logger.debug("SetSelectedRegistrar from unregistered ER")
2897 resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
2898 if resp.status != 501:
5c267d71 2899 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2900
2901 logger.debug("Unknown action")
2902 resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
2903 if resp.status != 401:
5c267d71 2904 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2905
2906def test_ap_wps_upnp_subscribe(dev, apdev):
2907 """WPS AP and UPnP event subscription"""
2908 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2909 hapd = add_ssdp_ap(apdev[0], ap_uuid)
47c549fd
JM
2910
2911 location = ssdp_get_location(ap_uuid)
2912 urls = upnp_get_urls(location)
9c06eda0 2913 eventurl = urlparse(urls['event_sub_url'])
47c549fd 2914
9c06eda0
MH
2915 url = urlparse(location)
2916 conn = HTTPConnection(url.netloc)
47c549fd 2917 #conn.set_debuglevel(1)
fab49f61
JM
2918 headers = {"callback": '<http://127.0.0.1:12345/event>',
2919 "timeout": "Second-1234"}
47c549fd
JM
2920 conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
2921 resp = conn.getresponse()
2922 if resp.status != 412:
5c267d71 2923 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2924
2925 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2926 resp = conn.getresponse()
2927 if resp.status != 412:
5c267d71 2928 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd 2929
fab49f61
JM
2930 headers = {"NT": "upnp:event",
2931 "timeout": "Second-1234"}
47c549fd
JM
2932 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2933 resp = conn.getresponse()
2934 if resp.status != 412:
5c267d71 2935 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd 2936
fab49f61
JM
2937 headers = {"callback": '<http://127.0.0.1:12345/event>',
2938 "NT": "upnp:foobar",
2939 "timeout": "Second-1234"}
47c549fd
JM
2940 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2941 resp = conn.getresponse()
2942 if resp.status != 400:
5c267d71 2943 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2944
2945 logger.debug("Valid subscription")
fab49f61
JM
2946 headers = {"callback": '<http://127.0.0.1:12345/event>',
2947 "NT": "upnp:event",
2948 "timeout": "Second-1234"}
47c549fd
JM
2949 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2950 resp = conn.getresponse()
2951 if resp.status != 200:
5c267d71 2952 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2953 sid = resp.getheader("sid")
2954 logger.debug("Subscription SID " + sid)
2955
2956 logger.debug("Invalid re-subscription")
fab49f61
JM
2957 headers = {"NT": "upnp:event",
2958 "sid": "123456734567854",
2959 "timeout": "Second-1234"}
47c549fd
JM
2960 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2961 resp = conn.getresponse()
2962 if resp.status != 400:
5c267d71 2963 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2964
2965 logger.debug("Invalid re-subscription")
fab49f61
JM
2966 headers = {"NT": "upnp:event",
2967 "sid": "uuid:123456734567854",
2968 "timeout": "Second-1234"}
47c549fd
JM
2969 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2970 resp = conn.getresponse()
2971 if resp.status != 400:
5c267d71 2972 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2973
2974 logger.debug("Invalid re-subscription")
fab49f61
JM
2975 headers = {"callback": '<http://127.0.0.1:12345/event>',
2976 "NT": "upnp:event",
2977 "sid": sid,
2978 "timeout": "Second-1234"}
47c549fd
JM
2979 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2980 resp = conn.getresponse()
2981 if resp.status != 400:
5c267d71 2982 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2983
2984 logger.debug("SID mismatch in re-subscription")
fab49f61
JM
2985 headers = {"NT": "upnp:event",
2986 "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
2987 "timeout": "Second-1234"}
47c549fd
JM
2988 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2989 resp = conn.getresponse()
2990 if resp.status != 412:
5c267d71 2991 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2992
2993 logger.debug("Valid re-subscription")
fab49f61
JM
2994 headers = {"NT": "upnp:event",
2995 "sid": sid,
2996 "timeout": "Second-1234"}
47c549fd
JM
2997 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2998 resp = conn.getresponse()
2999 if resp.status != 200:
5c267d71 3000 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3001 sid2 = resp.getheader("sid")
3002 logger.debug("Subscription SID " + sid2)
3003
3004 if sid != sid2:
3005 raise Exception("Unexpected SID change")
3006
3007 logger.debug("Valid re-subscription")
fab49f61
JM
3008 headers = {"NT": "upnp:event",
3009 "sid": "uuid: \t \t" + sid.split(':')[1],
3010 "timeout": "Second-1234"}
47c549fd
JM
3011 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3012 resp = conn.getresponse()
3013 if resp.status != 200:
5c267d71 3014 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3015
3016 logger.debug("Invalid unsubscription")
fab49f61 3017 headers = {"sid": sid}
47c549fd
JM
3018 conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
3019 resp = conn.getresponse()
3020 if resp.status != 412:
5c267d71 3021 raise Exception("Unexpected HTTP response: %d" % resp.status)
fab49f61 3022 headers = {"foo": "bar"}
47c549fd
JM
3023 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3024 resp = conn.getresponse()
3025 if resp.status != 412:
5c267d71 3026 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3027
3028 logger.debug("Valid unsubscription")
fab49f61 3029 headers = {"sid": sid}
47c549fd
JM
3030 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3031 resp = conn.getresponse()
3032 if resp.status != 200:
5c267d71 3033 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3034
3035 logger.debug("Unsubscription for not existing SID")
fab49f61 3036 headers = {"sid": sid}
47c549fd
JM
3037 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3038 resp = conn.getresponse()
3039 if resp.status != 412:
5c267d71 3040 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3041
3042 logger.debug("Invalid unsubscription")
fab49f61 3043 headers = {"sid": " \t \tfoo"}
47c549fd
JM
3044 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3045 resp = conn.getresponse()
3046 if resp.status != 400:
5c267d71 3047 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3048
3049 logger.debug("Invalid unsubscription")
fab49f61 3050 headers = {"sid": "uuid:\t \tfoo"}
47c549fd
JM
3051 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3052 resp = conn.getresponse()
3053 if resp.status != 400:
5c267d71 3054 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3055
3056 logger.debug("Invalid unsubscription")
fab49f61
JM
3057 headers = {"NT": "upnp:event",
3058 "sid": sid}
47c549fd
JM
3059 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3060 resp = conn.getresponse()
3061 if resp.status != 400:
5c267d71 3062 raise Exception("Unexpected HTTP response: %d" % resp.status)
fab49f61
JM
3063 headers = {"callback": '<http://127.0.0.1:12345/event>',
3064 "sid": sid}
47c549fd
JM
3065 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3066 resp = conn.getresponse()
3067 if resp.status != 400:
5c267d71 3068 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3069
3070 logger.debug("Valid subscription with multiple callbacks")
fab49f61
JM
3071 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>',
3072 "NT": "upnp:event",
3073 "timeout": "Second-1234"}
47c549fd
JM
3074 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3075 resp = conn.getresponse()
3076 if resp.status != 200:
5c267d71 3077 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3078 sid = resp.getheader("sid")
3079 logger.debug("Subscription SID " + sid)
d352c407 3080
24b7f282
JM
3081 # Force subscription to be deleted due to errors
3082 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3083 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3084 with alloc_fail(hapd, 1, "event_build_message"):
3085 for i in range(10):
3086 dev[1].dump_monitor()
3087 dev[2].dump_monitor()
3088 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3089 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3090 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3091 dev[1].request("WPS_CANCEL")
3092 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3093 dev[2].request("WPS_CANCEL")
3094 if i % 4 == 1:
3095 time.sleep(1)
3096 else:
3097 time.sleep(0.1)
3098 time.sleep(0.2)
3099
fab49f61 3100 headers = {"sid": sid}
24b7f282
JM
3101 conn.request("UNSUBSCRIBE", eventurl.path, "", headers)
3102 resp = conn.getresponse()
3103 if resp.status != 200 and resp.status != 412:
3104 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3105
fab49f61
JM
3106 headers = {"callback": '<http://127.0.0.1:12345/event>',
3107 "NT": "upnp:event",
3108 "timeout": "Second-1234"}
24b7f282
JM
3109 with alloc_fail(hapd, 1, "http_client_addr;event_send_start"):
3110 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3111 resp = conn.getresponse()
3112 if resp.status != 200:
3113 raise Exception("Unexpected HTTP response for SUBSCRIBE: %d" % resp.status)
3114 sid = resp.getheader("sid")
3115 logger.debug("Subscription SID " + sid)
3116
fab49f61 3117 headers = {"sid": sid}
24b7f282
JM
3118 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3119 resp = conn.getresponse()
3120 if resp.status != 200:
3121 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3122
fab49f61
JM
3123 headers = {"callback": '<http://127.0.0.1:12345/event>',
3124 "NT": "upnp:event",
3125 "timeout": "Second-1234"}
24b7f282
JM
3126 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3127 resp = conn.getresponse()
3128 if resp.status != 200:
3129 raise Exception("Unexpected HTTP response: %d" % resp.status)
3130 sid = resp.getheader("sid")
3131 logger.debug("Subscription SID " + sid)
3132
3133 with alloc_fail(hapd, 1, "=event_add"):
3134 for i in range(2):
3135 dev[1].dump_monitor()
3136 dev[2].dump_monitor()
3137 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3138 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3139 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3140 dev[1].request("WPS_CANCEL")
3141 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3142 dev[2].request("WPS_CANCEL")
3143 if i == 0:
3144 time.sleep(1)
3145 else:
3146 time.sleep(0.1)
3147
3148 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3149 resp = conn.getresponse()
3150 if resp.status != 200:
3151 raise Exception("Unexpected HTTP response: %d" % resp.status)
3152
3153 with alloc_fail(hapd, 1, "wpabuf_dup;event_add"):
3154 dev[1].dump_monitor()
3155 dev[2].dump_monitor()
3156 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3157 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3158 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3159 dev[1].request("WPS_CANCEL")
3160 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3161 dev[2].request("WPS_CANCEL")
3162 time.sleep(0.1)
3163
3164 with fail_test(hapd, 1, "os_get_random;uuid_make;subscription_start"):
3165 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3166 resp = conn.getresponse()
3167 if resp.status != 500:
3168 raise Exception("Unexpected HTTP response: %d" % resp.status)
3169
3170 with alloc_fail(hapd, 1, "=subscription_start"):
3171 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3172 resp = conn.getresponse()
3173 if resp.status != 500:
3174 raise Exception("Unexpected HTTP response: %d" % resp.status)
3175
fab49f61
JM
3176 headers = {"callback": '',
3177 "NT": "upnp:event",
3178 "timeout": "Second-1234"}
24b7f282
JM
3179 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3180 resp = conn.getresponse()
3181 if resp.status != 500:
3182 raise Exception("Unexpected HTTP response: %d" % resp.status)
3183
fab49f61
JM
3184 headers = {"callback": ' <',
3185 "NT": "upnp:event",
3186 "timeout": "Second-1234"}
24b7f282
JM
3187 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3188 resp = conn.getresponse()
3189 if resp.status != 500:
3190 raise Exception("Unexpected HTTP response: %d" % resp.status)
3191
fab49f61
JM
3192 headers = {"callback": '<http://127.0.0.1:12345/event>',
3193 "NT": "upnp:event",
3194 "timeout": "Second-1234"}
24b7f282
JM
3195 with alloc_fail(hapd, 1, "wpabuf_alloc;subscription_first_event"):
3196 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3197 resp = conn.getresponse()
3198 if resp.status != 500:
3199 raise Exception("Unexpected HTTP response: %d" % resp.status)
3200
3201 with alloc_fail(hapd, 1, "event_add;subscription_first_event"):
3202 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3203 resp = conn.getresponse()
3204 if resp.status != 500:
3205 raise Exception("Unexpected HTTP response: %d" % resp.status)
3206
3207 with alloc_fail(hapd, 1, "subscr_addr_add_url"):
3208 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3209 resp = conn.getresponse()
3210 if resp.status != 500:
3211 raise Exception("Unexpected HTTP response: %d" % resp.status)
3212
3213 with alloc_fail(hapd, 2, "subscr_addr_add_url"):
3214 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3215 resp = conn.getresponse()
3216 if resp.status != 500:
3217 raise Exception("Unexpected HTTP response: %d" % resp.status)
3218
3219 for i in range(6):
fab49f61
JM
3220 headers = {"callback": '<http://127.0.0.1:%d/event>' % (12345 + i),
3221 "NT": "upnp:event",
3222 "timeout": "Second-1234"}
24b7f282
JM
3223 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3224 resp = conn.getresponse()
3225 if resp.status != 200:
3226 raise Exception("Unexpected HTTP response: %d" % resp.status)
3227
3228 with alloc_fail(hapd, 1, "=upnp_wps_device_send_wlan_event"):
3229 dev[1].dump_monitor()
3230 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3231 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3232 dev[1].request("WPS_CANCEL")
3233 time.sleep(0.1)
3234
3235 with alloc_fail(hapd, 1, "wpabuf_alloc;upnp_wps_device_send_event"):
3236 dev[1].dump_monitor()
3237 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3238 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3239 dev[1].request("WPS_CANCEL")
3240 time.sleep(0.1)
3241
5b52e1ad
JM
3242 with alloc_fail(hapd, 1,
3243 "base64_gen_encode;?base64_encode;upnp_wps_device_send_wlan_event"):
24b7f282
JM
3244 dev[1].dump_monitor()
3245 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3246 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3247 dev[1].request("WPS_CANCEL")
3248 time.sleep(0.1)
3249
3250 hapd.disable()
3251 with alloc_fail(hapd, 1, "get_netif_info"):
3252 if "FAIL" not in hapd.request("ENABLE"):
3253 raise Exception("ENABLE succeeded during OOM")
3254
d91a64c4
JM
3255def test_ap_wps_upnp_subscribe_events(dev, apdev):
3256 """WPS AP and UPnP event subscription and many events"""
3257 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 3258 hapd = add_ssdp_ap(apdev[0], ap_uuid)
d91a64c4
JM
3259
3260 location = ssdp_get_location(ap_uuid)
3261 urls = upnp_get_urls(location)
9c06eda0 3262 eventurl = urlparse(urls['event_sub_url'])
d91a64c4 3263
9c06eda0 3264 class WPSERHTTPServer(StreamRequestHandler):
d91a64c4
JM
3265 def handle(self):
3266 data = self.rfile.readline().strip()
3267 logger.debug(data)
3268 self.wfile.write(gen_wps_event())
3269
3270 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
3271 server.timeout = 1
3272
9c06eda0
MH
3273 url = urlparse(location)
3274 conn = HTTPConnection(url.netloc)
d91a64c4 3275
fab49f61
JM
3276 headers = {"callback": '<http://127.0.0.1:12345/event>',
3277 "NT": "upnp:event",
3278 "timeout": "Second-1234"}
d91a64c4
JM
3279 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3280 resp = conn.getresponse()
3281 if resp.status != 200:
3282 raise Exception("Unexpected HTTP response: %d" % resp.status)
3283 sid = resp.getheader("sid")
3284 logger.debug("Subscription SID " + sid)
3285
3286 # Fetch the first event message
3287 server.handle_request()
3288
3289 # Force subscription event queue to reach the maximum length by generating
3290 # new proxied events without the ER fetching any of the pending events.
3291 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3292 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3293 for i in range(16):
3294 dev[1].dump_monitor()
3295 dev[2].dump_monitor()
3296 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3297 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3298 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3299 dev[1].request("WPS_CANCEL")
3300 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3301 dev[2].request("WPS_CANCEL")
3302 if i % 4 == 1:
3303 time.sleep(1)
3304 else:
3305 time.sleep(0.1)
3306
3307 hapd.request("WPS_PIN any 12345670")
3308 dev[1].dump_monitor()
3309 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3310 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=10)
3311 if ev is None:
3312 raise Exception("WPS success not reported")
3313
3314 # Close the WPS ER HTTP server without fetching all the pending events.
3315 # This tests hostapd code path that clears subscription and the remaining
3316 # event queue when the interface is deinitialized.
3317 server.handle_request()
3318 server.server_close()
3319
3320 dev[1].wait_connected()
3321
b2047531
JM
3322def test_ap_wps_upnp_http_proto(dev, apdev):
3323 """WPS AP and UPnP/HTTP protocol testing"""
3324 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 3325 add_ssdp_ap(apdev[0], ap_uuid)
b2047531
JM
3326
3327 location = ssdp_get_location(ap_uuid)
3328
9c06eda0
MH
3329 url = urlparse(location)
3330 conn = HTTPConnection(url.netloc, timeout=0.2)
b2047531
JM
3331 #conn.set_debuglevel(1)
3332
3333 conn.request("HEAD", "hello")
3334 resp = conn.getresponse()
3335 if resp.status != 501:
3336 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3337 conn.close()
3338
fab49f61 3339 for cmd in ["PUT", "DELETE", "TRACE", "CONNECT", "M-SEARCH", "M-POST"]:
b2047531
JM
3340 try:
3341 conn.request(cmd, "hello")
3342 resp = conn.getresponse()
bab493b9 3343 except Exception as e:
b2047531
JM
3344 pass
3345 conn.close()
3346
fab49f61 3347 headers = {"Content-Length": 'abc'}
b2047531
JM
3348 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3349 try:
3350 resp = conn.getresponse()
bab493b9 3351 except Exception as e:
b2047531
JM
3352 pass
3353 conn.close()
3354
fab49f61 3355 headers = {"Content-Length": '-10'}
b2047531
JM
3356 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3357 try:
3358 resp = conn.getresponse()
bab493b9 3359 except Exception as e:
b2047531
JM
3360 pass
3361 conn.close()
3362
fab49f61 3363 headers = {"Content-Length": '10000000000000'}
b2047531
JM
3364 conn.request("HEAD", "hello", "\r\n\r\nhello", headers)
3365 try:
3366 resp = conn.getresponse()
bab493b9 3367 except Exception as e:
b2047531
JM
3368 pass
3369 conn.close()
3370
fab49f61 3371 headers = {"Transfer-Encoding": 'abc'}
b2047531
JM
3372 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3373 resp = conn.getresponse()
3374 if resp.status != 501:
3375 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3376 conn.close()
3377
fab49f61 3378 headers = {"Transfer-Encoding": 'chunked'}
b2047531
JM
3379 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3380 resp = conn.getresponse()
3381 if resp.status != 501:
3382 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3383 conn.close()
3384
3385 # Too long a header
3386 conn.request("HEAD", 5000 * 'A')
3387 try:
3388 resp = conn.getresponse()
bab493b9 3389 except Exception as e:
b2047531
JM
3390 pass
3391 conn.close()
3392
3393 # Long URL but within header length limits
3394 conn.request("HEAD", 3000 * 'A')
3395 resp = conn.getresponse()
3396 if resp.status != 501:
3397 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3398 conn.close()
3399
fab49f61 3400 headers = {"Content-Length": '20'}
b2047531
JM
3401 conn.request("POST", "hello", 10 * 'A' + "\r\n\r\n", headers)
3402 try:
3403 resp = conn.getresponse()
bab493b9 3404 except Exception as e:
b2047531
JM
3405 pass
3406 conn.close()
3407
3408 conn.request("POST", "hello", 5000 * 'A' + "\r\n\r\n")
3409 resp = conn.getresponse()
3410 if resp.status != 404:
5c267d71 3411 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
3412 conn.close()
3413
3414 conn.request("POST", "hello", 60000 * 'A' + "\r\n\r\n")
3415 try:
3416 resp = conn.getresponse()
bab493b9 3417 except Exception as e:
b2047531
JM
3418 pass
3419 conn.close()
3420
3421def test_ap_wps_upnp_http_proto_chunked(dev, apdev):
3422 """WPS AP and UPnP/HTTP protocol testing for chunked encoding"""
3423 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 3424 add_ssdp_ap(apdev[0], ap_uuid)
b2047531
JM
3425
3426 location = ssdp_get_location(ap_uuid)
3427
9c06eda0
MH
3428 url = urlparse(location)
3429 conn = HTTPConnection(url.netloc)
b2047531
JM
3430 #conn.set_debuglevel(1)
3431
fab49f61 3432 headers = {"Transfer-Encoding": 'chunked'}
b2047531
JM
3433 conn.request("POST", "hello",
3434 "a\r\nabcdefghij\r\n" + "2\r\nkl\r\n" + "0\r\n\r\n",
3435 headers)
3436 resp = conn.getresponse()
3437 if resp.status != 404:
5c267d71 3438 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
3439 conn.close()
3440
3441 conn.putrequest("POST", "hello")
3442 conn.putheader('Transfer-Encoding', 'chunked')
3443 conn.endheaders()
cc02ce96 3444 conn.send(b"a\r\nabcdefghij\r\n")
b2047531 3445 time.sleep(0.1)
cc02ce96
MH
3446 conn.send(b"2\r\nkl\r\n")
3447 conn.send(b"0\r\n\r\n")
b2047531
JM
3448 resp = conn.getresponse()
3449 if resp.status != 404:
5c267d71 3450 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
3451 conn.close()
3452
3453 conn.putrequest("POST", "hello")
3454 conn.putheader('Transfer-Encoding', 'chunked')
3455 conn.endheaders()
3456 completed = False
3457 try:
3458 for i in range(20000):
cc02ce96
MH
3459 conn.send(b"1\r\nZ\r\n")
3460 conn.send(b"0\r\n\r\n")
b2047531
JM
3461 resp = conn.getresponse()
3462 completed = True
bab493b9 3463 except Exception as e:
b2047531
JM
3464 pass
3465 conn.close()
3466 if completed:
3467 raise Exception("Too long chunked request did not result in connection reset")
3468
fab49f61 3469 headers = {"Transfer-Encoding": 'chunked'}
b2047531
JM
3470 conn.request("POST", "hello", "80000000\r\na", headers)
3471 try:
3472 resp = conn.getresponse()
bab493b9 3473 except Exception as e:
b2047531
JM
3474 pass
3475 conn.close()
3476
3477 conn.request("POST", "hello", "10000000\r\na", headers)
3478 try:
3479 resp = conn.getresponse()
bab493b9 3480 except Exception as e:
b2047531
JM
3481 pass
3482 conn.close()
3483
9fd6804d 3484@remote_compatible
d352c407
JM
3485def test_ap_wps_disabled(dev, apdev):
3486 """WPS operations while WPS is disabled"""
3487 ssid = "test-wps-disabled"
fab49f61 3488 hapd = hostapd.add_ap(apdev[0], {"ssid": ssid})
d352c407
JM
3489 if "FAIL" not in hapd.request("WPS_PBC"):
3490 raise Exception("WPS_PBC succeeded unexpectedly")
3491 if "FAIL" not in hapd.request("WPS_CANCEL"):
3492 raise Exception("WPS_CANCEL succeeded unexpectedly")
a0fd2ae6
JM
3493
3494def test_ap_wps_mixed_cred(dev, apdev):
3495 """WPS 2.0 STA merging mixed mode WPA/WPA2 credentials"""
3496 ssid = "test-wps-wep"
fab49f61
JM
3497 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3498 "skip_cred_build": "1", "extra_cred": "wps-mixed-cred"}
6f334bf7 3499 hapd = hostapd.add_ap(apdev[0], params)
a0fd2ae6 3500 hapd.request("WPS_PBC")
33d0b157
JM
3501 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3502 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
9ed53f5e 3503 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
a0fd2ae6
JM
3504 if ev is None:
3505 raise Exception("WPS-SUCCESS event timed out")
3506 nets = dev[0].list_networks()
3507 if len(nets) != 1:
3508 raise Exception("Unexpected number of network blocks")
3509 id = nets[0]['id']
3510 proto = dev[0].get_network(id, "proto")
3511 if proto != "WPA RSN":
3512 raise Exception("Unexpected merged proto field value: " + proto)
3513 pairwise = dev[0].get_network(id, "pairwise")
70dcb4aa
JM
3514 p = pairwise.split()
3515 if "CCMP" not in p or "TKIP" not in p:
a0fd2ae6 3516 raise Exception("Unexpected merged pairwise field value: " + pairwise)
e5a79e3f 3517
9fd6804d 3518@remote_compatible
e5a79e3f
JM
3519def test_ap_wps_while_connected(dev, apdev):
3520 """WPS PBC provisioning while connected to another AP"""
3521 ssid = "test-wps-conf"
6f334bf7 3522 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
3523 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3524 "wpa_passphrase": "12345678", "wpa": "2",
3525 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e5a79e3f 3526
fab49f61 3527 hostapd.add_ap(apdev[1], {"ssid": "open"})
e5a79e3f
JM
3528 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3529
3530 logger.info("WPS provisioning step")
3531 hapd.request("WPS_PBC")
3532 dev[0].dump_monitor()
33d0b157 3533 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 3534 dev[0].wait_connected(timeout=30)
e5a79e3f
JM
3535 status = dev[0].get_status()
3536 if status['bssid'] != apdev[0]['bssid']:
3537 raise Exception("Unexpected BSSID")
3538
9fd6804d 3539@remote_compatible
e5a79e3f
JM
3540def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
3541 """WPS PBC provisioning while connected to another AP and STA_AUTOCONNECT disabled"""
3542 ssid = "test-wps-conf"
6f334bf7 3543 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
3544 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3545 "wpa_passphrase": "12345678", "wpa": "2",
3546 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e5a79e3f 3547
fab49f61 3548 hostapd.add_ap(apdev[1], {"ssid": "open"})
e5a79e3f
JM
3549
3550 try:
3551 dev[0].request("STA_AUTOCONNECT 0")
3552 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3553
3554 logger.info("WPS provisioning step")
3555 hapd.request("WPS_PBC")
3556 dev[0].dump_monitor()
33d0b157 3557 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 3558 dev[0].wait_connected(timeout=30)
e5a79e3f
JM
3559 status = dev[0].get_status()
3560 if status['bssid'] != apdev[0]['bssid']:
3561 raise Exception("Unexpected BSSID")
3562 finally:
3563 dev[0].request("STA_AUTOCONNECT 1")
3f08d1cd 3564
9fd6804d 3565@remote_compatible
3f08d1cd
JM
3566def test_ap_wps_from_event(dev, apdev):
3567 """WPS PBC event on AP to enable PBC"""
3568 ssid = "test-wps-conf"
8b8a1864 3569 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
3570 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3571 "wpa_passphrase": "12345678", "wpa": "2",
3572 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
33d0b157 3573 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3f08d1cd 3574 dev[0].dump_monitor()
33d0b157
JM
3575 hapd.dump_monitor()
3576 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3f08d1cd
JM
3577
3578 ev = hapd.wait_event(['WPS-ENROLLEE-SEEN'], timeout=15)
3579 if ev is None:
3580 raise Exception("No WPS-ENROLLEE-SEEN event on AP")
3581 vals = ev.split(' ')
3582 if vals[1] != dev[0].p2p_interface_addr():
3583 raise Exception("Unexpected enrollee address: " + vals[1])
3584 if vals[5] != '4':
3585 raise Exception("Unexpected Device Password Id: " + vals[5])
3586 hapd.request("WPS_PBC")
5f35a5e2 3587 dev[0].wait_connected(timeout=30)
1531402e
JM
3588
3589def test_ap_wps_ap_scan_2(dev, apdev):
3590 """AP_SCAN 2 for WPS"""
3591 ssid = "test-wps-conf"
8b8a1864 3592 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
3593 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3594 "wpa_passphrase": "12345678", "wpa": "2",
3595 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
1531402e
JM
3596 hapd.request("WPS_PBC")
3597
3598 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
3599 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
4b9d79b6 3600 wpas.dump_monitor()
1531402e
JM
3601
3602 if "OK" not in wpas.request("AP_SCAN 2"):
3603 raise Exception("Failed to set AP_SCAN 2")
3604
e51c8b2e 3605 wpas.flush_scan_cache()
33d0b157 3606 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
4b9d79b6 3607 wpas.dump_monitor()
33d0b157 3608 wpas.request("WPS_PBC " + apdev[0]['bssid'])
1531402e
JM
3609 ev = wpas.wait_event(["WPS-SUCCESS"], timeout=15)
3610 if ev is None:
3611 raise Exception("WPS-SUCCESS event timed out")
5f35a5e2 3612 wpas.wait_connected(timeout=30)
4b9d79b6 3613 wpas.dump_monitor()
1531402e 3614 wpas.request("DISCONNECT")
59642ca9
JM
3615 wpas.wait_disconnected()
3616 id = wpas.list_networks()[0]['id']
3617 pairwise = wpas.get_network(id, "pairwise")
3618 if "CCMP" not in pairwise.split():
3619 raise Exception("Unexpected pairwise parameter value: " + pairwise)
3620 group = wpas.get_network(id, "group")
3621 if "CCMP" not in group.split():
3622 raise Exception("Unexpected group parameter value: " + group)
3623 # Need to select a single cipher for ap_scan=2 testing
3624 wpas.set_network(id, "pairwise", "CCMP")
3625 wpas.set_network(id, "group", "CCMP")
1531402e
JM
3626 wpas.request("BSS_FLUSH 0")
3627 wpas.dump_monitor()
3628 wpas.request("REASSOCIATE")
5f35a5e2 3629 wpas.wait_connected(timeout=30)
4b9d79b6 3630 wpas.dump_monitor()
8b944cf7
JM
3631 wpas.request("DISCONNECT")
3632 wpas.wait_disconnected()
3633 wpas.flush_scan_cache()
a08fdb17 3634
9fd6804d 3635@remote_compatible
a08fdb17
JM
3636def test_ap_wps_eapol_workaround(dev, apdev):
3637 """EAPOL workaround code path for 802.1X header length mismatch"""
3638 ssid = "test-wps"
6f334bf7 3639 hapd = hostapd.add_ap(apdev[0],
fab49f61 3640 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
a08fdb17
JM
3641 bssid = apdev[0]['bssid']
3642 hapd.request("SET ext_eapol_frame_io 1")
3643 dev[0].request("SET ext_eapol_frame_io 1")
3644 hapd.request("WPS_PBC")
3645 dev[0].request("WPS_PBC")
3646
3647 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3648 if ev is None:
3649 raise Exception("Timeout on EAPOL-TX from hostapd")
3650
3651 res = dev[0].request("EAPOL_RX " + bssid + " 020000040193000501FFFF")
3652 if "OK" not in res:
3653 raise Exception("EAPOL_RX to wpa_supplicant failed")
46dea617
JM
3654
3655def test_ap_wps_iteration(dev, apdev):
3656 """WPS PIN and iterate through APs without selected registrar"""
3657 ssid = "test-wps-conf"
8b8a1864 3658 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
3659 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3660 "wpa_passphrase": "12345678", "wpa": "2",
3661 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
46dea617
JM
3662
3663 ssid2 = "test-wps-conf2"
8b8a1864 3664 hapd2 = hostapd.add_ap(apdev[1],
fab49f61
JM
3665 {"ssid": ssid2, "eap_server": "1", "wps_state": "2",
3666 "wpa_passphrase": "12345678", "wpa": "2",
3667 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
46dea617
JM
3668
3669 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3670 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
3671 dev[0].dump_monitor()
3672 pin = dev[0].request("WPS_PIN any")
3673
3674 # Wait for iteration through all WPS APs to happen before enabling any
3675 # Registrar.
3676 for i in range(2):
3677 ev = dev[0].wait_event(["Associated with"], timeout=30)
3678 if ev is None:
3679 raise Exception("No association seen")
3680 ev = dev[0].wait_event(["WPS-M2D"], timeout=10)
3681 if ev is None:
3682 raise Exception("No M2D from AP")
3683 dev[0].wait_disconnected()
3684
3685 # Verify that each AP requested PIN
3686 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3687 if ev is None:
3688 raise Exception("No WPS-PIN-NEEDED event from AP")
3689 ev = hapd2.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3690 if ev is None:
3691 raise Exception("No WPS-PIN-NEEDED event from AP2")
3692
3693 # Provide PIN to one of the APs and verify that connection gets formed
3694 hapd.request("WPS_PIN any " + pin)
3695 dev[0].wait_connected(timeout=30)
2272f5aa
JM
3696
3697def test_ap_wps_iteration_error(dev, apdev):
3698 """WPS AP iteration on no Selected Registrar and error case with an AP"""
3699 ssid = "test-wps-conf-pin"
8b8a1864 3700 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
3701 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3702 "wpa_passphrase": "12345678", "wpa": "2",
3703 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3704 "wps_independent": "1"})
2272f5aa
JM
3705 hapd.request("SET ext_eapol_frame_io 1")
3706 bssid = apdev[0]['bssid']
3707 pin = dev[0].wps_read_pin()
3708 dev[0].request("WPS_PIN any " + pin)
3709
3710 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3711 if ev is None:
3712 raise Exception("No EAPOL-TX (EAP-Request/Identity) from hostapd")
3713 dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
3714
3715 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3716 if ev is None:
3717 raise Exception("No EAPOL-TX (EAP-WSC/Start) from hostapd")
3718 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=5)
3719 if ev is None:
3720 raise Exception("No CTRL-EVENT-EAP-STARTED")
3721
3722 # Do not forward any more EAPOL frames to test wpa_supplicant behavior for
3723 # a case with an incorrectly behaving WPS AP.
3724
3725 # Start the real target AP and activate registrar on it.
8b8a1864 3726 hapd2 = hostapd.add_ap(apdev[1],
fab49f61
JM
3727 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3728 "wpa_passphrase": "12345678", "wpa": "2",
3729 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3730 "wps_independent": "1"})
2272f5aa
JM
3731 hapd2.request("WPS_PIN any " + pin)
3732
3733 dev[0].wait_disconnected(timeout=15)
3734 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
3735 if ev is None:
3736 raise Exception("No CTRL-EVENT-EAP-STARTED for the second AP")
3737 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
3738 if ev is None:
3739 raise Exception("No WPS-CRED-RECEIVED for the second AP")
3740 dev[0].wait_connected(timeout=15)
d6f6a86a 3741
9fd6804d 3742@remote_compatible
d6f6a86a
JM
3743def test_ap_wps_priority(dev, apdev):
3744 """WPS PIN provisioning with configured AP and wps_priority"""
3745 ssid = "test-wps-conf-pin"
6f334bf7 3746 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
3747 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3748 "wpa_passphrase": "12345678", "wpa": "2",
3749 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
d6f6a86a
JM
3750 logger.info("WPS provisioning step")
3751 pin = dev[0].wps_read_pin()
3752 hapd.request("WPS_PIN any " + pin)
3753 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3754 dev[0].dump_monitor()
3755 try:
3756 dev[0].request("SET wps_priority 6")
3757 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3758 dev[0].wait_connected(timeout=30)
3759 netw = dev[0].list_networks()
3760 prio = dev[0].get_network(netw[0]['id'], 'priority')
3761 if prio != '6':
3762 raise Exception("Unexpected network priority: " + prio)
3763 finally:
3764 dev[0].request("SET wps_priority 0")
2c3a0190 3765
9fd6804d 3766@remote_compatible
df1d01cf
JM
3767def test_ap_wps_and_non_wps(dev, apdev):
3768 """WPS and non-WPS AP in single hostapd process"""
fab49f61 3769 params = {"ssid": "wps", "eap_server": "1", "wps_state": "1"}
8b8a1864 3770 hapd = hostapd.add_ap(apdev[0], params)
df1d01cf 3771
fab49f61 3772 params = {"ssid": "no wps"}
8b8a1864 3773 hapd2 = hostapd.add_ap(apdev[1], params)
df1d01cf
JM
3774
3775 appin = hapd.request("WPS_AP_PIN random")
3776 if "FAIL" in appin:
3777 raise Exception("Could not generate random AP PIN")
3778 if appin not in hapd.request("WPS_AP_PIN get"):
3779 raise Exception("Could not fetch current AP PIN")
3780
3781 if "FAIL" in hapd.request("WPS_PBC"):
3782 raise Exception("WPS_PBC failed")
3783 if "FAIL" in hapd.request("WPS_CANCEL"):
3784 raise Exception("WPS_CANCEL failed")
3785
2c3a0190
JM
3786def test_ap_wps_init_oom(dev, apdev):
3787 """Initial AP configuration and OOM during PSK generation"""
3788 ssid = "test-wps"
fab49f61 3789 params = {"ssid": ssid, "eap_server": "1", "wps_state": "1"}
8b8a1864 3790 hapd = hostapd.add_ap(apdev[0], params)
2c3a0190 3791
5b52e1ad 3792 with alloc_fail(hapd, 1, "base64_gen_encode;?base64_encode;wps_build_cred"):
2c3a0190
JM
3793 pin = dev[0].wps_read_pin()
3794 hapd.request("WPS_PIN any " + pin)
3795 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3796 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3797 dev[0].wait_disconnected()
3798
3799 hapd.request("WPS_PIN any " + pin)
3800 dev[0].wait_connected(timeout=30)
ccf4d764 3801
9fd6804d 3802@remote_compatible
ccf4d764
JM
3803def test_ap_wps_er_oom(dev, apdev):
3804 """WPS ER OOM in XML processing"""
3805 try:
3806 _test_ap_wps_er_oom(dev, apdev)
3807 finally:
3808 dev[0].request("WPS_ER_STOP")
3809 dev[1].request("WPS_CANCEL")
3810 dev[0].request("DISCONNECT")
3811
3812def _test_ap_wps_er_oom(dev, apdev):
3813 ssid = "wps-er-ap-config"
3814 ap_pin = "12345670"
3815 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 3816 hostapd.add_ap(apdev[0],
fab49f61
JM
3817 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3818 "wpa_passphrase": "12345678", "wpa": "2",
3819 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3820 "device_name": "Wireless AP", "manufacturer": "Company",
3821 "model_name": "WAP", "model_number": "123",
3822 "serial_number": "12345", "device_type": "6-0050F204-1",
3823 "os_version": "01020300",
3824 "config_methods": "label push_button",
3825 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
ccf4d764
JM
3826
3827 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
3828
5b52e1ad
JM
3829 with alloc_fail(dev[0], 1,
3830 "base64_gen_decode;?base64_decode;xml_get_base64_item"):
ccf4d764
JM
3831 dev[0].request("WPS_ER_START ifname=lo")
3832 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=3)
3833 if ev is not None:
3834 raise Exception("Unexpected AP discovery")
3835
3836 dev[0].request("WPS_ER_STOP")
3837 dev[0].request("WPS_ER_START ifname=lo")
3838 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
3839 if ev is None:
3840 raise Exception("AP discovery timed out")
3841
3842 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
5b52e1ad
JM
3843 with alloc_fail(dev[0], 1,
3844 "base64_gen_decode;?base64_decode;xml_get_base64_item"):
ccf4d764
JM
3845 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
3846 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
3847 if ev is None:
3848 raise Exception("PBC scan failed")
3849 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
3850 if ev is None:
3851 raise Exception("Enrollee discovery timed out")
2602a2ff 3852
9fd6804d 3853@remote_compatible
c965ae03
JM
3854def test_ap_wps_er_init_oom(dev, apdev):
3855 """WPS ER and OOM during init"""
3856 try:
3857 _test_ap_wps_er_init_oom(dev, apdev)
3858 finally:
3859 dev[0].request("WPS_ER_STOP")
3860
3861def _test_ap_wps_er_init_oom(dev, apdev):
3862 with alloc_fail(dev[0], 1, "wps_er_init"):
3863 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3864 raise Exception("WPS_ER_START succeeded during OOM")
3865 with alloc_fail(dev[0], 1, "http_server_init"):
3866 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3867 raise Exception("WPS_ER_START succeeded during OOM")
3868 with alloc_fail(dev[0], 2, "http_server_init"):
3869 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3870 raise Exception("WPS_ER_START succeeded during OOM")
9b35afd6 3871 with alloc_fail(dev[0], 1, "eloop_sock_table_add_sock;?eloop_register_sock;wps_er_ssdp_init"):
c965ae03
JM
3872 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3873 raise Exception("WPS_ER_START succeeded during OOM")
3874 with fail_test(dev[0], 1, "os_get_random;wps_er_init"):
3875 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3876 raise Exception("WPS_ER_START succeeded during os_get_random failure")
3877
9fd6804d 3878@remote_compatible
07536b18
JM
3879def test_ap_wps_er_init_fail(dev, apdev):
3880 """WPS ER init failure"""
3881 if "FAIL" not in dev[0].request("WPS_ER_START ifname=does-not-exist"):
3882 dev[0].request("WPS_ER_STOP")
3883 raise Exception("WPS_ER_START with non-existing ifname succeeded")
3884
2602a2ff
JM
3885def test_ap_wps_wpa_cli_action(dev, apdev, test_params):
3886 """WPS events and wpa_cli action script"""
8936b095
JM
3887 logdir = os.path.abspath(test_params['logdir'])
3888 pidfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.pid')
3889 logfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.res')
3890 actionfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.action.sh')
2602a2ff
JM
3891
3892 with open(actionfile, 'w') as f:
3893 f.write('#!/bin/sh\n')
3894 f.write('echo $* >> %s\n' % logfile)
3895 # Kill the process and wait some time before returning to allow all the
3896 # pending events to be processed with some of this happening after the
3897 # eloop SIGALRM signal has been scheduled.
3898 f.write('if [ $2 = "WPS-SUCCESS" -a -r %s ]; then kill `cat %s`; sleep 1; fi\n' % (pidfile, pidfile))
3899
8936b095
JM
3900 os.chmod(actionfile, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC |
3901 stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
2602a2ff
JM
3902
3903 ssid = "test-wps-conf"
6f334bf7 3904 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
3905 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3906 "wpa_passphrase": "12345678", "wpa": "2",
3907 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2602a2ff
JM
3908
3909 prg = os.path.join(test_params['logdir'],
3910 'alt-wpa_supplicant/wpa_supplicant/wpa_cli')
3911 if not os.path.exists(prg):
3912 prg = '../../wpa_supplicant/wpa_cli'
fab49f61 3913 arg = [prg, '-P', pidfile, '-B', '-i', dev[0].ifname, '-a', actionfile]
2602a2ff
JM
3914 subprocess.call(arg)
3915
fab49f61 3916 arg = ['ps', 'ax']
2602a2ff 3917 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
04fa9fc7 3918 out = cmd.communicate()[0].decode()
2602a2ff
JM
3919 cmd.wait()
3920 logger.debug("Processes:\n" + out)
3921 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) not in out:
3922 raise Exception("Did not see wpa_cli running")
3923
3924 hapd.request("WPS_PIN any 12345670")
3925 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3926 dev[0].dump_monitor()
3927 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3928 dev[0].wait_connected(timeout=30)
3929
3930 for i in range(30):
3931 if not os.path.exists(pidfile):
3932 break
3933 time.sleep(0.1)
3934
3935 if not os.path.exists(logfile):
3936 raise Exception("wpa_cli action results file not found")
3937 with open(logfile, 'r') as f:
3938 res = f.read()
3939 if "WPS-SUCCESS" not in res:
3940 raise Exception("WPS-SUCCESS event not seen in action file")
3941
fab49f61 3942 arg = ['ps', 'ax']
2602a2ff 3943 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
04fa9fc7 3944 out = cmd.communicate()[0].decode()
2602a2ff
JM
3945 cmd.wait()
3946 logger.debug("Remaining processes:\n" + out)
3947 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) in out:
3948 raise Exception("wpa_cli still running")
3949
3950 if os.path.exists(pidfile):
3951 raise Exception("PID file not removed")
c965ae03
JM
3952
3953def test_ap_wps_er_ssdp_proto(dev, apdev):
3954 """WPS ER SSDP protocol testing"""
3955 try:
3956 _test_ap_wps_er_ssdp_proto(dev, apdev)
3957 finally:
3958 dev[0].request("WPS_ER_STOP")
3959
3960def _test_ap_wps_er_ssdp_proto(dev, apdev):
3961 socket.setdefaulttimeout(1)
3962 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
3963 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
3964 sock.bind(("239.255.255.250", 1900))
3965 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo foo"):
3966 raise Exception("Invalid filter accepted")
3967 if "OK" not in dev[0].request("WPS_ER_START ifname=lo 1.2.3.4"):
3968 raise Exception("WPS_ER_START with filter failed")
fab49f61 3969 (msg, addr) = sock.recvfrom(1000)
cc02ce96 3970 msg = msg.decode()
c965ae03
JM
3971 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3972 if "M-SEARCH" not in msg:
3973 raise Exception("Not an M-SEARCH")
cc02ce96 3974 sock.sendto(b"FOO", addr)
c965ae03
JM
3975 time.sleep(0.1)
3976 dev[0].request("WPS_ER_STOP")
3977
3978 dev[0].request("WPS_ER_START ifname=lo")
fab49f61 3979 (msg, addr) = sock.recvfrom(1000)
cc02ce96 3980 msg = msg.decode()
c965ae03
JM
3981 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3982 if "M-SEARCH" not in msg:
3983 raise Exception("Not an M-SEARCH")
cc02ce96
MH
3984 sock.sendto(b"FOO", addr)
3985 sock.sendto(b"HTTP/1.1 200 OK\r\nFOO\r\n\r\n", addr)
3986 sock.sendto(b"HTTP/1.1 200 OK\r\nNTS:foo\r\n\r\n", addr)
3987 sock.sendto(b"HTTP/1.1 200 OK\r\nNTS:ssdp:byebye\r\n\r\n", addr)
3988 sock.sendto(b"HTTP/1.1 200 OK\r\ncache-control: foo=1\r\n\r\n", addr)
3989 sock.sendto(b"HTTP/1.1 200 OK\r\ncache-control: max-age=1\r\n\r\n", addr)
3990 sock.sendto(b"HTTP/1.1 200 OK\r\nusn:\r\n\r\n", addr)
3991 sock.sendto(b"HTTP/1.1 200 OK\r\nusn:foo\r\n\r\n", addr)
3992 sock.sendto(b"HTTP/1.1 200 OK\r\nusn: uuid:\r\n\r\n", addr)
3993 sock.sendto(b"HTTP/1.1 200 OK\r\nusn: uuid: \r\n\r\n", addr)
3994 sock.sendto(b"HTTP/1.1 200 OK\r\nusn: uuid: foo\r\n\r\n", addr)
3995 sock.sendto(b"HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\n\r\n", addr)
3996 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)
3997 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 3998 with alloc_fail(dev[0], 1, "wps_er_ap_add"):
cc02ce96 3999 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
4000 time.sleep(0.1)
4001 with alloc_fail(dev[0], 2, "wps_er_ap_add"):
cc02ce96 4002 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
4003 time.sleep(0.1)
4004
4005 # Add an AP with bogus URL
cc02ce96 4006 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 4007 # Update timeout on AP without updating URL
cc02ce96 4008 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
4009 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4010 if ev is None:
4011 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4012
4013 # Add an AP with a valid URL (but no server listing to it)
cc02ce96 4014 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
4015 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4016 if ev is None:
4017 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4018
4019 sock.close()
4020
4021wps_event_url = None
4022
6aaa661a
JM
4023def gen_upnp_info(eventSubURL='wps_event', controlURL='wps_control',
4024 udn='uuid:27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'):
4c3ae1c0 4025 payload = '''<?xml version="1.0"?>
c965ae03
JM
4026<root xmlns="urn:schemas-upnp-org:device-1-0">
4027<specVersion>
4028<major>1</major>
4029<minor>0</minor>
4030</specVersion>
4031<device>
4032<deviceType>urn:schemas-wifialliance-org:device:WFADevice:1</deviceType>
4033<friendlyName>WPS Access Point</friendlyName>
4034<manufacturer>Company</manufacturer>
4035<modelName>WAP</modelName>
4036<modelNumber>123</modelNumber>
4037<serialNumber>12345</serialNumber>
6aaa661a
JM
4038'''
4039 if udn:
4040 payload += '<UDN>' + udn + '</UDN>'
4041 payload += '''<serviceList>
c965ae03
JM
4042<service>
4043<serviceType>urn:schemas-wifialliance-org:service:WFAWLANConfig:1</serviceType>
4044<serviceId>urn:wifialliance-org:serviceId:WFAWLANConfig1</serviceId>
4045<SCPDURL>wps_scpd.xml</SCPDURL>
4c3ae1c0 4046'''
6aaa661a
JM
4047 if controlURL:
4048 payload += '<controlURL>' + controlURL + '</controlURL>\n'
4c3ae1c0 4049 if eventSubURL:
6aaa661a 4050 payload += '<eventSubURL>' + eventSubURL + '</eventSubURL>\n'
4c3ae1c0 4051 payload += '''</service>
c965ae03
JM
4052</serviceList>
4053</device>
4054</root>
4055'''
4c3ae1c0
JM
4056 hdr = 'HTTP/1.1 200 OK\r\n' + \
4057 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4058 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4059 'Connection: close\r\n' + \
4060 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4061 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
f94df3c0 4062 return (hdr + payload).encode()
4c3ae1c0 4063
6aaa661a 4064def gen_wps_control(payload_override=None):
4c3ae1c0 4065 payload = '''<?xml version="1.0"?>
c965ae03
JM
4066<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4067<s:Body>
4068<u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4069<NewDeviceInfo>EEoAARAQIgABBBBHABAn6oAanlxOc72C+Jy80Q1+ECAABgIAAAADABAaABCJZ7DPtbU3Ust9
4070Z3wJF07WEDIAwH45D3i1OqB7eJGwTzqeapS71h3KyXncK2xJZ+xqScrlorNEg6LijBJzG2Ca
4071+FZli0iliDJd397yAx/jk4nFXco3q5ylBSvSw9dhJ5u1xBKSnTilKGlUHPhLP75PUqM3fot9
40727zwtFZ4bx6x1sBA6oEe2d0aUJmLumQGCiKEIWlnxs44zego/2tAe81bDzdPBM7o5HH/FUhD+
4073KoGzFXp51atP+1n9Vta6AkI0Vye99JKLcC6Md9dMJltSVBgd4Xc4lRAEAAIAIxAQAAIADRAN
4074AAEBEAgAAgAEEEQAAQIQIQAHQ29tcGFueRAjAANXQVAQJAADMTIzEEIABTEyMzQ1EFQACAAG
4075AFDyBAABEBEAC1dpcmVsZXNzIEFQEDwAAQEQAgACAAAQEgACAAAQCQACAAAQLQAEgQIDABBJ
4076AAYANyoAASA=
4077</NewDeviceInfo>
4078</u:GetDeviceInfoResponse>
4079</s:Body>
4080</s:Envelope>
4081'''
6aaa661a
JM
4082 if payload_override:
4083 payload = payload_override
4c3ae1c0
JM
4084 hdr = 'HTTP/1.1 200 OK\r\n' + \
4085 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4086 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4087 'Connection: close\r\n' + \
4088 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4089 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
f94df3c0 4090 return (hdr + payload).encode()
4c3ae1c0 4091
6aaa661a 4092def gen_wps_event(sid='uuid:7eb3342a-8a5f-47fe-a585-0785bfec6d8a'):
4c3ae1c0
JM
4093 payload = ""
4094 hdr = 'HTTP/1.1 200 OK\r\n' + \
4095 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4096 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4097 'Connection: close\r\n' + \
6aaa661a
JM
4098 'Content-Length: ' + str(len(payload)) + '\r\n'
4099 if sid:
4100 hdr += 'SID: ' + sid + '\r\n'
4101 hdr += 'Timeout: Second-1801\r\n' + \
4c3ae1c0 4102 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
f94df3c0 4103 return (hdr + payload).encode()
4c3ae1c0 4104
9c06eda0 4105class WPSAPHTTPServer(StreamRequestHandler):
4c3ae1c0 4106 def handle(self):
59aecb1c 4107 data = self.rfile.readline().decode().strip()
4c3ae1c0
JM
4108 logger.info("HTTP server received: " + data)
4109 while True:
59aecb1c 4110 hdr = self.rfile.readline().decode().strip()
4c3ae1c0
JM
4111 if len(hdr) == 0:
4112 break
4113 logger.info("HTTP header: " + hdr)
4114 if "CALLBACK:" in hdr:
4115 global wps_event_url
4116 wps_event_url = hdr.split(' ')[1].strip('<>')
4117
4118 if "GET /foo.xml" in data:
6aaa661a
JM
4119 self.handle_upnp_info()
4120 elif "POST /wps_control" in data:
4121 self.handle_wps_control()
4122 elif "SUBSCRIBE /wps_event" in data:
4123 self.handle_wps_event()
24b7f282
JM
4124 else:
4125 self.handle_others(data)
6aaa661a
JM
4126
4127 def handle_upnp_info(self):
4128 self.wfile.write(gen_upnp_info())
4c3ae1c0 4129
6aaa661a
JM
4130 def handle_wps_control(self):
4131 self.wfile.write(gen_wps_control())
c965ae03 4132
6aaa661a
JM
4133 def handle_wps_event(self):
4134 self.wfile.write(gen_wps_event())
c965ae03 4135
24b7f282
JM
4136 def handle_others(self, data):
4137 logger.info("Ignore HTTP request: " + data)
4138
9c06eda0 4139class MyTCPServer(TCPServer):
4c3ae1c0
JM
4140 def __init__(self, addr, handler):
4141 self.allow_reuse_address = True
9c06eda0 4142 TCPServer.__init__(self, addr, handler)
c965ae03 4143
24b7f282
JM
4144def wps_er_start(dev, http_server, max_age=1, wait_m_search=False,
4145 location_url=None):
c965ae03
JM
4146 socket.setdefaulttimeout(1)
4147 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4148 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4149 sock.bind(("239.255.255.250", 1900))
4c3ae1c0 4150 dev.request("WPS_ER_START ifname=lo")
24b7f282 4151 for i in range(100):
fab49f61 4152 (msg, addr) = sock.recvfrom(1000)
cc02ce96 4153 msg = msg.decode()
24b7f282
JM
4154 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4155 if "M-SEARCH" in msg:
4156 break
4157 if not wait_m_search:
4158 raise Exception("Not an M-SEARCH")
4159 if i == 99:
4160 raise Exception("No M-SEARCH seen")
c965ae03
JM
4161
4162 # Add an AP with a valid URL and server listing to it
4c3ae1c0 4163 server = MyTCPServer(("127.0.0.1", 12345), http_server)
24b7f282
JM
4164 if not location_url:
4165 location_url = 'http://127.0.0.1:12345/foo.xml'
cc02ce96 4166 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 4167 server.timeout = 1
fab49f61 4168 return server, sock
4c3ae1c0
JM
4169
4170def wps_er_stop(dev, sock, server, on_alloc_fail=False):
4171 sock.close()
4172 server.server_close()
4173
4174 if on_alloc_fail:
4175 done = False
4176 for i in range(50):
4177 res = dev.request("GET_ALLOC_FAIL")
4178 if res.startswith("0:"):
4179 done = True
4180 break
4181 time.sleep(0.1)
4182 if not done:
4183 raise Exception("No allocation failure reported")
4184 else:
4185 ev = dev.wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4186 if ev is None:
4187 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4188 dev.request("WPS_ER_STOP")
4189
24b7f282 4190def run_wps_er_proto_test(dev, handler, no_event_url=False, location_url=None):
6aaa661a
JM
4191 try:
4192 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
fab49f61 4193 server, sock = wps_er_start(dev, handler, location_url=location_url)
6aaa661a
JM
4194 global wps_event_url
4195 wps_event_url = None
4196 server.handle_request()
4197 server.handle_request()
4198 server.handle_request()
4199 server.server_close()
4200 if no_event_url:
4201 if wps_event_url:
4202 raise Exception("Received event URL unexpectedly")
4203 return
4204 if wps_event_url is None:
4205 raise Exception("Did not get event URL")
4206 logger.info("Event URL: " + wps_event_url)
4207 finally:
24b7f282 4208 dev.request("WPS_ER_STOP")
6aaa661a 4209
18478107 4210def send_wlanevent(url, uuid, data, no_response=False):
9c06eda0 4211 conn = HTTPConnection(url.netloc)
6aaa661a
JM
4212 payload = '''<?xml version="1.0" encoding="utf-8"?>
4213<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4214<e:property><STAStatus>1</STAStatus></e:property>
4215<e:property><APStatus>1</APStatus></e:property>
4216<e:property><WLANEvent>'''
c4e333fa 4217 payload += base64.b64encode(data).decode()
6aaa661a 4218 payload += '</WLANEvent></e:property></e:propertyset>'
fab49f61
JM
4219 headers = {"Content-type": 'text/xml; charset="utf-8"',
4220 "Server": "Unspecified, UPnP/1.0, Unspecified",
4221 "HOST": url.netloc,
4222 "NT": "upnp:event",
4223 "SID": "uuid:" + uuid,
4224 "SEQ": "0",
4225 "Content-Length": str(len(payload))}
6aaa661a 4226 conn.request("NOTIFY", url.path, payload, headers)
18478107
JM
4227 if no_response:
4228 try:
4229 conn.getresponse()
bab493b9 4230 except Exception as e:
18478107
JM
4231 pass
4232 return
6aaa661a
JM
4233 resp = conn.getresponse()
4234 if resp.status != 200:
4235 raise Exception("Unexpected HTTP response: %d" % resp.status)
4236
4c3ae1c0
JM
4237def test_ap_wps_er_http_proto(dev, apdev):
4238 """WPS ER HTTP protocol testing"""
4239 try:
4240 _test_ap_wps_er_http_proto(dev, apdev)
4241 finally:
4242 dev[0].request("WPS_ER_STOP")
4243
4244def _test_ap_wps_er_http_proto(dev, apdev):
4245 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
fab49f61 4246 server, sock = wps_er_start(dev[0], WPSAPHTTPServer, max_age=15)
c965ae03
JM
4247 global wps_event_url
4248 wps_event_url = None
4249 server.handle_request()
4250 server.handle_request()
4251 server.handle_request()
4252 server.server_close()
4253 if wps_event_url is None:
4254 raise Exception("Did not get event URL")
4255 logger.info("Event URL: " + wps_event_url)
4256
4257 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
4258 if ev is None:
4259 raise Exception("No WPS-ER-AP-ADD event")
4260 if uuid not in ev:
4261 raise Exception("UUID mismatch")
4262
4263 sock.close()
4264
4265 logger.info("Valid Probe Request notification")
9c06eda0
MH
4266 url = urlparse(wps_event_url)
4267 conn = HTTPConnection(url.netloc)
c965ae03
JM
4268 payload = '''<?xml version="1.0" encoding="utf-8"?>
4269<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4270<e:property><STAStatus>1</STAStatus></e:property>
4271<e:property><APStatus>1</APStatus></e:property>
4272<e:property><WLANEvent>ATAyOjAwOjAwOjAwOjAwOjAwEEoAARAQOgABAhAIAAIxSBBHABA2LbR7pTpRkYj7VFi5hrLk
4273EFQACAAAAAAAAAAAEDwAAQMQAgACAAAQCQACAAAQEgACAAAQIQABIBAjAAEgECQAASAQEQAI
4274RGV2aWNlIEEQSQAGADcqAAEg
4275</WLANEvent></e:property>
4276</e:propertyset>
4277'''
fab49f61
JM
4278 headers = {"Content-type": 'text/xml; charset="utf-8"',
4279 "Server": "Unspecified, UPnP/1.0, Unspecified",
4280 "HOST": url.netloc,
4281 "NT": "upnp:event",
4282 "SID": "uuid:" + uuid,
4283 "SEQ": "0",
4284 "Content-Length": str(len(payload))}
c965ae03
JM
4285 conn.request("NOTIFY", url.path, payload, headers)
4286 resp = conn.getresponse()
4287 if resp.status != 200:
4288 raise Exception("Unexpected HTTP response: %d" % resp.status)
4289
4290 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=5)
4291 if ev is None:
4292 raise Exception("No WPS-ER-ENROLLEE-ADD event")
4293 if "362db47b-a53a-5191-88fb-5458b986b2e4" not in ev:
4294 raise Exception("No Enrollee UUID match")
4295
4296 logger.info("Incorrect event URL AP id")
9c06eda0 4297 conn = HTTPConnection(url.netloc)
c965ae03
JM
4298 conn.request("NOTIFY", url.path + '123', payload, headers)
4299 resp = conn.getresponse()
4300 if resp.status != 404:
4301 raise Exception("Unexpected HTTP response: %d" % resp.status)
4302
4303 logger.info("Missing AP id")
9c06eda0 4304 conn = HTTPConnection(url.netloc)
c965ae03
JM
4305 conn.request("NOTIFY", '/event/' + url.path.split('/')[2],
4306 payload, headers)
4307 time.sleep(0.1)
4308
4309 logger.info("Incorrect event URL event id")
9c06eda0 4310 conn = HTTPConnection(url.netloc)
c965ae03
JM
4311 conn.request("NOTIFY", '/event/123456789/123', payload, headers)
4312 time.sleep(0.1)
4313
4314 logger.info("Incorrect event URL prefix")
9c06eda0 4315 conn = HTTPConnection(url.netloc)
c965ae03
JM
4316 conn.request("NOTIFY", '/foobar/123456789/123', payload, headers)
4317 resp = conn.getresponse()
4318 if resp.status != 404:
4319 raise Exception("Unexpected HTTP response: %d" % resp.status)
4320
4321 logger.info("Unsupported request")
9c06eda0 4322 conn = HTTPConnection(url.netloc)
c965ae03
JM
4323 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4324 resp = conn.getresponse()
4325 if resp.status != 501:
4326 raise Exception("Unexpected HTTP response: %d" % resp.status)
4327
4328 logger.info("Unsupported request and OOM")
4329 with alloc_fail(dev[0], 1, "wps_er_http_req"):
9c06eda0 4330 conn = HTTPConnection(url.netloc)
c965ae03
JM
4331 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4332 time.sleep(0.5)
4c3ae1c0 4333
6aaa661a 4334 logger.info("Too short WLANEvent")
15dfcb69 4335 data = b'\x00'
6aaa661a
JM
4336 send_wlanevent(url, uuid, data)
4337
4338 logger.info("Invalid WLANEventMAC")
15dfcb69 4339 data = b'\x00qwertyuiopasdfghjklzxcvbnm'
6aaa661a
JM
4340 send_wlanevent(url, uuid, data)
4341
4342 logger.info("Unknown WLANEventType")
15dfcb69 4343 data = b'\xff02:00:00:00:00:00'
6aaa661a
JM
4344 send_wlanevent(url, uuid, data)
4345
4346 logger.info("Probe Request notification without any attributes")
15dfcb69 4347 data = b'\x0102:00:00:00:00:00'
6aaa661a
JM
4348 send_wlanevent(url, uuid, data)
4349
4350 logger.info("Probe Request notification with invalid attribute")
15dfcb69 4351 data = b'\x0102:00:00:00:00:00\xff'
6aaa661a
JM
4352 send_wlanevent(url, uuid, data)
4353
4354 logger.info("EAP message without any attributes")
15dfcb69 4355 data = b'\x0202:00:00:00:00:00'
6aaa661a
JM
4356 send_wlanevent(url, uuid, data)
4357
4358 logger.info("EAP message with invalid attribute")
15dfcb69 4359 data = b'\x0202:00:00:00:00:00\xff'
6aaa661a
JM
4360 send_wlanevent(url, uuid, data)
4361
4362 logger.info("EAP message from new STA and not M1")
15dfcb69 4363 data = b'\x0202:ff:ff:ff:ff:ff' + b'\x10\x22\x00\x01\x05'
6aaa661a
JM
4364 send_wlanevent(url, uuid, data)
4365
4366 logger.info("EAP message: M1")
15dfcb69
MH
4367 data = b'\x0202:00:00:00:00:00'
4368 data += b'\x10\x22\x00\x01\x04'
4369 data += b'\x10\x47\x00\x10' + 16 * b'\x00'
4370 data += b'\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4371 data += b'\x10\x1a\x00\x10' + 16 * b'\x00'
4372 data += b'\x10\x32\x00\xc0' + 192 * b'\x00'
4373 data += b'\x10\x04\x00\x02\x00\x00'
4374 data += b'\x10\x10\x00\x02\x00\x00'
4375 data += b'\x10\x0d\x00\x01\x00'
4376 data += b'\x10\x08\x00\x02\x00\x00'
4377 data += b'\x10\x44\x00\x01\x00'
4378 data += b'\x10\x21\x00\x00'
4379 data += b'\x10\x23\x00\x00'
4380 data += b'\x10\x24\x00\x00'
4381 data += b'\x10\x42\x00\x00'
4382 data += b'\x10\x54\x00\x08' + 8 * b'\x00'
4383 data += b'\x10\x11\x00\x00'
4384 data += b'\x10\x3c\x00\x01\x00'
4385 data += b'\x10\x02\x00\x02\x00\x00'
4386 data += b'\x10\x12\x00\x02\x00\x00'
4387 data += b'\x10\x09\x00\x02\x00\x00'
4388 data += b'\x10\x2d\x00\x04\x00\x00\x00\x00'
6aaa661a
JM
4389 m1 = data
4390 send_wlanevent(url, uuid, data)
4391
4392 logger.info("EAP message: WSC_ACK")
15dfcb69 4393 data = b'\x0202:00:00:00:00:00' + b'\x10\x22\x00\x01\x0d'
6aaa661a
JM
4394 send_wlanevent(url, uuid, data)
4395
4396 logger.info("EAP message: M1")
4397 send_wlanevent(url, uuid, m1)
4398
4399 logger.info("EAP message: WSC_NACK")
15dfcb69 4400 data = b'\x0202:00:00:00:00:00' + b'\x10\x22\x00\x01\x0e'
6aaa661a
JM
4401 send_wlanevent(url, uuid, data)
4402
4403 logger.info("EAP message: M1 - Too long attribute values")
15dfcb69
MH
4404 data = b'\x0202:00:00:00:00:00'
4405 data += b'\x10\x11\x00\x21' + 33 * b'\x00'
4406 data += b'\x10\x45\x00\x21' + 33 * b'\x00'
4407 data += b'\x10\x42\x00\x21' + 33 * b'\x00'
4408 data += b'\x10\x24\x00\x21' + 33 * b'\x00'
4409 data += b'\x10\x23\x00\x21' + 33 * b'\x00'
4410 data += b'\x10\x21\x00\x41' + 65 * b'\x00'
4411 data += b'\x10\x49\x00\x09\x00\x37\x2a\x05\x02\x00\x00\x05\x00'
6aaa661a
JM
4412 send_wlanevent(url, uuid, data)
4413
4414 logger.info("EAP message: M1 missing UUID-E")
15dfcb69
MH
4415 data = b'\x0202:00:00:00:00:00'
4416 data += b'\x10\x22\x00\x01\x04'
6aaa661a
JM
4417 send_wlanevent(url, uuid, data)
4418
4419 logger.info("EAP message: M1 missing MAC Address")
15dfcb69 4420 data += b'\x10\x47\x00\x10' + 16 * b'\x00'
6aaa661a
JM
4421 send_wlanevent(url, uuid, data)
4422
4423 logger.info("EAP message: M1 missing Enrollee Nonce")
15dfcb69 4424 data += b'\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
6aaa661a
JM
4425 send_wlanevent(url, uuid, data)
4426
4427 logger.info("EAP message: M1 missing Public Key")
15dfcb69 4428 data += b'\x10\x1a\x00\x10' + 16 * b'\x00'
6aaa661a
JM
4429 send_wlanevent(url, uuid, data)
4430
4431 logger.info("EAP message: M1 missing Authentication Type flags")
15dfcb69 4432 data += b'\x10\x32\x00\xc0' + 192 * b'\x00'
6aaa661a
JM
4433 send_wlanevent(url, uuid, data)
4434
4435 logger.info("EAP message: M1 missing Encryption Type Flags")
15dfcb69 4436 data += b'\x10\x04\x00\x02\x00\x00'
6aaa661a
JM
4437 send_wlanevent(url, uuid, data)
4438
4439 logger.info("EAP message: M1 missing Connection Type flags")
15dfcb69 4440 data += b'\x10\x10\x00\x02\x00\x00'
6aaa661a
JM
4441 send_wlanevent(url, uuid, data)
4442
4443 logger.info("EAP message: M1 missing Config Methods")
15dfcb69 4444 data += b'\x10\x0d\x00\x01\x00'
6aaa661a
JM
4445 send_wlanevent(url, uuid, data)
4446
4447 logger.info("EAP message: M1 missing Wi-Fi Protected Setup State")
15dfcb69 4448 data += b'\x10\x08\x00\x02\x00\x00'
6aaa661a
JM
4449 send_wlanevent(url, uuid, data)
4450
4451 logger.info("EAP message: M1 missing Manufacturer")
15dfcb69 4452 data += b'\x10\x44\x00\x01\x00'
6aaa661a
JM
4453 send_wlanevent(url, uuid, data)
4454
4455 logger.info("EAP message: M1 missing Model Name")
15dfcb69 4456 data += b'\x10\x21\x00\x00'
6aaa661a
JM
4457 send_wlanevent(url, uuid, data)
4458
4459 logger.info("EAP message: M1 missing Model Number")
15dfcb69 4460 data += b'\x10\x23\x00\x00'
6aaa661a
JM
4461 send_wlanevent(url, uuid, data)
4462
4463 logger.info("EAP message: M1 missing Serial Number")
15dfcb69 4464 data += b'\x10\x24\x00\x00'
6aaa661a
JM
4465 send_wlanevent(url, uuid, data)
4466
4467 logger.info("EAP message: M1 missing Primary Device Type")
15dfcb69 4468 data += b'\x10\x42\x00\x00'
6aaa661a
JM
4469 send_wlanevent(url, uuid, data)
4470
4471 logger.info("EAP message: M1 missing Device Name")
15dfcb69 4472 data += b'\x10\x54\x00\x08' + 8 * b'\x00'
6aaa661a
JM
4473 send_wlanevent(url, uuid, data)
4474
4475 logger.info("EAP message: M1 missing RF Bands")
15dfcb69 4476 data += b'\x10\x11\x00\x00'
6aaa661a
JM
4477 send_wlanevent(url, uuid, data)
4478
4479 logger.info("EAP message: M1 missing Association State")
15dfcb69 4480 data += b'\x10\x3c\x00\x01\x00'
6aaa661a
JM
4481 send_wlanevent(url, uuid, data)
4482
4483 logger.info("EAP message: M1 missing Device Password ID")
15dfcb69 4484 data += b'\x10\x02\x00\x02\x00\x00'
6aaa661a
JM
4485 send_wlanevent(url, uuid, data)
4486
4487 logger.info("EAP message: M1 missing Configuration Error")
15dfcb69 4488 data += b'\x10\x12\x00\x02\x00\x00'
6aaa661a
JM
4489 send_wlanevent(url, uuid, data)
4490
4491 logger.info("EAP message: M1 missing OS Version")
15dfcb69 4492 data += b'\x10\x09\x00\x02\x00\x00'
6aaa661a 4493 send_wlanevent(url, uuid, data)
4c3ae1c0 4494
24b7f282
JM
4495 logger.info("Check max concurrent requests")
4496 addr = (url.hostname, url.port)
4497 socks = {}
4498 for i in range(20):
4499 socks[i] = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4500 socket.IPPROTO_TCP)
e5d3e13a
JM
4501 socks[i].settimeout(10)
4502 socks[i].connect(addr)
24b7f282 4503 for i in range(20):
cc02ce96 4504 socks[i].send(b"GET / HTTP/1.1\r\n\r\n")
24b7f282
JM
4505 count = 0
4506 for i in range(20):
4507 try:
cc02ce96 4508 res = socks[i].recv(100).decode()
24b7f282
JM
4509 if "HTTP/1" in res:
4510 count += 1
6f9b4de2
JM
4511 else:
4512 logger.info("recv[%d]: len=%d" % (i, len(res)))
24b7f282
JM
4513 except:
4514 pass
4515 socks[i].close()
4516 logger.info("%d concurrent HTTP GET operations returned response" % count)
6f9b4de2 4517 if count < 8:
24b7f282
JM
4518 raise Exception("Too few concurrent HTTP connections accepted")
4519
4520 logger.info("OOM in HTTP server")
fab49f61
JM
4521 for func in ["http_request_init", "httpread_create",
4522 "eloop_register_timeout;httpread_create",
4523 "eloop_sock_table_add_sock;?eloop_register_sock;httpread_create",
4524 "httpread_hdr_analyze"]:
24b7f282
JM
4525 with alloc_fail(dev[0], 1, func):
4526 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4527 socket.IPPROTO_TCP)
4528 sock.connect(addr)
cc02ce96 4529 sock.send(b"GET / HTTP/1.1\r\n\r\n")
24b7f282
JM
4530 try:
4531 sock.recv(100)
4532 except:
4533 pass
4534 sock.close()
4535
4536 logger.info("Invalid HTTP header")
fab49f61
JM
4537 for req in [" GET / HTTP/1.1\r\n\r\n",
4538 "HTTP/1.1 200 OK\r\n\r\n",
4539 "HTTP/\r\n\r\n",
4540 "GET %%a%aa% HTTP/1.1\r\n\r\n",
4541 "GET / HTTP/1.1\r\n FOO\r\n\r\n",
4542 "NOTIFY / HTTP/1.1\r\n" + 4097*'a' + '\r\n\r\n',
4543 "NOTIFY / HTTP/1.1\r\n\r\n" + 8193*'a',
4544 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n foo\r\n",
4545 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n1\r\nfoo\r\n",
4546 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\n",
4547 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\naa\ra\r\n\ra"]:
24b7f282
JM
4548 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4549 socket.IPPROTO_TCP)
4550 sock.settimeout(0.1)
4551 sock.connect(addr)
cc02ce96 4552 sock.send(req.encode())
24b7f282
JM
4553 try:
4554 sock.recv(100)
4555 except:
4556 pass
4557 sock.close()
4558
4559 with alloc_fail(dev[0], 2, "httpread_read_handler"):
4560 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4561 socket.IPPROTO_TCP)
4562 sock.connect(addr)
cc02ce96 4563 sock.send(b"NOTIFY / HTTP/1.1\r\n\r\n" + 4500 * b'a')
24b7f282
JM
4564 try:
4565 sock.recv(100)
4566 except:
4567 pass
4568 sock.close()
4569
9c06eda0 4570 conn = HTTPConnection(url.netloc)
24b7f282 4571 payload = '<foo'
fab49f61
JM
4572 headers = {"Content-type": 'text/xml; charset="utf-8"',
4573 "Server": "Unspecified, UPnP/1.0, Unspecified",
4574 "HOST": url.netloc,
4575 "NT": "upnp:event",
4576 "SID": "uuid:" + uuid,
4577 "SEQ": "0",
4578 "Content-Length": str(len(payload))}
24b7f282
JM
4579 conn.request("NOTIFY", url.path, payload, headers)
4580 resp = conn.getresponse()
4581 if resp.status != 200:
4582 raise Exception("Unexpected HTTP response: %d" % resp.status)
4583
9c06eda0 4584 conn = HTTPConnection(url.netloc)
24b7f282 4585 payload = '<WLANEvent foo></WLANEvent>'
fab49f61
JM
4586 headers = {"Content-type": 'text/xml; charset="utf-8"',
4587 "Server": "Unspecified, UPnP/1.0, Unspecified",
4588 "HOST": url.netloc,
4589 "NT": "upnp:event",
4590 "SID": "uuid:" + uuid,
4591 "SEQ": "0",
4592 "Content-Length": str(len(payload))}
24b7f282
JM
4593 conn.request("NOTIFY", url.path, payload, headers)
4594 resp = conn.getresponse()
4595 if resp.status != 200:
4596 raise Exception("Unexpected HTTP response: %d" % resp.status)
4597
4598 with alloc_fail(dev[0], 1, "xml_get_first_item"):
15dfcb69 4599 send_wlanevent(url, uuid, b'')
24b7f282
JM
4600
4601 with alloc_fail(dev[0], 1, "wpabuf_alloc_ext_data;xml_get_base64_item"):
15dfcb69 4602 send_wlanevent(url, uuid, b'foo')
24b7f282 4603
fab49f61
JM
4604 for func in ["wps_init",
4605 "wps_process_manufacturer",
4606 "wps_process_model_name",
4607 "wps_process_model_number",
4608 "wps_process_serial_number",
4609 "wps_process_dev_name"]:
24b7f282
JM
4610 with alloc_fail(dev[0], 1, func):
4611 send_wlanevent(url, uuid, m1)
4612
18478107
JM
4613 with alloc_fail(dev[0], 1, "wps_er_http_resp_ok"):
4614 send_wlanevent(url, uuid, m1, no_response=True)
4615
4616 with alloc_fail(dev[0], 1, "wps_er_http_resp_not_found"):
9c06eda0 4617 url2 = urlparse(wps_event_url.replace('/event/', '/notfound/'))
18478107
JM
4618 send_wlanevent(url2, uuid, m1, no_response=True)
4619
3d105cdf 4620 logger.info("EAP message: M1")
15dfcb69
MH
4621 data = b'\x0202:11:22:00:00:00'
4622 data += b'\x10\x22\x00\x01\x04'
4623 data += b'\x10\x47\x00\x10' + 16 * b'\x00'
4624 data += b'\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4625 data += b'\x10\x1a\x00\x10' + 16 * b'\x00'
4626 data += b'\x10\x32\x00\xc0' + 192 * b'\x00'
4627 data += b'\x10\x04\x00\x02\x00\x00'
4628 data += b'\x10\x10\x00\x02\x00\x00'
4629 data += b'\x10\x0d\x00\x01\x00'
4630 data += b'\x10\x08\x00\x02\x00\x00'
4631 data += b'\x10\x44\x00\x01\x00'
4632 data += b'\x10\x21\x00\x00'
4633 data += b'\x10\x23\x00\x00'
4634 data += b'\x10\x24\x00\x00'
4635 data += b'\x10\x42\x00\x00'
4636 data += b'\x10\x54\x00\x08' + 8 * b'\x00'
4637 data += b'\x10\x11\x00\x00'
4638 data += b'\x10\x3c\x00\x01\x00'
4639 data += b'\x10\x02\x00\x02\x00\x00'
4640 data += b'\x10\x12\x00\x02\x00\x00'
4641 data += b'\x10\x09\x00\x02\x00\x00'
4642 data += b'\x10\x2d\x00\x04\x00\x00\x00\x00'
3d105cdf
JM
4643 dev[0].dump_monitor()
4644 with alloc_fail(dev[0], 1, "wps_er_add_sta_data"):
4645 send_wlanevent(url, uuid, data)
4646 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=0.1)
4647 if ev is not None:
4648 raise Exception("Unexpected enrollee add event")
4649 send_wlanevent(url, uuid, data)
4650 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=2)
4651 if ev is None:
4652 raise Exception("Enrollee add event not seen")
4653
5b52e1ad
JM
4654 with alloc_fail(dev[0], 1,
4655 "base64_gen_encode;?base64_encode;wps_er_soap_hdr"):
fe67b945
JM
4656 send_wlanevent(url, uuid, data)
4657
4658 with alloc_fail(dev[0], 1, "wpabuf_alloc;wps_er_soap_hdr"):
4659 send_wlanevent(url, uuid, data)
4660
4661 with alloc_fail(dev[0], 1, "http_client_url_parse;wps_er_sta_send_msg"):
4662 send_wlanevent(url, uuid, data)
4663
4664 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_sta_send_msg"):
4665 send_wlanevent(url, uuid, data)
4666
4c3ae1c0
JM
4667def test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
4668 """WPS ER HTTP protocol testing - no eventSubURL"""
6aaa661a
JM
4669 class WPSAPHTTPServer_no_event_sub_url(WPSAPHTTPServer):
4670 def handle_upnp_info(self):
4671 self.wfile.write(gen_upnp_info(eventSubURL=None))
4672 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_event_sub_url,
4673 no_event_url=True)
4c3ae1c0
JM
4674
4675def test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev):
4676 """WPS ER HTTP protocol testing - DNS name in eventSubURL"""
6aaa661a
JM
4677 class WPSAPHTTPServer_event_sub_url_dns(WPSAPHTTPServer):
4678 def handle_upnp_info(self):
4679 self.wfile.write(gen_upnp_info(eventSubURL='http://example.com/wps_event'))
4680 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_event_sub_url_dns,
4681 no_event_url=True)
4c3ae1c0
JM
4682
4683def test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4684 """WPS ER HTTP protocol testing - subscribe OOM"""
4685 try:
4686 _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev)
4687 finally:
4688 dev[0].request("WPS_ER_STOP")
4689
4690def _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
fab49f61
JM
4691 tests = [(1, "http_client_url_parse"),
4692 (1, "wpabuf_alloc;wps_er_subscribe"),
4693 (1, "http_client_addr"),
4694 (1, "eloop_sock_table_add_sock;?eloop_register_sock;http_client_addr"),
4695 (1, "eloop_register_timeout;http_client_addr")]
4696 for count, func in tests:
4c3ae1c0 4697 with alloc_fail(dev[0], count, func):
fab49f61 4698 server, sock = wps_er_start(dev[0], WPSAPHTTPServer)
4c3ae1c0
JM
4699 server.handle_request()
4700 server.handle_request()
4701 wps_er_stop(dev[0], sock, server, on_alloc_fail=True)
6aaa661a
JM
4702
4703def test_ap_wps_er_http_proto_no_sid(dev, apdev):
4704 """WPS ER HTTP protocol testing - no SID"""
4705 class WPSAPHTTPServer_no_sid(WPSAPHTTPServer):
4706 def handle_wps_event(self):
4707 self.wfile.write(gen_wps_event(sid=None))
4708 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_sid)
4709
4710def test_ap_wps_er_http_proto_invalid_sid_no_uuid(dev, apdev):
4711 """WPS ER HTTP protocol testing - invalid SID - no UUID"""
4712 class WPSAPHTTPServer_invalid_sid_no_uuid(WPSAPHTTPServer):
4713 def handle_wps_event(self):
4714 self.wfile.write(gen_wps_event(sid='FOO'))
4715 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_no_uuid)
4716
4717def test_ap_wps_er_http_proto_invalid_sid_uuid(dev, apdev):
4718 """WPS ER HTTP protocol testing - invalid SID UUID"""
4719 class WPSAPHTTPServer_invalid_sid_uuid(WPSAPHTTPServer):
4720 def handle_wps_event(self):
4721 self.wfile.write(gen_wps_event(sid='uuid:FOO'))
4722 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_uuid)
4723
4724def test_ap_wps_er_http_proto_subscribe_failing(dev, apdev):
4725 """WPS ER HTTP protocol testing - SUBSCRIBE failing"""
4726 class WPSAPHTTPServer_fail_subscribe(WPSAPHTTPServer):
4727 def handle_wps_event(self):
4728 payload = ""
4729 hdr = 'HTTP/1.1 404 Not Found\r\n' + \
4730 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4731 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4732 'Connection: close\r\n' + \
4733 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4734 'Timeout: Second-1801\r\n' + \
4735 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
f94df3c0 4736 self.wfile.write((hdr + payload).encode())
6aaa661a
JM
4737 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_fail_subscribe)
4738
4739def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4740 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4741 class WPSAPHTTPServer_subscribe_invalid_response(WPSAPHTTPServer):
4742 def handle_wps_event(self):
4743 payload = ""
4744 hdr = 'HTTP/1.1 FOO\r\n' + \
4745 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4746 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4747 'Connection: close\r\n' + \
4748 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4749 'Timeout: Second-1801\r\n' + \
4750 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
f94df3c0 4751 self.wfile.write((hdr + payload).encode())
6aaa661a
JM
4752 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_subscribe_invalid_response)
4753
4754def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4755 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4756 class WPSAPHTTPServer_invalid_m1(WPSAPHTTPServer):
4757 def handle_wps_control(self):
4758 payload = '''<?xml version="1.0"?>
4759<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4760<s:Body>
4761<u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4762<NewDeviceInfo>Rk9P</NewDeviceInfo>
4763</u:GetDeviceInfoResponse>
4764</s:Body>
4765</s:Envelope>
4766'''
4767 self.wfile.write(gen_wps_control(payload_override=payload))
4768 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_m1, no_event_url=True)
4769
4770def test_ap_wps_er_http_proto_upnp_info_no_device(dev, apdev):
4771 """WPS ER HTTP protocol testing - No device in UPnP info"""
4772 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4773 def handle_upnp_info(self):
4774 payload = '''<?xml version="1.0"?>
4775<root xmlns="urn:schemas-upnp-org:device-1-0">
4776<specVersion>
4777<major>1</major>
4778<minor>0</minor>
4779</specVersion>
4780</root>
4781'''
4782 hdr = 'HTTP/1.1 200 OK\r\n' + \
4783 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4784 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4785 'Connection: close\r\n' + \
4786 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4787 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
f94df3c0 4788 self.wfile.write((hdr + payload).encode())
6aaa661a
JM
4789 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4790
4791def test_ap_wps_er_http_proto_upnp_info_no_device_type(dev, apdev):
4792 """WPS ER HTTP protocol testing - No deviceType in UPnP info"""
4793 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4794 def handle_upnp_info(self):
4795 payload = '''<?xml version="1.0"?>
4796<root xmlns="urn:schemas-upnp-org:device-1-0">
4797<specVersion>
4798<major>1</major>
4799<minor>0</minor>
4800</specVersion>
4801<device>
4802</device>
4803</root>
4804'''
4805 hdr = 'HTTP/1.1 200 OK\r\n' + \
4806 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4807 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4808 'Connection: close\r\n' + \
4809 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4810 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
f94df3c0 4811 self.wfile.write((hdr + payload).encode())
6aaa661a
JM
4812 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4813
4814def test_ap_wps_er_http_proto_upnp_info_invalid_udn_uuid(dev, apdev):
4815 """WPS ER HTTP protocol testing - Invalid UDN UUID"""
4816 class WPSAPHTTPServer_invalid_udn_uuid(WPSAPHTTPServer):
4817 def handle_upnp_info(self):
4818 self.wfile.write(gen_upnp_info(udn='uuid:foo'))
4819 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_udn_uuid)
4820
4821def test_ap_wps_er_http_proto_no_control_url(dev, apdev):
4822 """WPS ER HTTP protocol testing - no controlURL"""
4823 class WPSAPHTTPServer_no_control_url(WPSAPHTTPServer):
4824 def handle_upnp_info(self):
4825 self.wfile.write(gen_upnp_info(controlURL=None))
4826 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_control_url,
4827 no_event_url=True)
4828
4829def test_ap_wps_er_http_proto_control_url_dns(dev, apdev):
4830 """WPS ER HTTP protocol testing - DNS name in controlURL"""
4831 class WPSAPHTTPServer_control_url_dns(WPSAPHTTPServer):
4832 def handle_upnp_info(self):
4833 self.wfile.write(gen_upnp_info(controlURL='http://example.com/wps_control'))
4834 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_control_url_dns,
4835 no_event_url=True)
24b7f282
JM
4836
4837def test_ap_wps_http_timeout(dev, apdev):
4838 """WPS AP/ER and HTTP timeout"""
4839 try:
4840 _test_ap_wps_http_timeout(dev, apdev)
4841 finally:
4842 dev[0].request("WPS_ER_STOP")
4843
4844def _test_ap_wps_http_timeout(dev, apdev):
4845 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 4846 add_ssdp_ap(apdev[0], ap_uuid)
24b7f282
JM
4847
4848 location = ssdp_get_location(ap_uuid)
9c06eda0 4849 url = urlparse(location)
24b7f282
JM
4850 addr = (url.hostname, url.port)
4851 logger.debug("Open HTTP connection to hostapd, but do not complete request")
4852 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4853 socket.IPPROTO_TCP)
4854 sock.connect(addr)
cc02ce96 4855 sock.send(b"G")
24b7f282 4856
9c06eda0 4857 class DummyServer(StreamRequestHandler):
24b7f282
JM
4858 def handle(self):
4859 logger.debug("DummyServer - start 31 sec wait")
4860 time.sleep(31)
4861 logger.debug("DummyServer - wait done")
4862
4863 logger.debug("Start WPS ER")
fab49f61
JM
4864 server, sock2 = wps_er_start(dev[0], DummyServer, max_age=40,
4865 wait_m_search=True)
24b7f282
JM
4866
4867 logger.debug("Start server to accept, but not complete, HTTP connection from WPS ER")
4868 # This will wait for 31 seconds..
4869 server.handle_request()
4870
4871 logger.debug("Complete HTTP connection with hostapd (that should have already closed the connection)")
4872 try:
4873 sock.send("ET / HTTP/1.1\r\n\r\n")
4874 res = sock.recv(100)
4875 sock.close()
4876 except:
4877 pass
4878
4879def test_ap_wps_er_url_parse(dev, apdev):
4880 """WPS ER and URL parsing special cases"""
4881 try:
4882 _test_ap_wps_er_url_parse(dev, apdev)
4883 finally:
4884 dev[0].request("WPS_ER_STOP")
4885
4886def _test_ap_wps_er_url_parse(dev, apdev):
4887 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4888 sock.settimeout(1)
4889 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4890 sock.bind(("239.255.255.250", 1900))
4891 dev[0].request("WPS_ER_START ifname=lo")
fab49f61 4892 (msg, addr) = sock.recvfrom(1000)
cc02ce96 4893 msg = msg.decode()
24b7f282
JM
4894 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4895 if "M-SEARCH" not in msg:
4896 raise Exception("Not an M-SEARCH")
cc02ce96 4897 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 4898 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
cc02ce96 4899 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 4900 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
cc02ce96 4901 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
4902 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4903
4904 sock.close()
4905
4906def test_ap_wps_er_link_update(dev, apdev):
4907 """WPS ER and link update special cases"""
4908 class WPSAPHTTPServer_link_update(WPSAPHTTPServer):
4909 def handle_upnp_info(self):
4910 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4911 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update)
4912
4913 class WPSAPHTTPServer_link_update2(WPSAPHTTPServer):
4914 def handle_others(self, data):
4915 if "GET / " in data:
4916 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4917 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update2,
4918 location_url='http://127.0.0.1:12345')
4919
4920def test_ap_wps_er_http_client(dev, apdev):
4921 """WPS ER and HTTP client special cases"""
4922 with alloc_fail(dev[0], 1, "http_link_update"):
4923 run_wps_er_proto_test(dev[0], WPSAPHTTPServer)
4924
4925 with alloc_fail(dev[0], 1, "wpabuf_alloc;http_client_url"):
4926 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4927
4928 with alloc_fail(dev[0], 1, "httpread_create;http_client_tx_ready"):
4929 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4930
4931 class WPSAPHTTPServer_req_as_resp(WPSAPHTTPServer):
4932 def handle_upnp_info(self):
15dfcb69 4933 self.wfile.write(b"GET / HTTP/1.1\r\n\r\n")
24b7f282
JM
4934 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_req_as_resp,
4935 no_event_url=True)
4936
4937def test_ap_wps_init_oom(dev, apdev):
4938 """wps_init OOM cases"""
4939 ssid = "test-wps"
4940 appin = "12345670"
fab49f61
JM
4941 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
4942 "ap_pin": appin}
8b8a1864 4943 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
4944 pin = dev[0].wps_read_pin()
4945
4946 with alloc_fail(hapd, 1, "wps_init"):
4947 hapd.request("WPS_PIN any " + pin)
4948 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4949 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4950 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4951 if ev is None:
4952 raise Exception("No EAP failure reported")
4953 dev[0].request("WPS_CANCEL")
4954
4955 with alloc_fail(dev[0], 2, "wps_init"):
4956 hapd.request("WPS_PIN any " + pin)
4957 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4958 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4959 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4960 if ev is None:
4961 raise Exception("No EAP failure reported")
4962 dev[0].request("WPS_CANCEL")
4963
4964 with alloc_fail(dev[0], 2, "wps_init"):
4965 hapd.request("WPS_PBC")
4966 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4967 dev[0].request("WPS_PBC %s" % (apdev[0]['bssid']))
4968 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4969 if ev is None:
4970 raise Exception("No EAP failure reported")
4971 dev[0].request("WPS_CANCEL")
4972
4973 dev[0].dump_monitor()
4974 new_ssid = "wps-new-ssid"
4975 new_passphrase = "1234567890"
4976 with alloc_fail(dev[0], 3, "wps_init"):
4977 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
4978 new_passphrase, no_wait=True)
4979 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4980 if ev is None:
4981 raise Exception("No EAP failure reported")
4982
4983 dev[0].flush_scan_cache()
4984
9fd6804d 4985@remote_compatible
24b7f282
JM
4986def test_ap_wps_invalid_assoc_req_elem(dev, apdev):
4987 """WPS and invalid IE in Association Request frame"""
4988 ssid = "test-wps"
fab49f61 4989 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
8b8a1864 4990 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
4991 pin = "12345670"
4992 hapd.request("WPS_PIN any " + pin)
4993 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4994 try:
4995 dev[0].request("VENDOR_ELEM_ADD 13 dd050050f20410")
4996 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4997 for i in range(5):
4998 ev = hapd.wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=10)
4999 if ev and "vendor=14122" in ev:
5000 break
5001 if ev is None or "vendor=14122" not in ev:
5002 raise Exception("EAP-WSC not started")
5003 dev[0].request("WPS_CANCEL")
5004 finally:
5005 dev[0].request("VENDOR_ELEM_REMOVE 13 *")
5006
5007def test_ap_wps_pbc_pin_mismatch(dev, apdev):
5008 """WPS PBC/PIN mismatch"""
5009 ssid = "test-wps"
fab49f61 5010 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
8b8a1864 5011 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5012 hapd.request("SET wps_version_number 0x10")
5013 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5014 hapd.request("WPS_PBC")
5015 pin = dev[0].wps_read_pin()
5016 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5017 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5018 if ev is None:
5019 raise Exception("Scan did not complete")
5020 dev[0].request("WPS_CANCEL")
5021
5022 hapd.request("WPS_CANCEL")
5023 dev[0].flush_scan_cache()
5024
9fd6804d 5025@remote_compatible
24b7f282
JM
5026def test_ap_wps_ie_invalid(dev, apdev):
5027 """WPS PIN attempt with AP that has invalid WSC IE"""
5028 ssid = "test-wps"
fab49f61
JM
5029 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5030 "vendor_elements": "dd050050f20410"}
8b8a1864 5031 hapd = hostapd.add_ap(apdev[0], params)
fab49f61 5032 params = {'ssid': "another", "vendor_elements": "dd050050f20410"}
8b8a1864 5033 hostapd.add_ap(apdev[1], params)
24b7f282
JM
5034 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5035 pin = dev[0].wps_read_pin()
5036 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5037 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5038 if ev is None:
5039 raise Exception("Scan did not complete")
5040 dev[0].request("WPS_CANCEL")
5041
9fd6804d 5042@remote_compatible
24b7f282
JM
5043def test_ap_wps_scan_prio_order(dev, apdev):
5044 """WPS scan priority ordering"""
5045 ssid = "test-wps"
fab49f61 5046 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
8b8a1864 5047 hapd = hostapd.add_ap(apdev[0], params)
fab49f61 5048 params = {'ssid': "another", "vendor_elements": "dd050050f20410"}
8b8a1864 5049 hostapd.add_ap(apdev[1], params)
24b7f282
JM
5050 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5051 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
5052 pin = dev[0].wps_read_pin()
5053 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5054 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5055 if ev is None:
5056 raise Exception("Scan did not complete")
5057 dev[0].request("WPS_CANCEL")
5058
5059def test_ap_wps_probe_req_ie_oom(dev, apdev):
5060 """WPS ProbeReq IE OOM"""
5061 ssid = "test-wps"
fab49f61 5062 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
8b8a1864 5063 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5064 pin = dev[0].wps_read_pin()
5065 hapd.request("WPS_PIN any " + pin)
5066 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5067 with alloc_fail(dev[0], 1, "wps_build_probe_req_ie"):
5068 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5069 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5070 if ev is None:
5071 raise Exception("Association not seen")
5072 dev[0].request("WPS_CANCEL")
161c8515 5073 dev[0].wait_disconnected()
24b7f282
JM
5074
5075 with alloc_fail(dev[0], 1, "wps_ie_encapsulate"):
5076 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5077 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5078 if ev is None:
5079 raise Exception("Association not seen")
5080 dev[0].request("WPS_CANCEL")
161c8515
JM
5081 hapd.disable()
5082 dev[0].request("REMOVE_NETWORK all")
5083 dev[0].wait_disconnected()
5084 time.sleep(0.2)
5085 dev[0].flush_scan_cache()
24b7f282
JM
5086
5087def test_ap_wps_assoc_req_ie_oom(dev, apdev):
5088 """WPS AssocReq IE OOM"""
5089 ssid = "test-wps"
fab49f61 5090 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
8b8a1864 5091 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5092 pin = dev[0].wps_read_pin()
5093 hapd.request("WPS_PIN any " + pin)
5094 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5095 with alloc_fail(dev[0], 1, "wps_build_assoc_req_ie"):
5096 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5097 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5098 if ev is None:
5099 raise Exception("Association not seen")
5100 dev[0].request("WPS_CANCEL")
5101
5102def test_ap_wps_assoc_resp_ie_oom(dev, apdev):
5103 """WPS AssocResp IE OOM"""
5104 ssid = "test-wps"
fab49f61 5105 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
8b8a1864 5106 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5107 pin = dev[0].wps_read_pin()
5108 hapd.request("WPS_PIN any " + pin)
5109 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5110 with alloc_fail(hapd, 1, "wps_build_assoc_resp_ie"):
5111 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5112 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5113 if ev is None:
5114 raise Exception("Association not seen")
5115 dev[0].request("WPS_CANCEL")
5116
9fd6804d 5117@remote_compatible
24b7f282
JM
5118def test_ap_wps_bss_info_errors(dev, apdev):
5119 """WPS BSS info errors"""
fab49f61
JM
5120 params = {"ssid": "1",
5121 "vendor_elements": "dd0e0050f20410440001ff101100010a"}
8b8a1864 5122 hostapd.add_ap(apdev[0], params)
fab49f61 5123 params = {'ssid': "2", "vendor_elements": "dd050050f20410"}
8b8a1864 5124 hostapd.add_ap(apdev[1], params)
24b7f282
JM
5125 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5126 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
5127 bss = dev[0].get_bss(apdev[0]['bssid'])
5128 logger.info("BSS: " + str(bss))
5129 if "wps_state" in bss:
5130 raise Exception("Unexpected wps_state in BSS info")
5131 if 'wps_device_name' not in bss:
5132 raise Exception("No wps_device_name in BSS info")
5133 if bss['wps_device_name'] != '_':
5134 raise Exception("Unexpected wps_device_name value")
5135 bss = dev[0].get_bss(apdev[1]['bssid'])
5136 logger.info("BSS: " + str(bss))
5137
5138 with alloc_fail(dev[0], 1, "=wps_attr_text"):
5139 bss = dev[0].get_bss(apdev[0]['bssid'])
5140 logger.info("BSS(OOM): " + str(bss))
5141
5142def wps_run_pbc_fail_ap(apdev, dev, hapd):
5143 hapd.request("WPS_PBC")
5144 dev.scan_for_bss(apdev['bssid'], freq="2412")
5145 dev.request("WPS_PBC " + apdev['bssid'])
5146 ev = dev.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5147 if ev is None:
5148 raise Exception("No EAP failure reported")
5149 dev.request("WPS_CANCEL")
5150 dev.wait_disconnected()
5151 for i in range(5):
5152 try:
5153 dev.flush_scan_cache()
5154 break
bab493b9 5155 except Exception as e:
24b7f282
JM
5156 if str(e).startswith("Failed to trigger scan"):
5157 # Try again
5158 time.sleep(1)
5159 else:
5160 raise
5161
5162def wps_run_pbc_fail(apdev, dev):
5163 hapd = wps_start_ap(apdev)
5164 wps_run_pbc_fail_ap(apdev, dev, hapd)
5165
9fd6804d 5166@remote_compatible
24b7f282
JM
5167def test_ap_wps_pk_oom(dev, apdev):
5168 """WPS and public key OOM"""
5169 with alloc_fail(dev[0], 1, "wps_build_public_key"):
5170 wps_run_pbc_fail(apdev[0], dev[0])
5171
9fd6804d 5172@remote_compatible
24b7f282
JM
5173def test_ap_wps_pk_oom_ap(dev, apdev):
5174 """WPS and public key OOM on AP"""
5175 hapd = wps_start_ap(apdev[0])
5176 with alloc_fail(hapd, 1, "wps_build_public_key"):
5177 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5178
9fd6804d 5179@remote_compatible
24b7f282
JM
5180def test_ap_wps_encr_oom_ap(dev, apdev):
5181 """WPS and encrypted settings decryption OOM on AP"""
5182 hapd = wps_start_ap(apdev[0])
5183 pin = dev[0].wps_read_pin()
5184 hapd.request("WPS_PIN any " + pin)
5185 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5186 with alloc_fail(hapd, 1, "wps_decrypt_encr_settings"):
5187 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
5188 ev = hapd.wait_event(["WPS-FAIL"], timeout=10)
5189 if ev is None:
5190 raise Exception("No WPS-FAIL reported")
5191 dev[0].request("WPS_CANCEL")
5192 dev[0].wait_disconnected()
5193
9fd6804d 5194@remote_compatible
24b7f282
JM
5195def test_ap_wps_encr_no_random_ap(dev, apdev):
5196 """WPS and no random data available for encryption on AP"""
5197 hapd = wps_start_ap(apdev[0])
5198 with fail_test(hapd, 1, "os_get_random;wps_build_encr_settings"):
5199 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5200
9fd6804d 5201@remote_compatible
24b7f282
JM
5202def test_ap_wps_e_hash_no_random_sta(dev, apdev):
5203 """WPS and no random data available for e-hash on STA"""
5204 with fail_test(dev[0], 1, "os_get_random;wps_build_e_hash"):
5205 wps_run_pbc_fail(apdev[0], dev[0])
5206
9fd6804d 5207@remote_compatible
24b7f282
JM
5208def test_ap_wps_m1_no_random(dev, apdev):
5209 """WPS and no random for M1 on STA"""
5210 with fail_test(dev[0], 1, "os_get_random;wps_build_m1"):
5211 wps_run_pbc_fail(apdev[0], dev[0])
5212
9fd6804d 5213@remote_compatible
24b7f282
JM
5214def test_ap_wps_m1_oom(dev, apdev):
5215 """WPS and OOM for M1 on STA"""
5216 with alloc_fail(dev[0], 1, "wps_build_m1"):
5217 wps_run_pbc_fail(apdev[0], dev[0])
5218
9fd6804d 5219@remote_compatible
24b7f282
JM
5220def test_ap_wps_m3_oom(dev, apdev):
5221 """WPS and OOM for M3 on STA"""
5222 with alloc_fail(dev[0], 1, "wps_build_m3"):
5223 wps_run_pbc_fail(apdev[0], dev[0])
5224
9fd6804d 5225@remote_compatible
24b7f282
JM
5226def test_ap_wps_m5_oom(dev, apdev):
5227 """WPS and OOM for M5 on STA"""
5228 hapd = wps_start_ap(apdev[0])
5229 hapd.request("WPS_PBC")
5230 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5231 for i in range(1, 3):
5232 with alloc_fail(dev[0], i, "wps_build_m5"):
5233 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5234 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5235 if ev is None:
5236 raise Exception("No EAP failure reported")
5237 dev[0].request("WPS_CANCEL")
5238 dev[0].wait_disconnected()
5239 dev[0].flush_scan_cache()
5240
9fd6804d 5241@remote_compatible
24b7f282
JM
5242def test_ap_wps_m5_no_random(dev, apdev):
5243 """WPS and no random for M5 on STA"""
5244 with fail_test(dev[0], 1,
5245 "os_get_random;wps_build_encr_settings;wps_build_m5"):
5246 wps_run_pbc_fail(apdev[0], dev[0])
5247
9fd6804d 5248@remote_compatible
24b7f282
JM
5249def test_ap_wps_m7_oom(dev, apdev):
5250 """WPS and OOM for M7 on STA"""
5251 hapd = wps_start_ap(apdev[0])
5252 hapd.request("WPS_PBC")
5253 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5254 for i in range(1, 3):
5255 with alloc_fail(dev[0], i, "wps_build_m7"):
5256 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5257 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5258 if ev is None:
5259 raise Exception("No EAP failure reported")
5260 dev[0].request("WPS_CANCEL")
5261 dev[0].wait_disconnected()
5262 dev[0].flush_scan_cache()
5263
9fd6804d 5264@remote_compatible
24b7f282
JM
5265def test_ap_wps_m7_no_random(dev, apdev):
5266 """WPS and no random for M7 on STA"""
5267 with fail_test(dev[0], 1,
5268 "os_get_random;wps_build_encr_settings;wps_build_m7"):
5269 wps_run_pbc_fail(apdev[0], dev[0])
5270
9fd6804d 5271@remote_compatible
24b7f282
JM
5272def test_ap_wps_wsc_done_oom(dev, apdev):
5273 """WPS and OOM for WSC_Done on STA"""
5274 with alloc_fail(dev[0], 1, "wps_build_wsc_done"):
5275 wps_run_pbc_fail(apdev[0], dev[0])
5276
5277def test_ap_wps_random_psk_fail(dev, apdev):
5278 """WPS and no random for PSK on AP"""
5279 ssid = "test-wps"
5280 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
5281 appin = "12345670"
5282 try:
5283 os.remove(pskfile)
5284 except:
5285 pass
5286
5287 try:
5288 with open(pskfile, "w") as f:
5289 f.write("# WPA PSKs\n")
5290
fab49f61
JM
5291 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5292 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
5293 "rsn_pairwise": "CCMP", "ap_pin": appin,
5294 "wpa_psk_file": pskfile}
8b8a1864 5295 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5296
5297 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5298 with fail_test(hapd, 1, "os_get_random;wps_build_cred_network_key"):
5299 dev[0].request("WPS_REG " + apdev[0]['bssid'] + " " + appin)
5300 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5301 if ev is None:
5302 raise Exception("No EAP failure reported")
5303 dev[0].request("WPS_CANCEL")
5304 dev[0].wait_disconnected()
5305
5306 with fail_test(hapd, 1, "os_get_random;wps_build_cred"):
5307 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5308
5309 with alloc_fail(hapd, 1, "wps_build_cred"):
5310 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5311
5312 with alloc_fail(hapd, 2, "wps_build_cred"):
5313 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5314 finally:
5315 os.remove(pskfile)
5316
5317def wps_ext_eap_identity_req(dev, hapd, bssid):
5318 logger.debug("EAP-Identity/Request")
5319 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5320 if ev is None:
5321 raise Exception("Timeout on EAPOL-TX from hostapd")
5322 res = dev.request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
5323 if "OK" not in res:
5324 raise Exception("EAPOL_RX to wpa_supplicant failed")
5325
5326def wps_ext_eap_identity_resp(hapd, dev, addr):
5327 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
5328 if ev is None:
5329 raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
5330 res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
5331 if "OK" not in res:
5332 raise Exception("EAPOL_RX to hostapd failed")
5333
5334def wps_ext_eap_wsc(dst, src, src_addr, msg):
5335 logger.debug(msg)
5336 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5337 if ev is None:
5338 raise Exception("Timeout on EAPOL-TX")
5339 res = dst.request("EAPOL_RX " + src_addr + " " + ev.split(' ')[2])
5340 if "OK" not in res:
5341 raise Exception("EAPOL_RX failed")
5342
7511ead0 5343def wps_start_ext(apdev, dev, pbc=False, pin=None):
24b7f282
JM
5344 addr = dev.own_addr()
5345 bssid = apdev['bssid']
5346 ssid = "test-wps-conf"
fab49f61
JM
5347 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5348 "wpa_passphrase": "12345678", "wpa": "2",
5349 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
afc26df2 5350 hapd = hostapd.add_ap(apdev, params)
24b7f282 5351
d1883671
JM
5352 if pbc:
5353 hapd.request("WPS_PBC")
5354 else:
7511ead0
JM
5355 if pin is None:
5356 pin = dev.wps_read_pin()
d1883671 5357 hapd.request("WPS_PIN any " + pin)
24b7f282
JM
5358 dev.scan_for_bss(bssid, freq="2412")
5359 hapd.request("SET ext_eapol_frame_io 1")
5360 dev.request("SET ext_eapol_frame_io 1")
5361
d1883671
JM
5362 if pbc:
5363 dev.request("WPS_PBC " + bssid)
5364 else:
5365 dev.request("WPS_PIN " + bssid + " " + pin)
fab49f61 5366 return addr, bssid, hapd
24b7f282
JM
5367
5368def wps_auth_corrupt(dst, src, addr):
5369 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5370 if ev is None:
5371 raise Exception("Timeout on EAPOL-TX")
5372 src.request("SET ext_eapol_frame_io 0")
5373 dst.request("SET ext_eapol_frame_io 0")
5374 msg = ev.split(' ')[2]
5375 if msg[-24:-16] != '10050008':
5376 raise Exception("Could not find Authenticator attribute")
5377 # Corrupt Authenticator value
5378 msg = msg[:-1] + '%x' % ((int(msg[-1], 16) + 1) % 16)
5379 res = dst.request("EAPOL_RX " + addr + " " + msg)
5380 if "OK" not in res:
5381 raise Exception("EAPOL_RX failed")
5382
5383def wps_fail_finish(hapd, dev, fail_str):
5384 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5385 if ev is None:
5386 raise Exception("WPS-FAIL not indicated")
5387 if fail_str not in ev:
5388 raise Exception("Unexpected WPS-FAIL value: " + ev)
5389 dev.request("WPS_CANCEL")
5390 dev.wait_disconnected()
5391
5392def wps_auth_corrupt_from_ap(dev, hapd, bssid, fail_str):
5393 wps_auth_corrupt(dev, hapd, bssid)
5394 wps_fail_finish(hapd, dev, fail_str)
5395
5396def wps_auth_corrupt_to_ap(dev, hapd, addr, fail_str):
5397 wps_auth_corrupt(hapd, dev, addr)
5398 wps_fail_finish(hapd, dev, fail_str)
5399
5400def test_ap_wps_authenticator_mismatch_m2(dev, apdev):
5401 """WPS and Authenticator attribute mismatch in M2"""
fab49f61 5402 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
24b7f282
JM
5403 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5404 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5405 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5406 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5407 logger.debug("M2")
5408 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=5")
5409
5410def test_ap_wps_authenticator_mismatch_m3(dev, apdev):
5411 """WPS and Authenticator attribute mismatch in M3"""
fab49f61 5412 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
24b7f282
JM
5413 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5414 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5415 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5416 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5417 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5418 logger.debug("M3")
5419 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=7")
5420
5421def test_ap_wps_authenticator_mismatch_m4(dev, apdev):
5422 """WPS and Authenticator attribute mismatch in M4"""
fab49f61 5423 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
24b7f282
JM
5424 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5425 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5426 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5427 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5428 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5429 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5430 logger.debug("M4")
5431 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=8")
5432
5433def test_ap_wps_authenticator_mismatch_m5(dev, apdev):
5434 """WPS and Authenticator attribute mismatch in M5"""
fab49f61 5435 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
24b7f282
JM
5436 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5437 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5438 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5439 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5440 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5441 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5442 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5443 logger.debug("M5")
5444 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=9")
5445
5446def test_ap_wps_authenticator_mismatch_m6(dev, apdev):
5447 """WPS and Authenticator attribute mismatch in M6"""
fab49f61 5448 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
24b7f282
JM
5449 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5450 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5451 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5452 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5453 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5454 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5455 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5456 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5457 logger.debug("M6")
5458 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=10")
5459
5460def test_ap_wps_authenticator_mismatch_m7(dev, apdev):
5461 """WPS and Authenticator attribute mismatch in M7"""
fab49f61 5462 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
24b7f282
JM
5463 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5464 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5465 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5466 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5467 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5468 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5469 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5470 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5471 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5472 logger.debug("M7")
5473 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=11")
5474
5475def test_ap_wps_authenticator_mismatch_m8(dev, apdev):
5476 """WPS and Authenticator attribute mismatch in M8"""
fab49f61 5477 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
24b7f282
JM
5478 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5479 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5480 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5481 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5482 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5483 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5484 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5485 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5486 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5487 wps_ext_eap_wsc(hapd, dev[0], addr, "M7")
5488 logger.debug("M8")
5489 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=12")
5490
5491def test_ap_wps_authenticator_missing_m2(dev, apdev):
5492 """WPS and Authenticator attribute missing from M2"""
fab49f61 5493 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
24b7f282
JM
5494 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5495 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5496 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5497 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5498 logger.debug("M2")
5499 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5500 if ev is None:
5501 raise Exception("Timeout on EAPOL-TX")
5502 hapd.request("SET ext_eapol_frame_io 0")
5503 dev[0].request("SET ext_eapol_frame_io 0")
5504 msg = ev.split(' ')[2]
5505 if msg[-24:-16] != '10050008':
5506 raise Exception("Could not find Authenticator attribute")
5507 # Remove Authenticator value
5508 msg = msg[:-24]
5509 mlen = "%04x" % (int(msg[4:8], 16) - 12)
5510 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:]
5511 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5512 if "OK" not in res:
5513 raise Exception("EAPOL_RX failed")
5514 wps_fail_finish(hapd, dev[0], "msg=5")
5515
d1883671
JM
5516def test_ap_wps_m2_dev_passwd_id_p2p(dev, apdev):
5517 """WPS and M2 with different Device Password ID (P2P)"""
fab49f61 5518 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
d1883671
JM
5519 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5520 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5521 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5522 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5523 logger.debug("M2")
5524 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5525 if ev is None:
5526 raise Exception("Timeout on EAPOL-TX")
5527 hapd.request("SET ext_eapol_frame_io 0")
5528 dev[0].request("SET ext_eapol_frame_io 0")
5529 msg = ev.split(' ')[2]
5530 if msg[722:730] != '10120002':
5531 raise Exception("Could not find Device Password ID attribute")
5532 # Replace Device Password ID value. This will fail Authenticator check, but
5533 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5534 # log.
5535 msg = msg[0:730] + "0005" + msg[734:]
5536 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5537 if "OK" not in res:
5538 raise Exception("EAPOL_RX failed")
5539 wps_fail_finish(hapd, dev[0], "msg=5")
5540
5541def test_ap_wps_m2_dev_passwd_id_change_pin_to_pbc(dev, apdev):
5542 """WPS and M2 with different Device Password ID (PIN to PBC)"""
fab49f61 5543 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
d1883671
JM
5544 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5545 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5546 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5547 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5548 logger.debug("M2")
5549 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5550 if ev is None:
5551 raise Exception("Timeout on EAPOL-TX")
5552 hapd.request("SET ext_eapol_frame_io 0")
5553 dev[0].request("SET ext_eapol_frame_io 0")
5554 msg = ev.split(' ')[2]
5555 if msg[722:730] != '10120002':
5556 raise Exception("Could not find Device Password ID attribute")
5557 # Replace Device Password ID value (PIN --> PBC). This will be rejected.
5558 msg = msg[0:730] + "0004" + msg[734:]
5559 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5560 if "OK" not in res:
5561 raise Exception("EAPOL_RX failed")
5562 wps_fail_finish(hapd, dev[0], "msg=5")
5563
5564def test_ap_wps_m2_dev_passwd_id_change_pbc_to_pin(dev, apdev):
5565 """WPS and M2 with different Device Password ID (PBC to PIN)"""
fab49f61 5566 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5567 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5568 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5569 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5570 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5571 logger.debug("M2")
5572 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5573 if ev is None:
5574 raise Exception("Timeout on EAPOL-TX")
5575 hapd.request("SET ext_eapol_frame_io 0")
5576 dev[0].request("SET ext_eapol_frame_io 0")
5577 msg = ev.split(' ')[2]
5578 if msg[722:730] != '10120002':
5579 raise Exception("Could not find Device Password ID attribute")
5580 # Replace Device Password ID value. This will fail Authenticator check, but
5581 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5582 # log.
5583 msg = msg[0:730] + "0000" + msg[734:]
5584 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5585 if "OK" not in res:
5586 raise Exception("EAPOL_RX failed")
5587 wps_fail_finish(hapd, dev[0], "msg=5")
5588 dev[0].flush_scan_cache()
5589
5590def test_ap_wps_m2_missing_dev_passwd_id(dev, apdev):
5591 """WPS and M2 without Device Password ID"""
fab49f61 5592 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
d1883671
JM
5593 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5594 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5595 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5596 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5597 logger.debug("M2")
5598 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5599 if ev is None:
5600 raise Exception("Timeout on EAPOL-TX")
5601 hapd.request("SET ext_eapol_frame_io 0")
5602 dev[0].request("SET ext_eapol_frame_io 0")
5603 msg = ev.split(' ')[2]
5604 if msg[722:730] != '10120002':
5605 raise Exception("Could not find Device Password ID attribute")
5606 # Remove Device Password ID value. This will fail Authenticator check, but
5607 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5608 # log.
5609 mlen = "%04x" % (int(msg[4:8], 16) - 6)
5610 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:722] + msg[734:]
5611 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5612 if "OK" not in res:
5613 raise Exception("EAPOL_RX failed")
5614 wps_fail_finish(hapd, dev[0], "msg=5")
5615
5616def test_ap_wps_m2_missing_registrar_nonce(dev, apdev):
5617 """WPS and M2 without Registrar Nonce"""
fab49f61 5618 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5619 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5620 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5621 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5622 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5623 logger.debug("M2")
5624 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5625 if ev is None:
5626 raise Exception("Timeout on EAPOL-TX")
5627 hapd.request("SET ext_eapol_frame_io 0")
5628 dev[0].request("SET ext_eapol_frame_io 0")
5629 msg = ev.split(' ')[2]
5630 if msg[96:104] != '10390010':
5631 raise Exception("Could not find Registrar Nonce attribute")
5632 # Remove Registrar Nonce. This will fail Authenticator check, but
5633 # allows the code path in wps_process_registrar_nonce() to be checked from
5634 # the debug log.
5635 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5636 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:96] + msg[136:]
5637 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5638 if "OK" not in res:
5639 raise Exception("EAPOL_RX failed")
5640 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5641 if ev is None:
5642 raise Exception("Disconnect event not seen")
5643 dev[0].request("WPS_CANCEL")
5644 dev[0].flush_scan_cache()
5645
5646def test_ap_wps_m2_missing_enrollee_nonce(dev, apdev):
5647 """WPS and M2 without Enrollee Nonce"""
fab49f61 5648 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5649 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5650 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5651 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5652 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5653 logger.debug("M2")
5654 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5655 if ev is None:
5656 raise Exception("Timeout on EAPOL-TX")
5657 hapd.request("SET ext_eapol_frame_io 0")
5658 dev[0].request("SET ext_eapol_frame_io 0")
5659 msg = ev.split(' ')[2]
5660 if msg[56:64] != '101a0010':
5661 raise Exception("Could not find enrollee Nonce attribute")
5662 # Remove Enrollee Nonce. This will fail Authenticator check, but
5663 # allows the code path in wps_process_enrollee_nonce() to be checked from
5664 # the debug log.
5665 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5666 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:56] + msg[96:]
5667 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5668 if "OK" not in res:
5669 raise Exception("EAPOL_RX failed")
5670 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5671 if ev is None:
5672 raise Exception("Disconnect event not seen")
5673 dev[0].request("WPS_CANCEL")
5674 dev[0].flush_scan_cache()
5675
5676def test_ap_wps_m2_missing_uuid_r(dev, apdev):
5677 """WPS and M2 without UUID-R"""
fab49f61 5678 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5679 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5680 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5681 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5682 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5683 logger.debug("M2")
5684 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5685 if ev is None:
5686 raise Exception("Timeout on EAPOL-TX")
5687 hapd.request("SET ext_eapol_frame_io 0")
5688 dev[0].request("SET ext_eapol_frame_io 0")
5689 msg = ev.split(' ')[2]
5690 if msg[136:144] != '10480010':
5691 raise Exception("Could not find enrollee Nonce attribute")
5692 # Remove UUID-R. This will fail Authenticator check, but allows the code
5693 # path in wps_process_uuid_r() to be checked from the debug log.
5694 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5695 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:136] + msg[176:]
5696 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5697 if "OK" not in res:
5698 raise Exception("EAPOL_RX failed")
5699 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5700 if ev is None:
5701 raise Exception("Disconnect event not seen")
5702 dev[0].request("WPS_CANCEL")
5703 dev[0].flush_scan_cache()
5704
5705def test_ap_wps_m2_invalid(dev, apdev):
5706 """WPS and M2 parsing failure"""
fab49f61 5707 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5708 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5709 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5710 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5711 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5712 logger.debug("M2")
5713 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5714 if ev is None:
5715 raise Exception("Timeout on EAPOL-TX")
5716 hapd.request("SET ext_eapol_frame_io 0")
5717 dev[0].request("SET ext_eapol_frame_io 0")
5718 msg = ev.split(' ')[2]
5719 if msg[136:144] != '10480010':
5720 raise Exception("Could not find enrollee Nonce attribute")
5721 # Remove UUID-R. This will fail Authenticator check, but allows the code
5722 # path in wps_process_uuid_r() to be checked from the debug log.
5723 mlen = "%04x" % (int(msg[4:8], 16) - 1)
5724 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:-2]
5725 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5726 if "OK" not in res:
5727 raise Exception("EAPOL_RX failed")
5728 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5729 if ev is None:
5730 raise Exception("Disconnect event not seen")
5731 dev[0].request("WPS_CANCEL")
5732 dev[0].flush_scan_cache()
5733
5734def test_ap_wps_m2_missing_msg_type(dev, apdev):
5735 """WPS and M2 without Message Type"""
fab49f61 5736 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5737 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5738 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5739 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5740 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5741 logger.debug("M2")
5742 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5743 if ev is None:
5744 raise Exception("Timeout on EAPOL-TX")
5745 hapd.request("SET ext_eapol_frame_io 0")
5746 dev[0].request("SET ext_eapol_frame_io 0")
5747 msg = ev.split(' ')[2]
5748 if msg[46:54] != '10220001':
5749 raise Exception("Could not find Message Type attribute")
5750 # Remove Message Type. This will fail Authenticator check, but allows the
5751 # code path in wps_process_wsc_msg() to be checked from the debug log.
5752 mlen = "%04x" % (int(msg[4:8], 16) - 5)
5753 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:46] + msg[56:]
5754 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5755 if "OK" not in res:
5756 raise Exception("EAPOL_RX failed")
5757 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5758 if ev is None:
5759 raise Exception("Disconnect event not seen")
5760 dev[0].request("WPS_CANCEL")
5761 dev[0].flush_scan_cache()
5762
5763def test_ap_wps_m2_unknown_msg_type(dev, apdev):
5764 """WPS and M2 but unknown Message Type"""
fab49f61 5765 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5766 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5767 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5768 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5769 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5770 logger.debug("M2")
5771 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5772 if ev is None:
5773 raise Exception("Timeout on EAPOL-TX")
5774 hapd.request("SET ext_eapol_frame_io 0")
5775 dev[0].request("SET ext_eapol_frame_io 0")
5776 msg = ev.split(' ')[2]
5777 if msg[46:54] != '10220001':
5778 raise Exception("Could not find Message Type attribute")
5779 # Replace Message Type value. This will be rejected.
5780 msg = msg[0:54] + "00" + msg[56:]
5781 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5782 if "OK" not in res:
5783 raise Exception("EAPOL_RX failed")
5784 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5785 if ev is None:
5786 raise Exception("Disconnect event not seen")
5787 dev[0].request("WPS_CANCEL")
5788 dev[0].flush_scan_cache()
5789
5790def test_ap_wps_m2_unknown_opcode(dev, apdev):
5791 """WPS and M2 but unknown opcode"""
fab49f61 5792 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5793 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5794 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5795 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5796 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5797 logger.debug("M2")
5798 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5799 if ev is None:
5800 raise Exception("Timeout on EAPOL-TX")
5801 hapd.request("SET ext_eapol_frame_io 0")
5802 dev[0].request("SET ext_eapol_frame_io 0")
5803 msg = ev.split(' ')[2]
5804 # Replace opcode. This will be discarded in EAP-WSC processing.
5805 msg = msg[0:32] + "00" + msg[34:]
5806 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5807 if "OK" not in res:
5808 raise Exception("EAPOL_RX failed")
5809 dev[0].request("WPS_CANCEL")
5810 dev[0].wait_disconnected()
5811 dev[0].flush_scan_cache()
5812
5813def test_ap_wps_m2_unknown_opcode2(dev, apdev):
5814 """WPS and M2 but unknown opcode (WSC_Start)"""
fab49f61 5815 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5816 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5817 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5818 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5819 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5820 logger.debug("M2")
5821 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5822 if ev is None:
5823 raise Exception("Timeout on EAPOL-TX")
5824 hapd.request("SET ext_eapol_frame_io 0")
5825 dev[0].request("SET ext_eapol_frame_io 0")
5826 msg = ev.split(' ')[2]
5827 # Replace opcode. This will be discarded in EAP-WSC processing.
5828 msg = msg[0:32] + "01" + msg[34:]
5829 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5830 if "OK" not in res:
5831 raise Exception("EAPOL_RX failed")
5832 dev[0].request("WPS_CANCEL")
5833 dev[0].wait_disconnected()
5834 dev[0].flush_scan_cache()
5835
5836def test_ap_wps_m2_unknown_opcode3(dev, apdev):
5837 """WPS and M2 but unknown opcode (WSC_Done)"""
fab49f61 5838 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
d1883671
JM
5839 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5840 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5841 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5842 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5843 logger.debug("M2")
5844 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5845 if ev is None:
5846 raise Exception("Timeout on EAPOL-TX")
5847 hapd.request("SET ext_eapol_frame_io 0")
5848 dev[0].request("SET ext_eapol_frame_io 0")
5849 msg = ev.split(' ')[2]
5850 # Replace opcode. This will be discarded in WPS Enrollee processing.
5851 msg = msg[0:32] + "05" + msg[34:]
5852 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5853 if "OK" not in res:
5854 raise Exception("EAPOL_RX failed")
5855 dev[0].request("WPS_CANCEL")
5856 dev[0].wait_disconnected()
5857 dev[0].flush_scan_cache()
5858
5859def wps_m2_but_other(dev, apdev, title, msgtype):
fab49f61 5860 addr, bssid, hapd = wps_start_ext(apdev, dev)
d1883671
JM
5861 wps_ext_eap_identity_req(dev, hapd, bssid)
5862 wps_ext_eap_identity_resp(hapd, dev, addr)
5863 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5864 wps_ext_eap_wsc(hapd, dev, addr, "M1")
5865 logger.debug(title)
5866 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5867 if ev is None:
5868 raise Exception("Timeout on EAPOL-TX")
5869 hapd.request("SET ext_eapol_frame_io 0")
5870 dev.request("SET ext_eapol_frame_io 0")
5871 msg = ev.split(' ')[2]
5872 if msg[46:54] != '10220001':
5873 raise Exception("Could not find Message Type attribute")
5874 # Replace Message Type value. This will be rejected.
5875 msg = msg[0:54] + msgtype + msg[56:]
5876 res = dev.request("EAPOL_RX " + bssid + " " + msg)
5877 if "OK" not in res:
5878 raise Exception("EAPOL_RX failed")
5879 ev = dev.wait_event(["WPS-FAIL"], timeout=5)
5880 if ev is None:
5881 raise Exception("WPS-FAIL event not seen")
5882 dev.request("WPS_CANCEL")
5883 dev.wait_disconnected()
5884
5885def wps_m4_but_other(dev, apdev, title, msgtype):
fab49f61 5886 addr, bssid, hapd = wps_start_ext(apdev, dev)
d1883671
JM
5887 wps_ext_eap_identity_req(dev, hapd, bssid)
5888 wps_ext_eap_identity_resp(hapd, dev, addr)
5889 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5890 wps_ext_eap_wsc(hapd, dev, addr, "M1")
5891 wps_ext_eap_wsc(dev, hapd, bssid, "M2")
5892 wps_ext_eap_wsc(hapd, dev, addr, "M3")
5893 logger.debug(title)
5894 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5895 if ev is None:
5896 raise Exception("Timeout on EAPOL-TX")
5897 hapd.request("SET ext_eapol_frame_io 0")
5898 dev.request("SET ext_eapol_frame_io 0")
5899 msg = ev.split(' ')[2]
5900 if msg[46:54] != '10220001':
5901 raise Exception("Could not find Message Type attribute")
5902 # Replace Message Type value. This will be rejected.
5903 msg = msg[0:54] + msgtype + msg[56:]
5904 res = dev.request("EAPOL_RX " + bssid + " " + msg)
5905 if "OK" not in res:
5906 raise Exception("EAPOL_RX failed")
5907 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5908 if ev is None:
5909 raise Exception("WPS-FAIL event not seen")
5910 dev.request("WPS_CANCEL")
5911 dev.wait_disconnected()
5912
5913def test_ap_wps_m2_msg_type_m4(dev, apdev):
5914 """WPS and M2 but Message Type M4"""
5915 wps_m2_but_other(dev[0], apdev[0], "M2/M4", "08")
5916
5917def test_ap_wps_m2_msg_type_m6(dev, apdev):
5918 """WPS and M2 but Message Type M6"""
5919 wps_m2_but_other(dev[0], apdev[0], "M2/M6", "0a")
5920
5921def test_ap_wps_m2_msg_type_m8(dev, apdev):
5922 """WPS and M2 but Message Type M8"""
5923 wps_m2_but_other(dev[0], apdev[0], "M2/M8", "0c")
5924
5925def test_ap_wps_m4_msg_type_m2(dev, apdev):
5926 """WPS and M4 but Message Type M2"""
5927 wps_m4_but_other(dev[0], apdev[0], "M4/M2", "05")
5928
5929def test_ap_wps_m4_msg_type_m2d(dev, apdev):
5930 """WPS and M4 but Message Type M2D"""
5931 wps_m4_but_other(dev[0], apdev[0], "M4/M2D", "06")
5932
9fd6804d 5933@remote_compatible
24b7f282
JM
5934def test_ap_wps_config_methods(dev, apdev):
5935 """WPS configuration method parsing"""
5936 ssid = "test-wps-conf"
fab49f61
JM
5937 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5938 "wpa_passphrase": "12345678", "wpa": "2",
5939 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5940 "config_methods": "ethernet display ext_nfc_token int_nfc_token physical_display physical_push_button"}
8b8a1864 5941 hapd = hostapd.add_ap(apdev[0], params)
fab49f61
JM
5942 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5943 "wpa_passphrase": "12345678", "wpa": "2",
5944 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5945 "config_methods": "display push_button"}
8b8a1864 5946 hapd2 = hostapd.add_ap(apdev[1], params)
476daa05
JM
5947
5948def test_ap_wps_set_selected_registrar_proto(dev, apdev):
5949 """WPS UPnP SetSelectedRegistrar protocol testing"""
5950 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 5951 hapd = add_ssdp_ap(apdev[0], ap_uuid)
476daa05
JM
5952
5953 location = ssdp_get_location(ap_uuid)
5954 urls = upnp_get_urls(location)
9c06eda0
MH
5955 eventurl = urlparse(urls['event_sub_url'])
5956 ctrlurl = urlparse(urls['control_url'])
5957 url = urlparse(location)
5958 conn = HTTPConnection(url.netloc)
476daa05 5959
9c06eda0 5960 class WPSERHTTPServer(StreamRequestHandler):
476daa05
JM
5961 def handle(self):
5962 data = self.rfile.readline().strip()
5963 logger.debug(data)
5964 self.wfile.write(gen_wps_event())
5965
5966 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
5967 server.timeout = 1
5968
fab49f61
JM
5969 headers = {"callback": '<http://127.0.0.1:12345/event>',
5970 "NT": "upnp:event",
5971 "timeout": "Second-1234"}
476daa05
JM
5972 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
5973 resp = conn.getresponse()
5974 if resp.status != 200:
5975 raise Exception("Unexpected HTTP response: %d" % resp.status)
5976 sid = resp.getheader("sid")
5977 logger.debug("Subscription SID " + sid)
5978 server.handle_request()
5979
fab49f61
JM
5980 tests = [(500, "10"),
5981 (200, "104a000110" + "1041000101" + "101200020000" +
5982 "105300023148" +
5983 "1049002c00372a0001200124111111111111222222222222333333333333444444444444555555555555666666666666" +
5984 "10480010362db47ba53a519188fb5458b986b2e4"),
5985 (200, "104a000110" + "1041000100" + "101200020000" +
5986 "105300020000"),
5987 (200, "104a000110" + "1041000100"),
5988 (200, "104a000110")]
5989 for status, test in tests:
476daa05 5990 tlvs = binascii.unhexlify(test)
c4e333fa 5991 newmsg = base64.b64encode(tlvs).decode()
476daa05
JM
5992 msg = '<?xml version="1.0"?>\n'
5993 msg += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
5994 msg += '<s:Body>'
5995 msg += '<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">'
5996 msg += '<NewMessage>'
5997 msg += newmsg
5998 msg += "</NewMessage></u:SetSelectedRegistrar></s:Body></s:Envelope>"
fab49f61 5999 headers = {"Content-type": 'text/xml; charset="utf-8"'}
476daa05
JM
6000 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
6001 conn.request("POST", ctrlurl.path, msg, headers)
6002 resp = conn.getresponse()
6003 if resp.status != status:
6004 raise Exception("Unexpected HTTP response: %d (expected %d)" % (resp.status, status))
96038a5f
JM
6005
6006def test_ap_wps_adv_oom(dev, apdev):
6007 """WPS AP and advertisement OOM"""
6008 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 6009 hapd = add_ssdp_ap(apdev[0], ap_uuid)
96038a5f
JM
6010
6011 with alloc_fail(hapd, 1, "=msearchreply_state_machine_start"):
6012 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
6013 no_recv=True)
6014 time.sleep(0.2)
6015
6016 with alloc_fail(hapd, 1, "eloop_register_timeout;msearchreply_state_machine_start"):
6017 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
6018 no_recv=True)
6019 time.sleep(0.2)
6020
6021 with alloc_fail(hapd, 1,
6022 "next_advertisement;advertisement_state_machine_stop"):
6023 hapd.disable()
6024
6025 with alloc_fail(hapd, 1, "ssdp_listener_start"):
6026 if "FAIL" not in hapd.request("ENABLE"):
6027 raise Exception("ENABLE succeeded during OOM")
926404a6
JM
6028
6029def test_wps_config_methods(dev):
6030 """WPS config method update"""
6031 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
6032 wpas.interface_add("wlan5")
6033 if "OK" not in wpas.request("SET config_methods display label"):
6034 raise Exception("Failed to set config_methods")
6035 if wpas.request("GET config_methods").strip() != "display label":
6036 raise Exception("config_methods were not updated")
6037 if "OK" not in wpas.request("SET config_methods "):
6038 raise Exception("Failed to clear config_methods")
6039 if wpas.request("GET config_methods").strip() != "":
6040 raise Exception("config_methods were not cleared")
7511ead0
JM
6041
6042WPS_VENDOR_ID_WFA = 14122
6043WPS_VENDOR_TYPE = 1
6044
6045# EAP-WSC Op-Code values
6046WSC_Start = 0x01
6047WSC_ACK = 0x02
6048WSC_NACK = 0x03
6049WSC_MSG = 0x04
6050WSC_Done = 0x05
6051WSC_FRAG_ACK = 0x06
6052
6053ATTR_AP_CHANNEL = 0x1001
6054ATTR_ASSOC_STATE = 0x1002
6055ATTR_AUTH_TYPE = 0x1003
6056ATTR_AUTH_TYPE_FLAGS = 0x1004
6057ATTR_AUTHENTICATOR = 0x1005
6058ATTR_CONFIG_METHODS = 0x1008
6059ATTR_CONFIG_ERROR = 0x1009
6060ATTR_CONFIRM_URL4 = 0x100a
6061ATTR_CONFIRM_URL6 = 0x100b
6062ATTR_CONN_TYPE = 0x100c
6063ATTR_CONN_TYPE_FLAGS = 0x100d
6064ATTR_CRED = 0x100e
6065ATTR_ENCR_TYPE = 0x100f
6066ATTR_ENCR_TYPE_FLAGS = 0x1010
6067ATTR_DEV_NAME = 0x1011
6068ATTR_DEV_PASSWORD_ID = 0x1012
6069ATTR_E_HASH1 = 0x1014
6070ATTR_E_HASH2 = 0x1015
6071ATTR_E_SNONCE1 = 0x1016
6072ATTR_E_SNONCE2 = 0x1017
6073ATTR_ENCR_SETTINGS = 0x1018
6074ATTR_ENROLLEE_NONCE = 0x101a
6075ATTR_FEATURE_ID = 0x101b
6076ATTR_IDENTITY = 0x101c
6077ATTR_IDENTITY_PROOF = 0x101d
6078ATTR_KEY_WRAP_AUTH = 0x101e
6079ATTR_KEY_ID = 0x101f
6080ATTR_MAC_ADDR = 0x1020
6081ATTR_MANUFACTURER = 0x1021
6082ATTR_MSG_TYPE = 0x1022
6083ATTR_MODEL_NAME = 0x1023
6084ATTR_MODEL_NUMBER = 0x1024
6085ATTR_NETWORK_INDEX = 0x1026
6086ATTR_NETWORK_KEY = 0x1027
6087ATTR_NETWORK_KEY_INDEX = 0x1028
6088ATTR_NEW_DEVICE_NAME = 0x1029
6089ATTR_NEW_PASSWORD = 0x102a
6090ATTR_OOB_DEVICE_PASSWORD = 0x102c
6091ATTR_OS_VERSION = 0x102d
6092ATTR_POWER_LEVEL = 0x102f
6093ATTR_PSK_CURRENT = 0x1030
6094ATTR_PSK_MAX = 0x1031
6095ATTR_PUBLIC_KEY = 0x1032
6096ATTR_RADIO_ENABLE = 0x1033
6097ATTR_REBOOT = 0x1034
6098ATTR_REGISTRAR_CURRENT = 0x1035
6099ATTR_REGISTRAR_ESTABLISHED = 0x1036
6100ATTR_REGISTRAR_LIST = 0x1037
6101ATTR_REGISTRAR_MAX = 0x1038
6102ATTR_REGISTRAR_NONCE = 0x1039
6103ATTR_REQUEST_TYPE = 0x103a
6104ATTR_RESPONSE_TYPE = 0x103b
6105ATTR_RF_BANDS = 0x103c
6106ATTR_R_HASH1 = 0x103d
6107ATTR_R_HASH2 = 0x103e
6108ATTR_R_SNONCE1 = 0x103f
6109ATTR_R_SNONCE2 = 0x1040
6110ATTR_SELECTED_REGISTRAR = 0x1041
6111ATTR_SERIAL_NUMBER = 0x1042
6112ATTR_WPS_STATE = 0x1044
6113ATTR_SSID = 0x1045
6114ATTR_TOTAL_NETWORKS = 0x1046
6115ATTR_UUID_E = 0x1047
6116ATTR_UUID_R = 0x1048
6117ATTR_VENDOR_EXT = 0x1049
6118ATTR_VERSION = 0x104a
6119ATTR_X509_CERT_REQ = 0x104b
6120ATTR_X509_CERT = 0x104c
6121ATTR_EAP_IDENTITY = 0x104d
6122ATTR_MSG_COUNTER = 0x104e
6123ATTR_PUBKEY_HASH = 0x104f
6124ATTR_REKEY_KEY = 0x1050
6125ATTR_KEY_LIFETIME = 0x1051
6126ATTR_PERMITTED_CFG_METHODS = 0x1052
6127ATTR_SELECTED_REGISTRAR_CONFIG_METHODS = 0x1053
6128ATTR_PRIMARY_DEV_TYPE = 0x1054
6129ATTR_SECONDARY_DEV_TYPE_LIST = 0x1055
6130ATTR_PORTABLE_DEV = 0x1056
6131ATTR_AP_SETUP_LOCKED = 0x1057
6132ATTR_APPLICATION_EXT = 0x1058
6133ATTR_EAP_TYPE = 0x1059
6134ATTR_IV = 0x1060
6135ATTR_KEY_PROVIDED_AUTO = 0x1061
6136ATTR_802_1X_ENABLED = 0x1062
6137ATTR_APPSESSIONKEY = 0x1063
6138ATTR_WEPTRANSMITKEY = 0x1064
6139ATTR_REQUESTED_DEV_TYPE = 0x106a
6140
6141# Message Type
6142WPS_Beacon = 0x01
6143WPS_ProbeRequest = 0x02
6144WPS_ProbeResponse = 0x03
6145WPS_M1 = 0x04
6146WPS_M2 = 0x05
6147WPS_M2D = 0x06
6148WPS_M3 = 0x07
6149WPS_M4 = 0x08
6150WPS_M5 = 0x09
6151WPS_M6 = 0x0a
6152WPS_M7 = 0x0b
6153WPS_M8 = 0x0c
6154WPS_WSC_ACK = 0x0d
6155WPS_WSC_NACK = 0x0e
6156WPS_WSC_DONE = 0x0f
6157
6158def get_wsc_msg(dev):
6159 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
6160 if ev is None:
6161 raise Exception("Timeout on EAPOL-TX")
6162 data = binascii.unhexlify(ev.split(' ')[2])
6163 msg = {}
6164
6165 # Parse EAPOL header
6166 if len(data) < 4:
6167 raise Exception("No room for EAPOL header")
fab49f61 6168 version, type, length = struct.unpack('>BBH', data[0:4])
7511ead0
JM
6169 msg['eapol_version'] = version
6170 msg['eapol_type'] = type
6171 msg['eapol_length'] = length
6172 data = data[4:]
6173 if length != len(data):
6174 raise Exception("EAPOL header length mismatch (%d != %d)" % (length, len(data)))
6175 if type != 0:
6176 raise Exception("Unexpected EAPOL header type: %d" % type)
6177
6178 # Parse EAP header
6179 if len(data) < 4:
6180 raise Exception("No room for EAP header")
fab49f61 6181 code, identifier, length = struct.unpack('>BBH', data[0:4])
7511ead0
JM
6182 msg['eap_code'] = code
6183 msg['eap_identifier'] = identifier
6184 msg['eap_length'] = length
6185 data = data[4:]
6186 if msg['eapol_length'] != msg['eap_length']:
6187 raise Exception("EAP header length mismatch (%d != %d)" % (msg['eapol_length'], length))
6188
6189 # Parse EAP expanded header
6190 if len(data) < 1:
6191 raise Exception("No EAP type included")
786ce912 6192 msg['eap_type'], = struct.unpack('B', data[0:1])
7511ead0
JM
6193 data = data[1:]
6194
6195 if msg['eap_type'] == 254:
6196 if len(data) < 3 + 4:
6197 raise Exception("Truncated EAP expanded header")
15dfcb69 6198 msg['eap_vendor_id'], msg['eap_vendor_type'] = struct.unpack('>LL', b'\x00' + data[0:7])
7511ead0
JM
6199 data = data[7:]
6200 else:
6201 raise Exception("Unexpected EAP type")
6202
6203 if msg['eap_vendor_id'] != WPS_VENDOR_ID_WFA:
6204 raise Exception("Unexpected Vendor-Id")
6205 if msg['eap_vendor_type'] != WPS_VENDOR_TYPE:
6206 raise Exception("Unexpected Vendor-Type")
6207
6208 # Parse EAP-WSC header
6209 if len(data) < 2:
6210 raise Exception("Truncated EAP-WSC header")
6211 msg['wsc_opcode'], msg['wsc_flags'] = struct.unpack('BB', data[0:2])
6212 data = data[2:]
6213
6214 # Parse WSC attributes
6215 msg['raw_attrs'] = data
6216 attrs = {}
6217 while len(data) > 0:
6218 if len(data) < 4:
6219 raise Exception("Truncated attribute header")
fab49f61 6220 attr, length = struct.unpack('>HH', data[0:4])
7511ead0
JM
6221 data = data[4:]
6222 if length > len(data):
6223 raise Exception("Truncated attribute 0x%04x" % attr)
6224 attrs[attr] = data[0:length]
6225 data = data[length:]
6226 msg['wsc_attrs'] = attrs
6227
6228 if ATTR_MSG_TYPE in attrs:
6229 msg['wsc_msg_type'], = struct.unpack('B', attrs[ATTR_MSG_TYPE])
6230
6231 return msg
6232
6233def recv_wsc_msg(dev, opcode, msg_type):
6234 msg = get_wsc_msg(dev)
6235 if msg['wsc_opcode'] != opcode or msg['wsc_msg_type'] != msg_type:
6236 raise Exception("Unexpected Op-Code/MsgType")
6237 return msg, msg['wsc_attrs'], msg['raw_attrs']
6238
6239def build_wsc_attr(attr, payload):
b7da11fd
JM
6240 _payload = payload if type(payload) == bytes else payload.encode()
6241 return struct.pack('>HH', attr, len(_payload)) + _payload
7511ead0
JM
6242
6243def build_attr_msg_type(msg_type):
6244 return build_wsc_attr(ATTR_MSG_TYPE, struct.pack('B', msg_type))
6245
6246def build_eap_wsc(eap_code, eap_id, payload, opcode=WSC_MSG):
6247 length = 4 + 8 + 2 + len(payload)
6248 # EAPOL header
6249 msg = struct.pack('>BBH', 2, 0, length)
6250 # EAP header
6251 msg += struct.pack('>BBH', eap_code, eap_id, length)
6252 # EAP expanded header for EAP-WSC
6253 msg += struct.pack('B', 254)
6254 msg += struct.pack('>L', WPS_VENDOR_ID_WFA)[1:4]
6255 msg += struct.pack('>L', WPS_VENDOR_TYPE)
6256 # EAP-WSC header
6257 msg += struct.pack('BB', opcode, 0)
6258 # WSC attributes
6259 msg += payload
6260 return msg
6261
6262def build_eap_success(eap_id):
6263 length = 4
6264 # EAPOL header
6265 msg = struct.pack('>BBH', 2, 0, length)
6266 # EAP header
6267 msg += struct.pack('>BBH', 3, eap_id, length)
6268 return msg
6269
6270def build_eap_failure(eap_id):
6271 length = 4
6272 # EAPOL header
6273 msg = struct.pack('>BBH', 2, 0, length)
6274 # EAP header
6275 msg += struct.pack('>BBH', 4, eap_id, length)
6276 return msg
6277
6278def send_wsc_msg(dev, src, msg):
7ab74770 6279 res = dev.request("EAPOL_RX " + src + " " + binascii.hexlify(msg).decode())
7511ead0
JM
6280 if "OK" not in res:
6281 raise Exception("EAPOL_RX failed")
6282
6283group_5_prime = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF
6284group_5_generator = 2
6285
6286def wsc_kdf(key, label, bits):
15dfcb69 6287 result = b''
7511ead0
JM
6288 i = 1
6289 while len(result) * 8 < bits:
f94df3c0 6290 data = struct.pack('>L', i) + label.encode() + struct.pack('>L', bits)
7511ead0
JM
6291 m = hmac.new(key, data, hashlib.sha256)
6292 result += m.digest()
6293 i += 1
236bbda8 6294 return result[0:bits // 8]
7511ead0
JM
6295
6296def wsc_keys(kdk):
6297 keys = wsc_kdf(kdk, "Wi-Fi Easy and Secure Key Derivation", 640)
6298 authkey = keys[0:32]
6299 keywrapkey = keys[32:48]
6300 emsk = keys[48:80]
fab49f61 6301 return authkey, keywrapkey, emsk
7511ead0
JM
6302
6303def wsc_dev_pw_half_psk(authkey, dev_pw):
f94df3c0 6304 m = hmac.new(authkey, dev_pw.encode(), hashlib.sha256)
7511ead0
JM
6305 return m.digest()[0:16]
6306
6307def wsc_dev_pw_psk(authkey, dev_pw):
236bbda8
JM
6308 dev_pw_1 = dev_pw[0:len(dev_pw) // 2]
6309 dev_pw_2 = dev_pw[len(dev_pw) // 2:]
7511ead0
JM
6310 psk1 = wsc_dev_pw_half_psk(authkey, dev_pw_1)
6311 psk2 = wsc_dev_pw_half_psk(authkey, dev_pw_2)
fab49f61 6312 return psk1, psk2
7511ead0
JM
6313
6314def build_attr_authenticator(authkey, prev_msg, curr_msg):
6315 m = hmac.new(authkey, prev_msg + curr_msg, hashlib.sha256)
6316 auth = m.digest()[0:8]
6317 return build_wsc_attr(ATTR_AUTHENTICATOR, auth)
6318
6319def build_attr_encr_settings(authkey, keywrapkey, data):
6320 m = hmac.new(authkey, data, hashlib.sha256)
6321 kwa = m.digest()[0:8]
6322 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
15dfcb69 6323 iv = 16*b'\x99'
7511ead0
JM
6324 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6325 pad_len = 16 - len(data) % 16
6326 ps = pad_len * struct.pack('B', pad_len)
6327 data += ps
6328 wrapped = aes.encrypt(data)
6329 return build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6330
6331def decrypt_attr_encr_settings(authkey, keywrapkey, data):
6332 if len(data) < 32 or len(data) % 16 != 0:
6333 raise Exception("Unexpected Encrypted Settings length: %d" % len(data))
6334 iv = data[0:16]
6335 encr = data[16:]
6336 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6337 decrypted = aes.decrypt(encr)
786ce912 6338 pad_len, = struct.unpack('B', decrypted[-1:])
7511ead0
JM
6339 if pad_len > len(decrypted):
6340 raise Exception("Invalid padding in Encrypted Settings")
6341 for i in range(-pad_len, -1):
6342 if decrypted[i] != decrypted[-1]:
6343 raise Exception("Invalid PS value in Encrypted Settings")
db98b587 6344
7511ead0
JM
6345 decrypted = decrypted[0:len(decrypted) - pad_len]
6346 if len(decrypted) < 12:
6347 raise Exception("Truncated Encrypted Settings plaintext")
6348 kwa = decrypted[-12:]
fab49f61 6349 attr, length = struct.unpack(">HH", kwa[0:4])
7511ead0
JM
6350 if attr != ATTR_KEY_WRAP_AUTH or length != 8:
6351 raise Exception("Invalid KWA header")
6352 kwa = kwa[4:]
6353 decrypted = decrypted[0:len(decrypted) - 12]
6354
6355 m = hmac.new(authkey, decrypted, hashlib.sha256)
6356 calc_kwa = m.digest()[0:8]
6357 if kwa != calc_kwa:
6358 raise Exception("KWA mismatch")
6359
6360 return decrypted
6361
6362def zeropad_str(val, pad_len):
6363 while len(val) < pad_len * 2:
6364 val = '0' + val
6365 return val
6366
6367def wsc_dh_init():
6368 # For now, use a hardcoded private key. In theory, this is supposed to be
6369 # randomly selected.
6370 own_private = 0x123456789
6371 own_public = pow(group_5_generator, own_private, group_5_prime)
6372 pk = binascii.unhexlify(zeropad_str(format(own_public, '02x'), 192))
6373 return own_private, pk
6374
6375def wsc_dh_kdf(peer_pk, own_private, mac_addr, e_nonce, r_nonce):
e6b283f7 6376 peer_public = int(binascii.hexlify(peer_pk), 16)
7511ead0
JM
6377 if peer_public < 2 or peer_public >= group_5_prime:
6378 raise Exception("Invalid peer public key")
236bbda8 6379 if pow(peer_public, (group_5_prime - 1) // 2, group_5_prime) != 1:
7511ead0
JM
6380 raise Exception("Unexpected Legendre symbol for peer public key")
6381
6382 shared_secret = pow(peer_public, own_private, group_5_prime)
6383 ss = zeropad_str(format(shared_secret, "02x"), 192)
6384 logger.debug("DH shared secret: " + ss)
6385
6386 dhkey = hashlib.sha256(binascii.unhexlify(ss)).digest()
7ab74770 6387 logger.debug("DHKey: " + binascii.hexlify(dhkey).decode())
7511ead0
JM
6388
6389 m = hmac.new(dhkey, e_nonce + mac_addr + r_nonce, hashlib.sha256)
6390 kdk = m.digest()
7ab74770 6391 logger.debug("KDK: " + binascii.hexlify(kdk).decode())
fab49f61 6392 authkey, keywrapkey, emsk = wsc_keys(kdk)
7ab74770
MH
6393 logger.debug("AuthKey: " + binascii.hexlify(authkey).decode())
6394 logger.debug("KeyWrapKey: " + binascii.hexlify(keywrapkey).decode())
6395 logger.debug("EMSK: " + binascii.hexlify(emsk).decode())
fab49f61 6396 return authkey, keywrapkey
7511ead0
JM
6397
6398def wsc_dev_pw_hash(authkey, dev_pw, e_pk, r_pk):
fab49f61 6399 psk1, psk2 = wsc_dev_pw_psk(authkey, dev_pw)
7ab74770
MH
6400 logger.debug("PSK1: " + binascii.hexlify(psk1).decode())
6401 logger.debug("PSK2: " + binascii.hexlify(psk2).decode())
7511ead0
JM
6402
6403 # Note: Secret values are supposed to be random, but hardcoded values are
6404 # fine for testing.
15dfcb69 6405 s1 = 16*b'\x77'
7511ead0
JM
6406 m = hmac.new(authkey, s1 + psk1 + e_pk + r_pk, hashlib.sha256)
6407 hash1 = m.digest()
7ab74770 6408 logger.debug("Hash1: " + binascii.hexlify(hash1).decode())
7511ead0 6409
15dfcb69 6410 s2 = 16*b'\x88'
7511ead0
JM
6411 m = hmac.new(authkey, s2 + psk2 + e_pk + r_pk, hashlib.sha256)
6412 hash2 = m.digest()
7ab74770 6413 logger.debug("Hash2: " + binascii.hexlify(hash2).decode())
fab49f61 6414 return s1, s2, hash1, hash2
7511ead0
JM
6415
6416def build_m1(eap_id, uuid_e, mac_addr, e_nonce, e_pk,
6417 manufacturer='', model_name='', config_methods='\x00\x00'):
6418 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6419 attrs += build_attr_msg_type(WPS_M1)
6420 attrs += build_wsc_attr(ATTR_UUID_E, uuid_e)
6421 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6422 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6423 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, e_pk)
6424 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6425 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6426 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6427 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, config_methods)
6428 attrs += build_wsc_attr(ATTR_WPS_STATE, '\x00')
6429 attrs += build_wsc_attr(ATTR_MANUFACTURER, manufacturer)
6430 attrs += build_wsc_attr(ATTR_MODEL_NAME, model_name)
6431 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6432 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6433 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6434 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6435 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6436 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6437 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, '\x00\x00')
6438 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6439 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6440 m1 = build_eap_wsc(2, eap_id, attrs)
6441 return m1, attrs
6442
6443def build_m2(authkey, m1, eap_id, e_nonce, r_nonce, uuid_r, r_pk,
6444 dev_pw_id='\x00\x00', eap_code=1):
6445 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6446 attrs += build_attr_msg_type(WPS_M2)
6447 if e_nonce:
6448 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6449 if r_nonce:
6450 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6451 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6452 if r_pk:
6453 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, r_pk)
6454 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6455 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6456 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6457 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6458 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6459 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6460 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6461 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6462 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6463 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6464 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6465 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6466 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6467 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6468 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6469 attrs += build_attr_authenticator(authkey, m1, attrs)
6470 m2 = build_eap_wsc(eap_code, eap_id, attrs)
6471 return m2, attrs
6472
6473def build_m2d(m1, eap_id, e_nonce, r_nonce, uuid_r, dev_pw_id=None, eap_code=1):
6474 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6475 attrs += build_attr_msg_type(WPS_M2D)
6476 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6477 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6478 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6479 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6480 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6481 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6482 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6483 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6484 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6485 #attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6486 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6487 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6488 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6489 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6490 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6491 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6492 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6493 if dev_pw_id:
6494 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6495 m2d = build_eap_wsc(eap_code, eap_id, attrs)
6496 return m2d, attrs
6497
6498def build_ack(eap_id, e_nonce, r_nonce, msg_type=WPS_WSC_ACK, eap_code=1):
6499 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6500 if msg_type is not None:
6501 attrs += build_attr_msg_type(msg_type)
6502 if e_nonce:
6503 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6504 if r_nonce:
6505 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6506 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_ACK)
6507 return msg, attrs
6508
6509def build_nack(eap_id, e_nonce, r_nonce, config_error='\x00\x00',
6510 msg_type=WPS_WSC_NACK, eap_code=1):
6511 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6512 if msg_type is not None:
6513 attrs += build_attr_msg_type(msg_type)
6514 if e_nonce:
6515 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6516 if r_nonce:
6517 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6518 if config_error:
6519 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, config_error)
6520 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_NACK)
6521 return msg, attrs
6522
6523def test_wps_ext(dev, apdev):
6524 """WPS against external implementation"""
6525 pin = "12345670"
fab49f61 6526 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
6527 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6528 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6529
6530 logger.debug("Receive WSC/Start from AP")
6531 msg = get_wsc_msg(hapd)
6532 if msg['wsc_opcode'] != WSC_Start:
6533 raise Exception("Unexpected Op-Code for WSC/Start")
6534 wsc_start_id = msg['eap_identifier']
6535
6536 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
6537 uuid_e = 16*b'\x11'
6538 e_nonce = 16*b'\x22'
7511ead0
JM
6539 own_private, e_pk = wsc_dh_init()
6540
6541 logger.debug("Send M1 to AP")
6542 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
6543 e_nonce, e_pk)
6544 send_wsc_msg(hapd, addr, m1)
6545
6546 logger.debug("Receive M2 from AP")
6547 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
6548
fab49f61
JM
6549 authkey, keywrapkey = wsc_dh_kdf(m2_attrs[ATTR_PUBLIC_KEY], own_private,
6550 mac_addr, e_nonce,
6551 m2_attrs[ATTR_REGISTRAR_NONCE])
6552 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk,
6553 m2_attrs[ATTR_PUBLIC_KEY])
7511ead0
JM
6554
6555 logger.debug("Send M3 to AP")
6556 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6557 attrs += build_attr_msg_type(WPS_M3)
6558 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6559 m2_attrs[ATTR_REGISTRAR_NONCE])
6560 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
6561 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
6562 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
6563 raw_m3_attrs = attrs
6564 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6565 send_wsc_msg(hapd, addr, m3)
6566
6567 logger.debug("Receive M4 from AP")
6568 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
6569
6570 logger.debug("Send M5 to AP")
6571 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6572 attrs += build_attr_msg_type(WPS_M5)
6573 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6574 m2_attrs[ATTR_REGISTRAR_NONCE])
6575 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
6576 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6577 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
6578 raw_m5_attrs = attrs
6579 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6580 send_wsc_msg(hapd, addr, m5)
6581
6582 logger.debug("Receive M6 from AP")
6583 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
6584
6585 logger.debug("Send M7 to AP")
6586 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6587 attrs += build_attr_msg_type(WPS_M7)
6588 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6589 m2_attrs[ATTR_REGISTRAR_NONCE])
6590 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
6591 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6592 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
6593 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6594 raw_m7_attrs = attrs
6595 send_wsc_msg(hapd, addr, m7)
6596
6597 logger.debug("Receive M8 from AP")
6598 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
6599 m8_cred = decrypt_attr_encr_settings(authkey, keywrapkey,
6600 m8_attrs[ATTR_ENCR_SETTINGS])
7ab74770 6601 logger.debug("M8 Credential: " + binascii.hexlify(m8_cred).decode())
7511ead0
JM
6602
6603 logger.debug("Prepare WSC_Done")
6604 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6605 attrs += build_attr_msg_type(WPS_WSC_DONE)
6606 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6607 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6608 m2_attrs[ATTR_REGISTRAR_NONCE])
6609 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
6610 # Do not send WSC_Done yet to allow exchangw with STA complete before the
6611 # AP disconnects.
6612
15dfcb69
MH
6613 uuid_r = 16*b'\x33'
6614 r_nonce = 16*b'\x44'
7511ead0
JM
6615
6616 eap_id = wsc_start_id
6617 logger.debug("Send WSC/Start to STA")
15dfcb69 6618 wsc_start = build_eap_wsc(1, eap_id, b'', opcode=WSC_Start)
7511ead0
JM
6619 send_wsc_msg(dev[0], bssid, wsc_start)
6620 eap_id = (eap_id + 1) % 256
6621
6622 logger.debug("Receive M1 from STA")
6623 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6624
fab49f61
JM
6625 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6626 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6627 r_nonce)
6628 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
6629 m1_attrs[ATTR_PUBLIC_KEY],
6630 e_pk)
7511ead0
JM
6631
6632 logger.debug("Send M2 to STA")
6633 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6634 m1_attrs[ATTR_ENROLLEE_NONCE],
6635 r_nonce, uuid_r, e_pk)
6636 send_wsc_msg(dev[0], bssid, m2)
6637 eap_id = (eap_id + 1) % 256
6638
6639 logger.debug("Receive M3 from STA")
6640 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6641
6642 logger.debug("Send M4 to STA")
6643 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6644 attrs += build_attr_msg_type(WPS_M4)
6645 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6646 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6647 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6648 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6649 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6650 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6651 raw_m4_attrs = attrs
6652 m4 = build_eap_wsc(1, eap_id, attrs)
6653 send_wsc_msg(dev[0], bssid, m4)
6654 eap_id = (eap_id + 1) % 256
6655
6656 logger.debug("Receive M5 from STA")
6657 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6658
6659 logger.debug("Send M6 to STA")
6660 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6661 attrs += build_attr_msg_type(WPS_M6)
6662 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6663 m1_attrs[ATTR_ENROLLEE_NONCE])
6664 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6665 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6666 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6667 raw_m6_attrs = attrs
6668 m6 = build_eap_wsc(1, eap_id, attrs)
6669 send_wsc_msg(dev[0], bssid, m6)
6670 eap_id = (eap_id + 1) % 256
6671
6672 logger.debug("Receive M7 from STA")
6673 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6674
6675 logger.debug("Send M8 to STA")
6676 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6677 attrs += build_attr_msg_type(WPS_M8)
6678 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6679 m1_attrs[ATTR_ENROLLEE_NONCE])
6680 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6681 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6682 raw_m8_attrs = attrs
6683 m8 = build_eap_wsc(1, eap_id, attrs)
6684 send_wsc_msg(dev[0], bssid, m8)
6685 eap_id = (eap_id + 1) % 256
6686
6687 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=5)
6688 if ev is None:
6689 raise Exception("wpa_supplicant did not report credential")
6690
6691 logger.debug("Receive WSC_Done from STA")
6692 msg = get_wsc_msg(dev[0])
6693 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6694 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6695
6696 logger.debug("Send WSC_Done to AP")
6697 hapd.request("SET ext_eapol_frame_io 0")
6698 dev[0].request("SET ext_eapol_frame_io 0")
6699 send_wsc_msg(hapd, addr, wsc_done)
6700
6701 ev = hapd.wait_event(["WPS-REG-SUCCESS"], timeout=5)
6702 if ev is None:
6703 raise Exception("hostapd did not report WPS success")
6704
6705 dev[0].wait_connected()
6706
6707def wps_start_kwa(dev, apdev):
6708 pin = "12345670"
fab49f61 6709 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
6710 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6711 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6712 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6713
6714 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
6715 uuid_r = 16*b'\x33'
6716 r_nonce = 16*b'\x44'
7511ead0
JM
6717 own_private, e_pk = wsc_dh_init()
6718
6719 logger.debug("Receive M1 from STA")
6720 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6721 eap_id = (msg['eap_identifier'] + 1) % 256
6722
fab49f61
JM
6723 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6724 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6725 r_nonce)
6726 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
6727 m1_attrs[ATTR_PUBLIC_KEY],
6728 e_pk)
7511ead0
JM
6729
6730 logger.debug("Send M2 to STA")
6731 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6732 m1_attrs[ATTR_ENROLLEE_NONCE],
6733 r_nonce, uuid_r, e_pk)
6734 send_wsc_msg(dev[0], bssid, m2)
6735 eap_id = (eap_id + 1) % 256
6736
6737 logger.debug("Receive M3 from STA")
6738 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6739
6740 logger.debug("Send M4 to STA")
6741 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6742 attrs += build_attr_msg_type(WPS_M4)
6743 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6744 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6745 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6746
6747 return r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs
6748
6749def wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id):
6750 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6751 m4 = build_eap_wsc(1, eap_id, attrs)
6752 send_wsc_msg(dev[0], bssid, m4)
6753 eap_id = (eap_id + 1) % 256
6754
6755 logger.debug("Receive M5 from STA")
6756 msg = get_wsc_msg(dev[0])
6757 if msg['wsc_opcode'] != WSC_NACK:
6758 raise Exception("Unexpected message - expected WSC_Nack")
6759
6760 dev[0].request("WPS_CANCEL")
6761 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6762 dev[0].wait_disconnected()
6763
6764def test_wps_ext_kwa_proto_no_kwa(dev, apdev):
6765 """WPS and KWA error: No KWA attribute"""
fab49f61 6766 r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs = wps_start_kwa(dev, apdev)
7511ead0
JM
6767 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6768 # Encrypted Settings without KWA
15dfcb69 6769 iv = 16*b'\x99'
7511ead0
JM
6770 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6771 pad_len = 16 - len(data) % 16
6772 ps = pad_len * struct.pack('B', pad_len)
6773 data += ps
6774 wrapped = aes.encrypt(data)
6775 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6776 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6777
6778def test_wps_ext_kwa_proto_data_after_kwa(dev, apdev):
6779 """WPS and KWA error: Data after KWA"""
fab49f61 6780 r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs = wps_start_kwa(dev, apdev)
7511ead0
JM
6781 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6782 # Encrypted Settings and data after KWA
6783 m = hmac.new(authkey, data, hashlib.sha256)
6784 kwa = m.digest()[0:8]
6785 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6786 data += build_wsc_attr(ATTR_VENDOR_EXT, "1234567890")
15dfcb69 6787 iv = 16*b'\x99'
7511ead0
JM
6788 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6789 pad_len = 16 - len(data) % 16
6790 ps = pad_len * struct.pack('B', pad_len)
6791 data += ps
6792 wrapped = aes.encrypt(data)
6793 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6794 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6795
6796def test_wps_ext_kwa_proto_kwa_mismatch(dev, apdev):
6797 """WPS and KWA error: KWA mismatch"""
fab49f61 6798 r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs = wps_start_kwa(dev, apdev)
7511ead0
JM
6799 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6800 # Encrypted Settings and KWA with incorrect value
6801 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, 8*'\x00')
15dfcb69 6802 iv = 16*b'\x99'
7511ead0
JM
6803 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6804 pad_len = 16 - len(data) % 16
6805 ps = pad_len * struct.pack('B', pad_len)
6806 data += ps
6807 wrapped = aes.encrypt(data)
6808 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6809 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6810
6811def wps_run_cred_proto(dev, apdev, m8_cred, connect=False, no_connect=False):
6812 pin = "12345670"
fab49f61 6813 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
6814 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6815 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6816 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6817
6818 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
6819 uuid_r = 16*b'\x33'
6820 r_nonce = 16*b'\x44'
7511ead0
JM
6821 own_private, e_pk = wsc_dh_init()
6822
6823 logger.debug("Receive M1 from STA")
6824 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6825 eap_id = (msg['eap_identifier'] + 1) % 256
6826
fab49f61
JM
6827 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6828 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6829 r_nonce)
6830 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
6831 m1_attrs[ATTR_PUBLIC_KEY],
6832 e_pk)
7511ead0
JM
6833
6834 logger.debug("Send M2 to STA")
6835 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6836 m1_attrs[ATTR_ENROLLEE_NONCE],
6837 r_nonce, uuid_r, e_pk)
6838 send_wsc_msg(dev[0], bssid, m2)
6839 eap_id = (eap_id + 1) % 256
6840
6841 logger.debug("Receive M3 from STA")
6842 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6843
6844 logger.debug("Send M4 to STA")
6845 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6846 attrs += build_attr_msg_type(WPS_M4)
6847 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6848 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6849 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6850 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6851 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6852 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6853 raw_m4_attrs = attrs
6854 m4 = build_eap_wsc(1, eap_id, attrs)
6855 send_wsc_msg(dev[0], bssid, m4)
6856 eap_id = (eap_id + 1) % 256
6857
6858 logger.debug("Receive M5 from STA")
6859 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6860
6861 logger.debug("Send M6 to STA")
6862 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6863 attrs += build_attr_msg_type(WPS_M6)
6864 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6865 m1_attrs[ATTR_ENROLLEE_NONCE])
6866 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6867 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6868 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6869 raw_m6_attrs = attrs
6870 m6 = build_eap_wsc(1, eap_id, attrs)
6871 send_wsc_msg(dev[0], bssid, m6)
6872 eap_id = (eap_id + 1) % 256
6873
6874 logger.debug("Receive M7 from STA")
6875 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6876
6877 logger.debug("Send M8 to STA")
6878 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6879 attrs += build_attr_msg_type(WPS_M8)
6880 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6881 m1_attrs[ATTR_ENROLLEE_NONCE])
6882 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6883 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6884 raw_m8_attrs = attrs
6885 m8 = build_eap_wsc(1, eap_id, attrs)
6886 send_wsc_msg(dev[0], bssid, m8)
6887 eap_id = (eap_id + 1) % 256
6888
6889 if no_connect:
6890 logger.debug("Receive WSC_Done from STA")
6891 msg = get_wsc_msg(dev[0])
6892 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6893 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6894
6895 hapd.request("SET ext_eapol_frame_io 0")
6896 dev[0].request("SET ext_eapol_frame_io 0")
6897
6898 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6899
6900 dev[0].wait_disconnected()
6901 dev[0].request("REMOVE_NETWORK all")
6902 elif connect:
6903 logger.debug("Receive WSC_Done from STA")
6904 msg = get_wsc_msg(dev[0])
6905 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6906 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6907
6908 hapd.request("SET ext_eapol_frame_io 0")
6909 dev[0].request("SET ext_eapol_frame_io 0")
6910
6911 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6912
6913 dev[0].wait_connected()
6914 else:
6915 # Verify STA NACK's the credential
6916 msg = get_wsc_msg(dev[0])
6917 if msg['wsc_opcode'] != WSC_NACK:
6918 raise Exception("Unexpected message - expected WSC_Nack")
6919 dev[0].request("WPS_CANCEL")
6920 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6921 dev[0].wait_disconnected()
6922
6923def build_cred(nw_idx='\x01', ssid='test-wps-conf', auth_type='\x00\x20',
6924 encr_type='\x00\x08', nw_key="12345678",
6925 mac_addr='\x00\x00\x00\x00\x00\x00'):
15dfcb69 6926 attrs = b''
7511ead0
JM
6927 if nw_idx is not None:
6928 attrs += build_wsc_attr(ATTR_NETWORK_INDEX, nw_idx)
6929 if ssid is not None:
6930 attrs += build_wsc_attr(ATTR_SSID, ssid)
6931 if auth_type is not None:
6932 attrs += build_wsc_attr(ATTR_AUTH_TYPE, auth_type)
6933 if encr_type is not None:
6934 attrs += build_wsc_attr(ATTR_ENCR_TYPE, encr_type)
6935 if nw_key is not None:
6936 attrs += build_wsc_attr(ATTR_NETWORK_KEY, nw_key)
6937 if mac_addr is not None:
6938 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6939 return build_wsc_attr(ATTR_CRED, attrs)
6940
6941def test_wps_ext_cred_proto_success(dev, apdev):
6942 """WPS and Credential: success"""
6943 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6944 m8_cred = build_cred(mac_addr=mac_addr)
6945 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6946
6947def test_wps_ext_cred_proto_mac_addr_mismatch(dev, apdev):
6948 """WPS and Credential: MAC Address mismatch"""
6949 m8_cred = build_cred()
6950 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6951
6952def test_wps_ext_cred_proto_zero_padding(dev, apdev):
6953 """WPS and Credential: zeropadded attributes"""
6954 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6955 m8_cred = build_cred(mac_addr=mac_addr, ssid='test-wps-conf\x00',
6956 nw_key="12345678\x00")
6957 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6958
6959def test_wps_ext_cred_proto_ssid_missing(dev, apdev):
6960 """WPS and Credential: SSID missing"""
6961 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6962 m8_cred = build_cred(mac_addr=mac_addr, ssid=None)
6963 wps_run_cred_proto(dev, apdev, m8_cred)
6964
6965def test_wps_ext_cred_proto_ssid_zero_len(dev, apdev):
6966 """WPS and Credential: Zero-length SSID"""
6967 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6968 m8_cred = build_cred(mac_addr=mac_addr, ssid="")
6969 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6970
6971def test_wps_ext_cred_proto_auth_type_missing(dev, apdev):
6972 """WPS and Credential: Auth Type missing"""
6973 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6974 m8_cred = build_cred(mac_addr=mac_addr, auth_type=None)
6975 wps_run_cred_proto(dev, apdev, m8_cred)
6976
6977def test_wps_ext_cred_proto_encr_type_missing(dev, apdev):
6978 """WPS and Credential: Encr Type missing"""
6979 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6980 m8_cred = build_cred(mac_addr=mac_addr, encr_type=None)
6981 wps_run_cred_proto(dev, apdev, m8_cred)
6982
6983def test_wps_ext_cred_proto_network_key_missing(dev, apdev):
6984 """WPS and Credential: Network Key missing"""
6985 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6986 m8_cred = build_cred(mac_addr=mac_addr, nw_key=None)
6987 wps_run_cred_proto(dev, apdev, m8_cred)
6988
6989def test_wps_ext_cred_proto_network_key_missing_open(dev, apdev):
6990 """WPS and Credential: Network Key missing (open)"""
6991 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6992 m8_cred = build_cred(mac_addr=mac_addr, auth_type='\x00\x01',
6993 encr_type='\x00\x01', nw_key=None, ssid="foo")
6994 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6995
6996def test_wps_ext_cred_proto_mac_addr_missing(dev, apdev):
6997 """WPS and Credential: MAC Address missing"""
6998 m8_cred = build_cred(mac_addr=None)
6999 wps_run_cred_proto(dev, apdev, m8_cred)
7000
7001def test_wps_ext_cred_proto_invalid_encr_type(dev, apdev):
7002 """WPS and Credential: Invalid Encr Type"""
7003 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7004 m8_cred = build_cred(mac_addr=mac_addr, encr_type='\x00\x00')
7005 wps_run_cred_proto(dev, apdev, m8_cred)
7006
7007def test_wps_ext_cred_proto_missing_cred(dev, apdev):
7008 """WPS and Credential: Missing Credential"""
7009 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69 7010 m8_cred = b''
7511ead0
JM
7011 wps_run_cred_proto(dev, apdev, m8_cred)
7012
7013def test_wps_ext_proto_m2_no_public_key(dev, apdev):
7014 """WPS and no Public Key in M2"""
7015 pin = "12345670"
fab49f61 7016 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
7017 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7018 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7019 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7020
7021 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
7022 uuid_r = 16*b'\x33'
7023 r_nonce = 16*b'\x44'
7511ead0
JM
7024 own_private, e_pk = wsc_dh_init()
7025
7026 logger.debug("Receive M1 from STA")
7027 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7028 eap_id = (msg['eap_identifier'] + 1) % 256
7029
fab49f61
JM
7030 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7031 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7032 r_nonce)
7033 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7034 m1_attrs[ATTR_PUBLIC_KEY],
7035 e_pk)
7511ead0
JM
7036
7037 logger.debug("Send M2 to STA")
7038 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7039 m1_attrs[ATTR_ENROLLEE_NONCE],
7040 r_nonce, uuid_r, None)
7041 send_wsc_msg(dev[0], bssid, m2)
7042 eap_id = (eap_id + 1) % 256
7043
7044 # Verify STA NACK's the credential
7045 msg = get_wsc_msg(dev[0])
7046 if msg['wsc_opcode'] != WSC_NACK:
7047 raise Exception("Unexpected message - expected WSC_Nack")
7048 dev[0].request("WPS_CANCEL")
7049 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7050 dev[0].wait_disconnected()
7051
7052def test_wps_ext_proto_m2_invalid_public_key(dev, apdev):
7053 """WPS and invalid Public Key in M2"""
7054 pin = "12345670"
fab49f61 7055 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
7056 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7057 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7058 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7059
7060 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
7061 uuid_r = 16*b'\x33'
7062 r_nonce = 16*b'\x44'
7511ead0
JM
7063 own_private, e_pk = wsc_dh_init()
7064
7065 logger.debug("Receive M1 from STA")
7066 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7067 eap_id = (msg['eap_identifier'] + 1) % 256
7068
fab49f61
JM
7069 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7070 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7071 r_nonce)
7072 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7073 m1_attrs[ATTR_PUBLIC_KEY],
7074 e_pk)
7511ead0
JM
7075
7076 logger.debug("Send M2 to STA")
7077 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7078 m1_attrs[ATTR_ENROLLEE_NONCE],
15dfcb69 7079 r_nonce, uuid_r, 192*b'\xff')
7511ead0
JM
7080 send_wsc_msg(dev[0], bssid, m2)
7081 eap_id = (eap_id + 1) % 256
7082
7083 # Verify STA NACK's the credential
7084 msg = get_wsc_msg(dev[0])
7085 if msg['wsc_opcode'] != WSC_NACK:
7086 raise Exception("Unexpected message - expected WSC_Nack")
7087 dev[0].request("WPS_CANCEL")
7088 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7089 dev[0].wait_disconnected()
7090
7091def test_wps_ext_proto_m2_public_key_oom(dev, apdev):
7092 """WPS and Public Key OOM in M2"""
7093 pin = "12345670"
fab49f61 7094 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
7095 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7096 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7097 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7098
7099 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
7100 uuid_r = 16*b'\x33'
7101 r_nonce = 16*b'\x44'
7511ead0
JM
7102 own_private, e_pk = wsc_dh_init()
7103
7104 logger.debug("Receive M1 from STA")
7105 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7106 eap_id = (msg['eap_identifier'] + 1) % 256
7107
fab49f61
JM
7108 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7109 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7110 r_nonce)
7111 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7112 m1_attrs[ATTR_PUBLIC_KEY],
7113 e_pk)
7511ead0
JM
7114
7115 logger.debug("Send M2 to STA")
7116 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7117 m1_attrs[ATTR_ENROLLEE_NONCE],
7118 r_nonce, uuid_r, e_pk)
7119 with alloc_fail(dev[0], 1, "wpabuf_alloc_copy;wps_process_pubkey"):
7120 send_wsc_msg(dev[0], bssid, m2)
7121 eap_id = (eap_id + 1) % 256
7122
7123 # Verify STA NACK's the credential
7124 msg = get_wsc_msg(dev[0])
7125 if msg['wsc_opcode'] != WSC_NACK:
7126 raise Exception("Unexpected message - expected WSC_Nack")
7127 dev[0].request("WPS_CANCEL")
7128 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7129 dev[0].wait_disconnected()
7130
7131def test_wps_ext_proto_nack_m3(dev, apdev):
7132 """WPS and NACK M3"""
7133 pin = "12345670"
fab49f61 7134 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
7135 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7136 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7137 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7138
7139 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
7140 uuid_r = 16*b'\x33'
7141 r_nonce = 16*b'\x44'
7511ead0
JM
7142 own_private, e_pk = wsc_dh_init()
7143
7144 logger.debug("Receive M1 from STA")
7145 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7146 eap_id = (msg['eap_identifier'] + 1) % 256
7147
fab49f61
JM
7148 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7149 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7150 r_nonce)
7151 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7152 m1_attrs[ATTR_PUBLIC_KEY],
7153 e_pk)
7511ead0
JM
7154
7155 logger.debug("Send M2 to STA")
7156 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7157 m1_attrs[ATTR_ENROLLEE_NONCE],
7158 r_nonce, uuid_r, e_pk)
7159 send_wsc_msg(dev[0], bssid, m2)
7160 eap_id = (eap_id + 1) % 256
7161
7162 logger.debug("Receive M3 from STA")
7163 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7164
7165 logger.debug("Send NACK to STA")
7166 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7167 r_nonce, config_error='\x01\x23')
7168 send_wsc_msg(dev[0], bssid, msg)
7169 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7170 if ev is None:
7171 raise Exception("Failure not reported")
7172 if "msg=7 config_error=291" not in ev:
7173 raise Exception("Unexpected failure reason: " + ev)
7174
7175def test_wps_ext_proto_nack_m5(dev, apdev):
7176 """WPS and NACK M5"""
7177 pin = "12345670"
fab49f61 7178 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
7179 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7180 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7181 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7182
7183 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
7184 uuid_r = 16*b'\x33'
7185 r_nonce = 16*b'\x44'
7511ead0
JM
7186 own_private, e_pk = wsc_dh_init()
7187
7188 logger.debug("Receive M1 from STA")
7189 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7190 eap_id = (msg['eap_identifier'] + 1) % 256
7191
fab49f61
JM
7192 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7193 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7194 r_nonce)
7195 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7196 m1_attrs[ATTR_PUBLIC_KEY],
7197 e_pk)
7511ead0
JM
7198
7199 logger.debug("Send M2 to STA")
7200 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7201 m1_attrs[ATTR_ENROLLEE_NONCE],
7202 r_nonce, uuid_r, e_pk)
7203 send_wsc_msg(dev[0], bssid, m2)
7204 eap_id = (eap_id + 1) % 256
7205
7206 logger.debug("Receive M3 from STA")
7207 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7208
7209 logger.debug("Send M4 to STA")
7210 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7211 attrs += build_attr_msg_type(WPS_M4)
7212 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7213 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7214 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7215 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7216 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7217 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7218 raw_m4_attrs = attrs
7219 m4 = build_eap_wsc(1, eap_id, attrs)
7220 send_wsc_msg(dev[0], bssid, m4)
7221 eap_id = (eap_id + 1) % 256
7222
7223 logger.debug("Receive M5 from STA")
7224 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7225
7226 logger.debug("Send NACK to STA")
7227 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7228 r_nonce, config_error='\x01\x24')
7229 send_wsc_msg(dev[0], bssid, msg)
7230 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7231 if ev is None:
7232 raise Exception("Failure not reported")
7233 if "msg=9 config_error=292" not in ev:
7234 raise Exception("Unexpected failure reason: " + ev)
7235
7236def wps_nack_m3(dev, apdev):
7237 pin = "00000000"
fab49f61 7238 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
7511ead0
JM
7239 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7240 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7241 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7242
7243 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
7244 uuid_r = 16*b'\x33'
7245 r_nonce = 16*b'\x44'
7511ead0
JM
7246 own_private, e_pk = wsc_dh_init()
7247
7248 logger.debug("Receive M1 from STA")
7249 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7250 eap_id = (msg['eap_identifier'] + 1) % 256
7251
fab49f61
JM
7252 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7253 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7254 r_nonce)
7255 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7256 m1_attrs[ATTR_PUBLIC_KEY],
7257 e_pk)
7511ead0
JM
7258
7259 logger.debug("Send M2 to STA")
7260 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7261 m1_attrs[ATTR_ENROLLEE_NONCE],
7262 r_nonce, uuid_r, e_pk, dev_pw_id='\x00\x04')
7263 send_wsc_msg(dev[0], bssid, m2)
7264 eap_id = (eap_id + 1) % 256
7265
7266 logger.debug("Receive M3 from STA")
7267 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7268 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid
7269
7270def test_wps_ext_proto_nack_m3_no_config_error(dev, apdev):
7271 """WPS and NACK M3 missing Config Error"""
7272 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7273 logger.debug("Send NACK to STA")
7274 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, config_error=None)
7275 send_wsc_msg(dev[0], bssid, msg)
7276 dev[0].request("WPS_CANCEL")
7277 dev[0].wait_disconnected()
7278 dev[0].flush_scan_cache()
7279
7280def test_wps_ext_proto_nack_m3_no_e_nonce(dev, apdev):
7281 """WPS and NACK M3 missing E-Nonce"""
7282 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7283 logger.debug("Send NACK to STA")
7284 msg, attrs = build_nack(eap_id, None, r_nonce)
7285 send_wsc_msg(dev[0], bssid, msg)
7286 dev[0].request("WPS_CANCEL")
7287 dev[0].wait_disconnected()
7288 dev[0].flush_scan_cache()
7289
7290def test_wps_ext_proto_nack_m3_e_nonce_mismatch(dev, apdev):
7291 """WPS and NACK M3 E-Nonce mismatch"""
7292 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7293 logger.debug("Send NACK to STA")
7294 msg, attrs = build_nack(eap_id, 16*'\x00', r_nonce)
7295 send_wsc_msg(dev[0], bssid, msg)
7296 dev[0].request("WPS_CANCEL")
7297 dev[0].wait_disconnected()
7298 dev[0].flush_scan_cache()
7299
7300def test_wps_ext_proto_nack_m3_no_r_nonce(dev, apdev):
7301 """WPS and NACK M3 missing R-Nonce"""
7302 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7303 logger.debug("Send NACK to STA")
7304 msg, attrs = build_nack(eap_id, e_nonce, None)
7305 send_wsc_msg(dev[0], bssid, msg)
7306 dev[0].request("WPS_CANCEL")
7307 dev[0].wait_disconnected()
7308 dev[0].flush_scan_cache()
7309
7310def test_wps_ext_proto_nack_m3_r_nonce_mismatch(dev, apdev):
7311 """WPS and NACK M3 R-Nonce mismatch"""
7312 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7313 logger.debug("Send NACK to STA")
7314 msg, attrs = build_nack(eap_id, e_nonce, 16*'\x00')
7315 send_wsc_msg(dev[0], bssid, msg)
7316 dev[0].request("WPS_CANCEL")
7317 dev[0].wait_disconnected()
7318 dev[0].flush_scan_cache()
7319
7320def test_wps_ext_proto_nack_m3_no_msg_type(dev, apdev):
7321 """WPS and NACK M3 no Message Type"""
7322 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7323 logger.debug("Send NACK to STA")
7324 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=None)
7325 send_wsc_msg(dev[0], bssid, msg)
7326 dev[0].request("WPS_CANCEL")
7327 dev[0].wait_disconnected()
7328 dev[0].flush_scan_cache()
7329
7330def test_wps_ext_proto_nack_m3_invalid_msg_type(dev, apdev):
7331 """WPS and NACK M3 invalid Message Type"""
7332 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7333 logger.debug("Send NACK to STA")
7334 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=123)
7335 send_wsc_msg(dev[0], bssid, msg)
7336 dev[0].request("WPS_CANCEL")
7337 dev[0].wait_disconnected()
7338 dev[0].flush_scan_cache()
7339
7340def test_wps_ext_proto_nack_m3_invalid_attr(dev, apdev):
7341 """WPS and NACK M3 invalid attribute"""
7342 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7343 logger.debug("Send NACK to STA")
15dfcb69 7344 attrs = b'\x10\x10\x00'
7511ead0
JM
7345 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_NACK)
7346 send_wsc_msg(dev[0], bssid, msg)
7347 dev[0].request("WPS_CANCEL")
7348 dev[0].wait_disconnected()
7349 dev[0].flush_scan_cache()
7350
7351def test_wps_ext_proto_ack_m3_no_e_nonce(dev, apdev):
7352 """WPS and ACK M3 missing E-Nonce"""
7353 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7354 logger.debug("Send NACK to STA")
7355 msg, attrs = build_ack(eap_id, None, r_nonce)
7356 send_wsc_msg(dev[0], bssid, msg)
7357 dev[0].request("WPS_CANCEL")
7358 dev[0].wait_disconnected()
7359 dev[0].flush_scan_cache()
7360
7361def test_wps_ext_proto_ack_m3_e_nonce_mismatch(dev, apdev):
7362 """WPS and ACK M3 E-Nonce mismatch"""
7363 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7364 logger.debug("Send NACK to STA")
7365 msg, attrs = build_ack(eap_id, 16*'\x00', r_nonce)
7366 send_wsc_msg(dev[0], bssid, msg)
7367 dev[0].request("WPS_CANCEL")
7368 dev[0].wait_disconnected()
7369 dev[0].flush_scan_cache()
7370
7371def test_wps_ext_proto_ack_m3_no_r_nonce(dev, apdev):
7372 """WPS and ACK M3 missing R-Nonce"""
7373 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7374 logger.debug("Send NACK to STA")
7375 msg, attrs = build_ack(eap_id, e_nonce, None)
7376 send_wsc_msg(dev[0], bssid, msg)
7377 dev[0].request("WPS_CANCEL")
7378 dev[0].wait_disconnected()
7379 dev[0].flush_scan_cache()
7380
7381def test_wps_ext_proto_ack_m3_r_nonce_mismatch(dev, apdev):
7382 """WPS and ACK M3 R-Nonce mismatch"""
7383 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7384 logger.debug("Send NACK to STA")
7385 msg, attrs = build_ack(eap_id, e_nonce, 16*'\x00')
7386 send_wsc_msg(dev[0], bssid, msg)
7387 dev[0].request("WPS_CANCEL")
7388 dev[0].wait_disconnected()
7389 dev[0].flush_scan_cache()
7390
7391def test_wps_ext_proto_ack_m3_no_msg_type(dev, apdev):
7392 """WPS and ACK M3 no Message Type"""
7393 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7394 logger.debug("Send NACK to STA")
7395 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=None)
7396 send_wsc_msg(dev[0], bssid, msg)
7397 dev[0].request("WPS_CANCEL")
7398 dev[0].wait_disconnected()
7399 dev[0].flush_scan_cache()
7400
7401def test_wps_ext_proto_ack_m3_invalid_msg_type(dev, apdev):
7402 """WPS and ACK M3 invalid Message Type"""
7403 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7404 logger.debug("Send NACK to STA")
7405 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=123)
7406 send_wsc_msg(dev[0], bssid, msg)
7407 dev[0].request("WPS_CANCEL")
7408 dev[0].wait_disconnected()
7409 dev[0].flush_scan_cache()
7410
7411def test_wps_ext_proto_ack_m3_invalid_attr(dev, apdev):
7412 """WPS and ACK M3 invalid attribute"""
7413 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7414 logger.debug("Send ACK to STA")
15dfcb69 7415 attrs = b'\x10\x10\x00'
7511ead0
JM
7416 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_ACK)
7417 send_wsc_msg(dev[0], bssid, msg)
7418 dev[0].request("WPS_CANCEL")
7419 dev[0].wait_disconnected()
7420 dev[0].flush_scan_cache()
7421
7422def test_wps_ext_proto_ack_m3(dev, apdev):
7423 """WPS and ACK M3"""
7424 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7425 logger.debug("Send ACK to STA")
7426 msg, attrs = build_ack(eap_id, e_nonce, r_nonce)
7427 send_wsc_msg(dev[0], bssid, msg)
7428 dev[0].request("WPS_CANCEL")
7429 dev[0].wait_disconnected()
7430 dev[0].flush_scan_cache()
7431
7432def wps_to_m3_helper(dev, apdev):
7433 pin = "12345670"
fab49f61 7434 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
7435 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7436 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7437 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7438
7439 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
7440 uuid_r = 16*b'\x33'
7441 r_nonce = 16*b'\x44'
7511ead0
JM
7442 own_private, e_pk = wsc_dh_init()
7443
7444 logger.debug("Receive M1 from STA")
7445 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7446 eap_id = (msg['eap_identifier'] + 1) % 256
7447
fab49f61
JM
7448 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7449 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7450 r_nonce)
7451 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7452 m1_attrs[ATTR_PUBLIC_KEY],
7453 e_pk)
7511ead0
JM
7454
7455 logger.debug("Send M2 to STA")
7456 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7457 m1_attrs[ATTR_ENROLLEE_NONCE],
7458 r_nonce, uuid_r, e_pk)
7459 send_wsc_msg(dev[0], bssid, m2)
7460 eap_id = (eap_id + 1) % 256
7461
7462 logger.debug("Receive M3 from STA")
7463 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7464 return eap_id, m1_attrs, r_nonce, bssid, r_hash1, r_hash2, r_s1, r_s2, raw_m3_attrs, authkey, keywrapkey
7465
7466def wps_to_m3(dev, apdev):
7467 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)
7468 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s1, raw_m3_attrs, authkey, keywrapkey
7469
7470def wps_to_m5(dev, apdev):
7471 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)
7472
7473 logger.debug("Send M4 to STA")
7474 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7475 attrs += build_attr_msg_type(WPS_M4)
7476 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7477 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7478 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7479 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7480 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7481 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7482 raw_m4_attrs = attrs
7483 m4 = build_eap_wsc(1, eap_id, attrs)
7484 send_wsc_msg(dev[0], bssid, m4)
7485 eap_id = (eap_id + 1) % 256
7486
7487 logger.debug("Receive M5 from STA")
7488 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7489
7490 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s2, raw_m5_attrs, authkey, keywrapkey
7491
7492def test_wps_ext_proto_m4_missing_r_hash1(dev, apdev):
7493 """WPS and no R-Hash1 in M4"""
7494 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7495
7496 logger.debug("Send M4 to STA")
7497 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7498 attrs += build_attr_msg_type(WPS_M4)
7499 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7500 #attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7501 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7502 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7503 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7504 attrs += build_attr_authenticator(authkey, m3, attrs)
7505 m4 = build_eap_wsc(1, eap_id, attrs)
7506 send_wsc_msg(dev[0], bssid, m4)
7507 eap_id = (eap_id + 1) % 256
7508
7509 logger.debug("Receive M5 (NACK) from STA")
7510 msg = get_wsc_msg(dev[0])
7511 if msg['wsc_opcode'] != WSC_NACK:
7512 raise Exception("Unexpected message - expected WSC_Nack")
7513
7514 dev[0].request("WPS_CANCEL")
7515 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7516 dev[0].wait_disconnected()
7517
7518def test_wps_ext_proto_m4_missing_r_hash2(dev, apdev):
7519 """WPS and no R-Hash2 in M4"""
7520 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7521
7522 logger.debug("Send M4 to STA")
7523 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7524 attrs += build_attr_msg_type(WPS_M4)
7525 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7526 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7527 #attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7528 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7529 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7530 attrs += build_attr_authenticator(authkey, m3, attrs)
7531 m4 = build_eap_wsc(1, eap_id, attrs)
7532 send_wsc_msg(dev[0], bssid, m4)
7533 eap_id = (eap_id + 1) % 256
7534
7535 logger.debug("Receive M5 (NACK) from STA")
7536 msg = get_wsc_msg(dev[0])
7537 if msg['wsc_opcode'] != WSC_NACK:
7538 raise Exception("Unexpected message - expected WSC_Nack")
7539
7540 dev[0].request("WPS_CANCEL")
7541 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7542 dev[0].wait_disconnected()
7543
7544def test_wps_ext_proto_m4_missing_r_snonce1(dev, apdev):
7545 """WPS and no R-SNonce1 in M4"""
7546 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7547
7548 logger.debug("Send M4 to STA")
7549 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7550 attrs += build_attr_msg_type(WPS_M4)
7551 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7552 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7553 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7554 #data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
15dfcb69 7555 data = b''
7511ead0
JM
7556 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7557 attrs += build_attr_authenticator(authkey, m3, attrs)
7558 m4 = build_eap_wsc(1, eap_id, attrs)
7559 send_wsc_msg(dev[0], bssid, m4)
7560 eap_id = (eap_id + 1) % 256
7561
7562 logger.debug("Receive M5 (NACK) from STA")
7563 msg = get_wsc_msg(dev[0])
7564 if msg['wsc_opcode'] != WSC_NACK:
7565 raise Exception("Unexpected message - expected WSC_Nack")
7566
7567 dev[0].request("WPS_CANCEL")
7568 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7569 dev[0].wait_disconnected()
7570
7571def test_wps_ext_proto_m4_invalid_pad_string(dev, apdev):
7572 """WPS and invalid pad string in M4"""
7573 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7574
7575 logger.debug("Send M4 to STA")
7576 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7577 attrs += build_attr_msg_type(WPS_M4)
7578 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7579 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7580 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7581 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7582
7583 m = hmac.new(authkey, data, hashlib.sha256)
7584 kwa = m.digest()[0:8]
7585 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
15dfcb69 7586 iv = 16*b'\x99'
7511ead0
JM
7587 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7588 pad_len = 16 - len(data) % 16
7589 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', pad_len - 1)
7590 data += ps
7591 wrapped = aes.encrypt(data)
7592 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7593
7594 attrs += build_attr_authenticator(authkey, m3, attrs)
7595 m4 = build_eap_wsc(1, eap_id, attrs)
7596 send_wsc_msg(dev[0], bssid, m4)
7597 eap_id = (eap_id + 1) % 256
7598
7599 logger.debug("Receive M5 (NACK) from STA")
7600 msg = get_wsc_msg(dev[0])
7601 if msg['wsc_opcode'] != WSC_NACK:
7602 raise Exception("Unexpected message - expected WSC_Nack")
7603
7604 dev[0].request("WPS_CANCEL")
7605 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7606 dev[0].wait_disconnected()
7607
7608def test_wps_ext_proto_m4_invalid_pad_value(dev, apdev):
7609 """WPS and invalid pad value in M4"""
7610 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7611
7612 logger.debug("Send M4 to STA")
7613 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7614 attrs += build_attr_msg_type(WPS_M4)
7615 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7616 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7617 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7618 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7619
7620 m = hmac.new(authkey, data, hashlib.sha256)
7621 kwa = m.digest()[0:8]
7622 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
15dfcb69 7623 iv = 16*b'\x99'
7511ead0
JM
7624 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7625 pad_len = 16 - len(data) % 16
7626 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', 255)
7627 data += ps
7628 wrapped = aes.encrypt(data)
7629 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7630
7631 attrs += build_attr_authenticator(authkey, m3, 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 (NACK) from STA")
7637 msg = get_wsc_msg(dev[0])
7638 if msg['wsc_opcode'] != WSC_NACK:
7639 raise Exception("Unexpected message - expected WSC_Nack")
7640
7641 dev[0].request("WPS_CANCEL")
7642 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7643 dev[0].wait_disconnected()
7644
7645def test_wps_ext_proto_m4_no_encr_settings(dev, apdev):
7646 """WPS and no Encr Settings in M4"""
7647 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7648
7649 logger.debug("Send M4 to STA")
7650 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7651 attrs += build_attr_msg_type(WPS_M4)
7652 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7653 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7654 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7655 attrs += build_attr_authenticator(authkey, m3, attrs)
7656 m4 = build_eap_wsc(1, eap_id, attrs)
7657 send_wsc_msg(dev[0], bssid, m4)
7658 eap_id = (eap_id + 1) % 256
7659
7660 logger.debug("Receive M5 (NACK) from STA")
7661 msg = get_wsc_msg(dev[0])
7662 if msg['wsc_opcode'] != WSC_NACK:
7663 raise Exception("Unexpected message - expected WSC_Nack")
7664
7665 dev[0].request("WPS_CANCEL")
7666 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7667 dev[0].wait_disconnected()
7668
7669def test_wps_ext_proto_m6_missing_r_snonce2(dev, apdev):
7670 """WPS and no R-SNonce2 in M6"""
7671 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7672
7673 logger.debug("Send M6 to STA")
7674 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7675 attrs += build_attr_msg_type(WPS_M6)
7676 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7677 #data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
15dfcb69 7678 data = b''
7511ead0
JM
7679 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7680 attrs += build_attr_authenticator(authkey, m5, attrs)
7681 m6 = build_eap_wsc(1, eap_id, attrs)
7682 send_wsc_msg(dev[0], bssid, m6)
7683 eap_id = (eap_id + 1) % 256
7684
7685 logger.debug("Receive M7 (NACK) from STA")
7686 msg = get_wsc_msg(dev[0])
7687 if msg['wsc_opcode'] != WSC_NACK:
7688 raise Exception("Unexpected message - expected WSC_Nack")
7689
7690 dev[0].request("WPS_CANCEL")
7691 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7692 dev[0].wait_disconnected()
7693
7694def test_wps_ext_proto_m6_no_encr_settings(dev, apdev):
7695 """WPS and no Encr Settings in M6"""
7696 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7697
7698 logger.debug("Send M6 to STA")
7699 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7700 attrs += build_attr_msg_type(WPS_M6)
7701 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7702 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7703 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7704 attrs += build_attr_authenticator(authkey, m5, attrs)
7705 m6 = build_eap_wsc(1, eap_id, attrs)
7706 send_wsc_msg(dev[0], bssid, m6)
7707 eap_id = (eap_id + 1) % 256
7708
7709 logger.debug("Receive M7 (NACK) from STA")
7710 msg = get_wsc_msg(dev[0])
7711 if msg['wsc_opcode'] != WSC_NACK:
7712 raise Exception("Unexpected message - expected WSC_Nack")
7713
7714 dev[0].request("WPS_CANCEL")
7715 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7716 dev[0].wait_disconnected()
7717
7718def test_wps_ext_proto_m8_no_encr_settings(dev, apdev):
7719 """WPS and no Encr Settings in M6"""
7720 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7721
7722 logger.debug("Send M6 to STA")
7723 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7724 attrs += build_attr_msg_type(WPS_M6)
7725 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7726 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7727 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7728 attrs += build_attr_authenticator(authkey, m5, attrs)
7729 raw_m6_attrs = attrs
7730 m6 = build_eap_wsc(1, eap_id, attrs)
7731 send_wsc_msg(dev[0], bssid, m6)
7732 eap_id = (eap_id + 1) % 256
7733
7734 logger.debug("Receive M7 from STA")
7735 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
7736
7737 logger.debug("Send M8 to STA")
7738 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7739 attrs += build_attr_msg_type(WPS_M8)
7740 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7741 #attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
7742 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7743 raw_m8_attrs = attrs
7744 m8 = build_eap_wsc(1, eap_id, attrs)
7745 send_wsc_msg(dev[0], bssid, m8)
7746
7747 logger.debug("Receive WSC_Done (NACK) from STA")
7748 msg = get_wsc_msg(dev[0])
7749 if msg['wsc_opcode'] != WSC_NACK:
7750 raise Exception("Unexpected message - expected WSC_Nack")
7751
7752 dev[0].request("WPS_CANCEL")
7753 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7754 dev[0].wait_disconnected()
7755
7756def wps_start_ext_reg(apdev, dev):
7757 addr = dev.own_addr()
7758 bssid = apdev['bssid']
7759 ssid = "test-wps-conf"
7760 appin = "12345670"
fab49f61
JM
7761 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
7762 "wpa_passphrase": "12345678", "wpa": "2",
7763 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
7764 "ap_pin": appin}
afc26df2 7765 hapd = hostapd.add_ap(apdev, params)
7511ead0
JM
7766
7767 dev.scan_for_bss(bssid, freq="2412")
7768 hapd.request("SET ext_eapol_frame_io 1")
7769 dev.request("SET ext_eapol_frame_io 1")
7770
7771 dev.request("WPS_REG " + bssid + " " + appin)
7772
fab49f61 7773 return addr, bssid, hapd
7511ead0
JM
7774
7775def wps_run_ap_settings_proto(dev, apdev, ap_settings, success):
fab49f61 7776 addr, bssid, hapd = wps_start_ext_reg(apdev[0], dev[0])
7511ead0
JM
7777 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7778 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7779
7780 logger.debug("Receive M1 from AP")
7781 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7782 mac_addr = m1_attrs[ATTR_MAC_ADDR]
7783 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7784 e_pk = m1_attrs[ATTR_PUBLIC_KEY]
7785
7786 appin = '12345670'
15dfcb69
MH
7787 uuid_r = 16*b'\x33'
7788 r_nonce = 16*b'\x44'
7511ead0 7789 own_private, r_pk = wsc_dh_init()
fab49f61
JM
7790 authkey, keywrapkey = wsc_dh_kdf(e_pk, own_private, mac_addr, e_nonce,
7791 r_nonce)
7792 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, appin, e_pk, r_pk)
7511ead0
JM
7793
7794 logger.debug("Send M2 to AP")
7795 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, msg['eap_identifier'],
7796 e_nonce, r_nonce, uuid_r, r_pk, eap_code=2)
7797 send_wsc_msg(hapd, addr, m2)
7798
7799 logger.debug("Receive M3 from AP")
7800 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M3)
7801
7802 logger.debug("Send M4 to AP")
7803 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7804 attrs += build_attr_msg_type(WPS_M4)
7805 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7806 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7807 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7808 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7809 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7810 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7811 raw_m4_attrs = attrs
7812 m4 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7813 send_wsc_msg(hapd, addr, m4)
7814
7815 logger.debug("Receive M5 from AP")
7816 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M5)
7817
7818 logger.debug("Send M6 to STA")
7819 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7820 attrs += build_attr_msg_type(WPS_M6)
7821 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7822 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7823 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7824 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
7825 raw_m6_attrs = attrs
7826 m6 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7827 send_wsc_msg(hapd, addr, m6)
7828
7829 logger.debug("Receive M7 from AP")
7830 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M7)
7831
7832 logger.debug("Send M8 to STA")
7833 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7834 attrs += build_attr_msg_type(WPS_M8)
7835 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7836 if ap_settings:
7837 attrs += build_attr_encr_settings(authkey, keywrapkey, ap_settings)
7838 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7839 raw_m8_attrs = attrs
7840 m8 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7841 send_wsc_msg(hapd, addr, m8)
7842
7843 if success:
7844 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
7845 if ev is None:
7846 raise Exception("New AP settings not reported")
7847 logger.debug("Receive WSC_Done from AP")
7848 msg = get_wsc_msg(hapd)
7849 if msg['wsc_opcode'] != WSC_Done:
7850 raise Exception("Unexpected message - expected WSC_Done")
7851
7852 logger.debug("Send WSC_ACK to AP")
fab49f61
JM
7853 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
7854 eap_code=2)
7511ead0
JM
7855 send_wsc_msg(hapd, addr, ack)
7856 dev[0].wait_disconnected()
7857 else:
7858 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
7859 if ev is None:
7860 raise Exception("WPS failure not reported")
7861 logger.debug("Receive WSC_NACK from AP")
7862 msg = get_wsc_msg(hapd)
7863 if msg['wsc_opcode'] != WSC_NACK:
7864 raise Exception("Unexpected message - expected WSC_NACK")
7865
7866 logger.debug("Send WSC_NACK to AP")
fab49f61
JM
7867 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7868 eap_code=2)
7511ead0
JM
7869 send_wsc_msg(hapd, addr, nack)
7870 dev[0].wait_disconnected()
7871
7872def test_wps_ext_ap_settings_success(dev, apdev):
7873 """WPS and AP Settings: success"""
7874 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7875 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7876 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7877 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7878 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7879 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7880 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7881
9fd6804d 7882@remote_compatible
7511ead0
JM
7883def test_wps_ext_ap_settings_missing(dev, apdev):
7884 """WPS and AP Settings: missing"""
7885 wps_run_ap_settings_proto(dev, apdev, None, False)
7886
9fd6804d 7887@remote_compatible
7511ead0
JM
7888def test_wps_ext_ap_settings_mac_addr_mismatch(dev, apdev):
7889 """WPS and AP Settings: MAC Address mismatch"""
7890 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7891 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7892 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7893 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7894 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7895 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, '\x00\x00\x00\x00\x00\x00')
7896 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7897
9fd6804d 7898@remote_compatible
7511ead0
JM
7899def test_wps_ext_ap_settings_mac_addr_missing(dev, apdev):
7900 """WPS and AP Settings: missing MAC Address"""
7901 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7902 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7903 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7904 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7905 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7906 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7907
9fd6804d 7908@remote_compatible
7511ead0
JM
7909def test_wps_ext_ap_settings_reject_encr_type(dev, apdev):
7910 """WPS and AP Settings: reject Encr Type"""
7911 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7912 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7913 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7914 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x00')
7915 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7916 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7917 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7918
9fd6804d 7919@remote_compatible
7511ead0
JM
7920def test_wps_ext_ap_settings_m2d(dev, apdev):
7921 """WPS and AP Settings: M2D"""
fab49f61 7922 addr, bssid, hapd = wps_start_ext_reg(apdev[0], dev[0])
7511ead0
JM
7923 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7924 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7925
7926 logger.debug("Receive M1 from AP")
7927 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7928 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7929
7930 r_nonce = 16*'\x44'
7931 uuid_r = 16*'\x33'
7932
7933 logger.debug("Send M2D to AP")
7934 m2d, raw_m2d_attrs = build_m2d(raw_m1_attrs, msg['eap_identifier'],
7935 e_nonce, r_nonce, uuid_r,
7936 dev_pw_id='\x00\x00', eap_code=2)
7937 send_wsc_msg(hapd, addr, m2d)
7938
7939 ev = hapd.wait_event(["WPS-M2D"], timeout=5)
7940 if ev is None:
7941 raise Exception("M2D not reported")
7942
7943 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7944
7945def wps_wait_ap_nack(hapd, dev, e_nonce, r_nonce):
7946 logger.debug("Receive WSC_NACK from AP")
7947 msg = get_wsc_msg(hapd)
7948 if msg['wsc_opcode'] != WSC_NACK:
7949 raise Exception("Unexpected message - expected WSC_NACK")
7950
7951 logger.debug("Send WSC_NACK to AP")
fab49f61
JM
7952 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7953 eap_code=2)
7511ead0
JM
7954 send_wsc_msg(hapd, dev.own_addr(), nack)
7955 dev.wait_disconnected()
7956
9fd6804d 7957@remote_compatible
7511ead0
JM
7958def test_wps_ext_m3_missing_e_hash1(dev, apdev):
7959 """WPS proto: M3 missing E-Hash1"""
7960 pin = "12345670"
fab49f61 7961 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
7962 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7963 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7964
7965 logger.debug("Receive WSC/Start from AP")
7966 msg = get_wsc_msg(hapd)
7967 if msg['wsc_opcode'] != WSC_Start:
7968 raise Exception("Unexpected Op-Code for WSC/Start")
7969
7970 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
7971 uuid_e = 16*b'\x11'
7972 e_nonce = 16*b'\x22'
7511ead0
JM
7973 own_private, e_pk = wsc_dh_init()
7974
7975 logger.debug("Send M1 to AP")
7976 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7977 e_nonce, e_pk)
7978 send_wsc_msg(hapd, addr, m1)
7979
7980 logger.debug("Receive M2 from AP")
7981 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7982 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7983 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7984
fab49f61
JM
7985 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7986 r_nonce)
7987 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
7988
7989 logger.debug("Send M3 to AP")
7990 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7991 attrs += build_attr_msg_type(WPS_M3)
7992 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7993 #attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7994 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7995 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7996 raw_m3_attrs = attrs
7997 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7998 send_wsc_msg(hapd, addr, m3)
7999
8000 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8001
9fd6804d 8002@remote_compatible
7511ead0
JM
8003def test_wps_ext_m3_missing_e_hash2(dev, apdev):
8004 """WPS proto: M3 missing E-Hash2"""
8005 pin = "12345670"
fab49f61 8006 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8007 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8008 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8009
8010 logger.debug("Receive WSC/Start from AP")
8011 msg = get_wsc_msg(hapd)
8012 if msg['wsc_opcode'] != WSC_Start:
8013 raise Exception("Unexpected Op-Code for WSC/Start")
8014
8015 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8016 uuid_e = 16*b'\x11'
8017 e_nonce = 16*b'\x22'
7511ead0
JM
8018 own_private, e_pk = wsc_dh_init()
8019
8020 logger.debug("Send M1 to AP")
8021 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8022 e_nonce, e_pk)
8023 send_wsc_msg(hapd, addr, m1)
8024
8025 logger.debug("Receive M2 from AP")
8026 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8027 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8028 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8029
fab49f61
JM
8030 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8031 r_nonce)
8032 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8033
8034 logger.debug("Send M3 to AP")
8035 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8036 attrs += build_attr_msg_type(WPS_M3)
8037 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8038 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8039 #attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8040 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8041 raw_m3_attrs = attrs
8042 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8043 send_wsc_msg(hapd, addr, m3)
8044
8045 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8046
9fd6804d 8047@remote_compatible
7511ead0
JM
8048def test_wps_ext_m5_missing_e_snonce1(dev, apdev):
8049 """WPS proto: M5 missing E-SNonce1"""
8050 pin = "12345670"
fab49f61 8051 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8052 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8053 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8054
8055 logger.debug("Receive WSC/Start from AP")
8056 msg = get_wsc_msg(hapd)
8057 if msg['wsc_opcode'] != WSC_Start:
8058 raise Exception("Unexpected Op-Code for WSC/Start")
8059
8060 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8061 uuid_e = 16*b'\x11'
8062 e_nonce = 16*b'\x22'
7511ead0
JM
8063 own_private, e_pk = wsc_dh_init()
8064
8065 logger.debug("Send M1 to AP")
8066 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8067 e_nonce, e_pk)
8068 send_wsc_msg(hapd, addr, m1)
8069
8070 logger.debug("Receive M2 from AP")
8071 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8072 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8073 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8074
fab49f61
JM
8075 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8076 r_nonce)
8077 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8078
8079 logger.debug("Send M3 to AP")
8080 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8081 attrs += build_attr_msg_type(WPS_M3)
8082 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8083 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8084 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8085 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8086 raw_m3_attrs = attrs
8087 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8088 send_wsc_msg(hapd, addr, m3)
8089
8090 logger.debug("Receive M4 from AP")
8091 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8092
8093 logger.debug("Send M5 to AP")
8094 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8095 attrs += build_attr_msg_type(WPS_M5)
8096 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8097 #data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
15dfcb69 8098 data = b''
7511ead0
JM
8099 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8100 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8101 raw_m5_attrs = attrs
8102 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8103 send_wsc_msg(hapd, addr, m5)
8104
8105 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8106
9fd6804d 8107@remote_compatible
7511ead0
JM
8108def test_wps_ext_m5_e_snonce1_mismatch(dev, apdev):
8109 """WPS proto: M5 E-SNonce1 mismatch"""
8110 pin = "12345670"
fab49f61 8111 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8112 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8113 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8114
8115 logger.debug("Receive WSC/Start from AP")
8116 msg = get_wsc_msg(hapd)
8117 if msg['wsc_opcode'] != WSC_Start:
8118 raise Exception("Unexpected Op-Code for WSC/Start")
8119
8120 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8121 uuid_e = 16*b'\x11'
8122 e_nonce = 16*b'\x22'
7511ead0
JM
8123 own_private, e_pk = wsc_dh_init()
8124
8125 logger.debug("Send M1 to AP")
8126 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8127 e_nonce, e_pk)
8128 send_wsc_msg(hapd, addr, m1)
8129
8130 logger.debug("Receive M2 from AP")
8131 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8132 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8133 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8134
fab49f61
JM
8135 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8136 r_nonce)
8137 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8138
8139 logger.debug("Send M3 to AP")
8140 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8141 attrs += build_attr_msg_type(WPS_M3)
8142 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8143 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8144 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8145 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8146 raw_m3_attrs = attrs
8147 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8148 send_wsc_msg(hapd, addr, m3)
8149
8150 logger.debug("Receive M4 from AP")
8151 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8152
8153 logger.debug("Send M5 to AP")
8154 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8155 attrs += build_attr_msg_type(WPS_M5)
8156 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8157 data = build_wsc_attr(ATTR_E_SNONCE1, 16*'\x00')
8158 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8159 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8160 raw_m5_attrs = attrs
8161 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8162 send_wsc_msg(hapd, addr, m5)
8163
8164 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8165
8166def test_wps_ext_m7_missing_e_snonce2(dev, apdev):
8167 """WPS proto: M7 missing E-SNonce2"""
8168 pin = "12345670"
fab49f61 8169 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8170 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8171 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8172
8173 logger.debug("Receive WSC/Start from AP")
8174 msg = get_wsc_msg(hapd)
8175 if msg['wsc_opcode'] != WSC_Start:
8176 raise Exception("Unexpected Op-Code for WSC/Start")
8177
8178 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8179 uuid_e = 16*b'\x11'
8180 e_nonce = 16*b'\x22'
7511ead0
JM
8181 own_private, e_pk = wsc_dh_init()
8182
8183 logger.debug("Send M1 to AP")
8184 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8185 e_nonce, e_pk)
8186 send_wsc_msg(hapd, addr, m1)
8187
8188 logger.debug("Receive M2 from AP")
8189 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8190 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8191 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8192
fab49f61
JM
8193 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8194 r_nonce)
8195 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8196
8197 logger.debug("Send M3 to AP")
8198 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8199 attrs += build_attr_msg_type(WPS_M3)
8200 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8201 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8202 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8203 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8204 raw_m3_attrs = attrs
8205 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8206 send_wsc_msg(hapd, addr, m3)
8207
8208 logger.debug("Receive M4 from AP")
8209 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8210
8211 logger.debug("Send M5 to AP")
8212 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8213 attrs += build_attr_msg_type(WPS_M5)
8214 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8215 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8216 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8217 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8218 raw_m5_attrs = attrs
8219 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8220 send_wsc_msg(hapd, addr, m5)
8221
8222 logger.debug("Receive M6 from AP")
8223 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8224
8225 logger.debug("Send M7 to AP")
8226 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8227 attrs += build_attr_msg_type(WPS_M7)
8228 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8229 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
15dfcb69 8230 data = b''
7511ead0
JM
8231 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8232 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8233 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8234 raw_m7_attrs = attrs
8235 send_wsc_msg(hapd, addr, m7)
8236
8237 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8238
9fd6804d 8239@remote_compatible
7511ead0
JM
8240def test_wps_ext_m7_e_snonce2_mismatch(dev, apdev):
8241 """WPS proto: M7 E-SNonce2 mismatch"""
8242 pin = "12345670"
fab49f61 8243 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8244 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8245 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8246
8247 logger.debug("Receive WSC/Start from AP")
8248 msg = get_wsc_msg(hapd)
8249 if msg['wsc_opcode'] != WSC_Start:
8250 raise Exception("Unexpected Op-Code for WSC/Start")
8251
8252 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8253 uuid_e = 16*b'\x11'
8254 e_nonce = 16*b'\x22'
7511ead0
JM
8255 own_private, e_pk = wsc_dh_init()
8256
8257 logger.debug("Send M1 to AP")
8258 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8259 e_nonce, e_pk)
8260 send_wsc_msg(hapd, addr, m1)
8261
8262 logger.debug("Receive M2 from AP")
8263 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8264 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8265 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8266
fab49f61
JM
8267 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8268 r_nonce)
8269 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8270
8271 logger.debug("Send M3 to AP")
8272 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8273 attrs += build_attr_msg_type(WPS_M3)
8274 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8275 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8276 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8277 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8278 raw_m3_attrs = attrs
8279 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8280 send_wsc_msg(hapd, addr, m3)
8281
8282 logger.debug("Receive M4 from AP")
8283 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8284
8285 logger.debug("Send M5 to AP")
8286 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8287 attrs += build_attr_msg_type(WPS_M5)
8288 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8289 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8290 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8291 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8292 raw_m5_attrs = attrs
8293 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8294 send_wsc_msg(hapd, addr, m5)
8295
8296 logger.debug("Receive M6 from AP")
8297 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8298
8299 logger.debug("Send M7 to AP")
8300 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8301 attrs += build_attr_msg_type(WPS_M7)
8302 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8303 data = build_wsc_attr(ATTR_E_SNONCE2, 16*'\x00')
8304 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8305 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8306 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8307 raw_m7_attrs = attrs
8308 send_wsc_msg(hapd, addr, m7)
8309
8310 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8311
9fd6804d 8312@remote_compatible
7511ead0
JM
8313def test_wps_ext_m1_pubkey_oom(dev, apdev):
8314 """WPS proto: M1 PubKey OOM"""
8315 pin = "12345670"
fab49f61 8316 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8317 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8318 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8319
8320 logger.debug("Receive WSC/Start from AP")
8321 msg = get_wsc_msg(hapd)
8322 if msg['wsc_opcode'] != WSC_Start:
8323 raise Exception("Unexpected Op-Code for WSC/Start")
8324
8325 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8326 uuid_e = 16*'\x11'
8327 e_nonce = 16*'\x22'
8328 own_private, e_pk = wsc_dh_init()
8329
8330 logger.debug("Send M1 to AP")
8331 with alloc_fail(hapd, 1, "wpabuf_alloc_copy;wps_process_pubkey"):
8332 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8333 e_nonce, e_pk)
8334 send_wsc_msg(hapd, addr, m1)
8335 wps_wait_eap_failure(hapd, dev[0])
8336
8337def wps_wait_eap_failure(hapd, dev):
8338 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
8339 if ev is None:
8340 raise Exception("EAP-Failure not reported")
8341 dev.wait_disconnected()
8342
9fd6804d 8343@remote_compatible
7511ead0
JM
8344def test_wps_ext_m3_m1(dev, apdev):
8345 """WPS proto: M3 replaced with M1"""
8346 pin = "12345670"
fab49f61 8347 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8348 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8349 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8350
8351 logger.debug("Receive WSC/Start from AP")
8352 msg = get_wsc_msg(hapd)
8353 if msg['wsc_opcode'] != WSC_Start:
8354 raise Exception("Unexpected Op-Code for WSC/Start")
8355
8356 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8357 uuid_e = 16*b'\x11'
8358 e_nonce = 16*b'\x22'
7511ead0
JM
8359 own_private, e_pk = wsc_dh_init()
8360
8361 logger.debug("Send M1 to AP")
8362 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8363 e_nonce, e_pk)
8364 send_wsc_msg(hapd, addr, m1)
8365
8366 logger.debug("Receive M2 from AP")
8367 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8368 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8369 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8370
fab49f61
JM
8371 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8372 r_nonce)
8373 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8374
8375 logger.debug("Send M3(M1) to AP")
8376 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8377 attrs += build_attr_msg_type(WPS_M1)
8378 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8379 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8380 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8381 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8382 raw_m3_attrs = attrs
8383 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8384 send_wsc_msg(hapd, addr, m3)
8385
8386 wps_wait_eap_failure(hapd, dev[0])
8387
9fd6804d 8388@remote_compatible
7511ead0
JM
8389def test_wps_ext_m5_m3(dev, apdev):
8390 """WPS proto: M5 replaced with M3"""
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(M3) to AP")
8435 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8436 attrs += build_attr_msg_type(WPS_M3)
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 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8446
9fd6804d 8447@remote_compatible
7511ead0
JM
8448def test_wps_ext_m3_m2(dev, apdev):
8449 """WPS proto: M3 replaced with M2"""
8450 pin = "12345670"
fab49f61 8451 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8452 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8453 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8454
8455 logger.debug("Receive WSC/Start from AP")
8456 msg = get_wsc_msg(hapd)
8457 if msg['wsc_opcode'] != WSC_Start:
8458 raise Exception("Unexpected Op-Code for WSC/Start")
8459
8460 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8461 uuid_e = 16*b'\x11'
8462 e_nonce = 16*b'\x22'
7511ead0
JM
8463 own_private, e_pk = wsc_dh_init()
8464
8465 logger.debug("Send M1 to AP")
8466 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8467 e_nonce, e_pk)
8468 send_wsc_msg(hapd, addr, m1)
8469
8470 logger.debug("Receive M2 from AP")
8471 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8472 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8473 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8474
fab49f61
JM
8475 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8476 r_nonce)
8477 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8478
8479 logger.debug("Send M3(M2) to AP")
8480 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8481 attrs += build_attr_msg_type(WPS_M2)
8482 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8483 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8484 raw_m3_attrs = attrs
8485 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8486 send_wsc_msg(hapd, addr, m3)
8487
8488 wps_wait_eap_failure(hapd, dev[0])
8489
9fd6804d 8490@remote_compatible
7511ead0
JM
8491def test_wps_ext_m3_m5(dev, apdev):
8492 """WPS proto: M3 replaced with M5"""
8493 pin = "12345670"
fab49f61 8494 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8495 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8496 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8497
8498 logger.debug("Receive WSC/Start from AP")
8499 msg = get_wsc_msg(hapd)
8500 if msg['wsc_opcode'] != WSC_Start:
8501 raise Exception("Unexpected Op-Code for WSC/Start")
8502
8503 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8504 uuid_e = 16*b'\x11'
8505 e_nonce = 16*b'\x22'
7511ead0
JM
8506 own_private, e_pk = wsc_dh_init()
8507
8508 logger.debug("Send M1 to AP")
8509 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8510 e_nonce, e_pk)
8511 send_wsc_msg(hapd, addr, m1)
8512
8513 logger.debug("Receive M2 from AP")
8514 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8515 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8516 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8517
fab49f61
JM
8518 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8519 r_nonce)
8520 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8521
8522 logger.debug("Send M3(M5) to AP")
8523 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8524 attrs += build_attr_msg_type(WPS_M5)
8525 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8526 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8527 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8528 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8529 raw_m3_attrs = attrs
8530 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8531 send_wsc_msg(hapd, addr, m3)
8532
8533 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8534
9fd6804d 8535@remote_compatible
7511ead0
JM
8536def test_wps_ext_m3_m7(dev, apdev):
8537 """WPS proto: M3 replaced with M7"""
8538 pin = "12345670"
fab49f61 8539 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8540 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8541 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8542
8543 logger.debug("Receive WSC/Start from AP")
8544 msg = get_wsc_msg(hapd)
8545 if msg['wsc_opcode'] != WSC_Start:
8546 raise Exception("Unexpected Op-Code for WSC/Start")
8547
8548 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8549 uuid_e = 16*b'\x11'
8550 e_nonce = 16*b'\x22'
7511ead0
JM
8551 own_private, e_pk = wsc_dh_init()
8552
8553 logger.debug("Send M1 to AP")
8554 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8555 e_nonce, e_pk)
8556 send_wsc_msg(hapd, addr, m1)
8557
8558 logger.debug("Receive M2 from AP")
8559 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8560 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8561 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8562
fab49f61
JM
8563 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8564 r_nonce)
8565 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8566
8567 logger.debug("Send M3(M7) to AP")
8568 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8569 attrs += build_attr_msg_type(WPS_M7)
8570 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8571 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8572 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8573 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8574 raw_m3_attrs = attrs
8575 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8576 send_wsc_msg(hapd, addr, m3)
8577
8578 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8579
9fd6804d 8580@remote_compatible
7511ead0
JM
8581def test_wps_ext_m3_done(dev, apdev):
8582 """WPS proto: M3 replaced with WSC_Done"""
8583 pin = "12345670"
fab49f61 8584 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8585 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8586 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8587
8588 logger.debug("Receive WSC/Start from AP")
8589 msg = get_wsc_msg(hapd)
8590 if msg['wsc_opcode'] != WSC_Start:
8591 raise Exception("Unexpected Op-Code for WSC/Start")
8592
8593 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8594 uuid_e = 16*b'\x11'
8595 e_nonce = 16*b'\x22'
7511ead0
JM
8596 own_private, e_pk = wsc_dh_init()
8597
8598 logger.debug("Send M1 to AP")
8599 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8600 e_nonce, e_pk)
8601 send_wsc_msg(hapd, addr, m1)
8602
8603 logger.debug("Receive M2 from AP")
8604 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8605 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8606 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8607
fab49f61
JM
8608 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8609 r_nonce)
8610 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8611
8612 logger.debug("Send M3(WSC_Done) to AP")
8613 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8614 attrs += build_attr_msg_type(WPS_WSC_DONE)
8615 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8616 raw_m3_attrs = attrs
8617 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8618 send_wsc_msg(hapd, addr, m3)
8619
8620 wps_wait_eap_failure(hapd, dev[0])
8621
9fd6804d 8622@remote_compatible
7511ead0
JM
8623def test_wps_ext_m2_nack_invalid(dev, apdev):
8624 """WPS proto: M2 followed by invalid NACK"""
8625 pin = "12345670"
fab49f61 8626 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8627 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8628 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8629
8630 logger.debug("Receive WSC/Start from AP")
8631 msg = get_wsc_msg(hapd)
8632 if msg['wsc_opcode'] != WSC_Start:
8633 raise Exception("Unexpected Op-Code for WSC/Start")
8634
8635 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8636 uuid_e = 16*b'\x11'
8637 e_nonce = 16*b'\x22'
7511ead0
JM
8638 own_private, e_pk = wsc_dh_init()
8639
8640 logger.debug("Send M1 to AP")
8641 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8642 e_nonce, e_pk)
8643 send_wsc_msg(hapd, addr, m1)
8644
8645 logger.debug("Receive M2 from AP")
8646 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8647 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8648 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8649
fab49f61
JM
8650 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8651 r_nonce)
8652 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8653
8654 logger.debug("Send WSC_NACK to AP")
15dfcb69 8655 attrs = b'\x10\x00\x00'
7511ead0
JM
8656 nack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_NACK)
8657 send_wsc_msg(hapd, addr, nack)
8658
8659 wps_wait_eap_failure(hapd, dev[0])
8660
9fd6804d 8661@remote_compatible
7511ead0
JM
8662def test_wps_ext_m2_nack_no_msg_type(dev, apdev):
8663 """WPS proto: M2 followed by NACK without Msg Type"""
8664 pin = "12345670"
fab49f61 8665 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8666 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8667 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8668
8669 logger.debug("Receive WSC/Start from AP")
8670 msg = get_wsc_msg(hapd)
8671 if msg['wsc_opcode'] != WSC_Start:
8672 raise Exception("Unexpected Op-Code for WSC/Start")
8673
8674 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8675 uuid_e = 16*b'\x11'
8676 e_nonce = 16*b'\x22'
7511ead0
JM
8677 own_private, e_pk = wsc_dh_init()
8678
8679 logger.debug("Send M1 to AP")
8680 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8681 e_nonce, e_pk)
8682 send_wsc_msg(hapd, addr, m1)
8683
8684 logger.debug("Receive M2 from AP")
8685 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8686 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8687 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8688
fab49f61
JM
8689 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8690 r_nonce)
8691 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8692
8693 logger.debug("Send WSC_NACK to AP")
fab49f61
JM
8694 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8695 msg_type=None, eap_code=2)
7511ead0
JM
8696 send_wsc_msg(hapd, addr, nack)
8697
8698 wps_wait_eap_failure(hapd, dev[0])
8699
9fd6804d 8700@remote_compatible
7511ead0
JM
8701def test_wps_ext_m2_nack_invalid_msg_type(dev, apdev):
8702 """WPS proto: M2 followed by NACK with invalid Msg Type"""
8703 pin = "12345670"
fab49f61 8704 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8705 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8706 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8707
8708 logger.debug("Receive WSC/Start from AP")
8709 msg = get_wsc_msg(hapd)
8710 if msg['wsc_opcode'] != WSC_Start:
8711 raise Exception("Unexpected Op-Code for WSC/Start")
8712
8713 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8714 uuid_e = 16*b'\x11'
8715 e_nonce = 16*b'\x22'
7511ead0
JM
8716 own_private, e_pk = wsc_dh_init()
8717
8718 logger.debug("Send M1 to AP")
8719 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8720 e_nonce, e_pk)
8721 send_wsc_msg(hapd, addr, m1)
8722
8723 logger.debug("Receive M2 from AP")
8724 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8725 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8726 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8727
fab49f61
JM
8728 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8729 r_nonce)
8730 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8731
8732 logger.debug("Send WSC_NACK to AP")
fab49f61
JM
8733 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8734 msg_type=WPS_WSC_ACK, eap_code=2)
7511ead0
JM
8735 send_wsc_msg(hapd, addr, nack)
8736
8737 wps_wait_eap_failure(hapd, dev[0])
8738
9fd6804d 8739@remote_compatible
7511ead0
JM
8740def test_wps_ext_m2_nack_e_nonce_mismatch(dev, apdev):
8741 """WPS proto: M2 followed by NACK with e-nonce mismatch"""
8742 pin = "12345670"
fab49f61 8743 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8744 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8745 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8746
8747 logger.debug("Receive WSC/Start from AP")
8748 msg = get_wsc_msg(hapd)
8749 if msg['wsc_opcode'] != WSC_Start:
8750 raise Exception("Unexpected Op-Code for WSC/Start")
8751
8752 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8753 uuid_e = 16*b'\x11'
8754 e_nonce = 16*b'\x22'
7511ead0
JM
8755 own_private, e_pk = wsc_dh_init()
8756
8757 logger.debug("Send M1 to AP")
8758 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8759 e_nonce, e_pk)
8760 send_wsc_msg(hapd, addr, m1)
8761
8762 logger.debug("Receive M2 from AP")
8763 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8764 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8765 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8766
fab49f61
JM
8767 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8768 r_nonce)
8769 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8770
8771 logger.debug("Send WSC_NACK to AP")
fab49f61
JM
8772 nack, attrs = build_nack(msg['eap_identifier'], 16*b'\x00', r_nonce,
8773 eap_code=2)
7511ead0
JM
8774 send_wsc_msg(hapd, addr, nack)
8775
8776 wps_wait_eap_failure(hapd, dev[0])
8777
9fd6804d 8778@remote_compatible
7511ead0
JM
8779def test_wps_ext_m2_nack_no_config_error(dev, apdev):
8780 """WPS proto: M2 followed by NACK without Config Error"""
8781 pin = "12345670"
fab49f61 8782 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8783 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8784 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8785
8786 logger.debug("Receive WSC/Start from AP")
8787 msg = get_wsc_msg(hapd)
8788 if msg['wsc_opcode'] != WSC_Start:
8789 raise Exception("Unexpected Op-Code for WSC/Start")
8790
8791 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8792 uuid_e = 16*b'\x11'
8793 e_nonce = 16*b'\x22'
7511ead0
JM
8794 own_private, e_pk = wsc_dh_init()
8795
8796 logger.debug("Send M1 to AP")
8797 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8798 e_nonce, e_pk)
8799 send_wsc_msg(hapd, addr, m1)
8800
8801 logger.debug("Receive M2 from AP")
8802 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8803 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8804 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8805
fab49f61
JM
8806 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8807 r_nonce)
8808 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8809
8810 logger.debug("Send WSC_NACK to AP")
fab49f61
JM
8811 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8812 config_error=None, eap_code=2)
7511ead0
JM
8813 send_wsc_msg(hapd, addr, nack)
8814
8815 wps_wait_eap_failure(hapd, dev[0])
8816
9fd6804d 8817@remote_compatible
7511ead0
JM
8818def test_wps_ext_m2_ack_invalid(dev, apdev):
8819 """WPS proto: M2 followed by invalid ACK"""
8820 pin = "12345670"
fab49f61 8821 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8822 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8823 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8824
8825 logger.debug("Receive WSC/Start from AP")
8826 msg = get_wsc_msg(hapd)
8827 if msg['wsc_opcode'] != WSC_Start:
8828 raise Exception("Unexpected Op-Code for WSC/Start")
8829
8830 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8831 uuid_e = 16*b'\x11'
8832 e_nonce = 16*b'\x22'
7511ead0
JM
8833 own_private, e_pk = wsc_dh_init()
8834
8835 logger.debug("Send M1 to AP")
8836 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8837 e_nonce, e_pk)
8838 send_wsc_msg(hapd, addr, m1)
8839
8840 logger.debug("Receive M2 from AP")
8841 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8842 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8843 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8844
fab49f61
JM
8845 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8846 r_nonce)
8847 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8848
8849 logger.debug("Send WSC_ACK to AP")
15dfcb69 8850 attrs = b'\x10\x00\x00'
7511ead0
JM
8851 ack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_ACK)
8852 send_wsc_msg(hapd, addr, ack)
8853
8854 wps_wait_eap_failure(hapd, dev[0])
8855
9fd6804d 8856@remote_compatible
7511ead0
JM
8857def test_wps_ext_m2_ack(dev, apdev):
8858 """WPS proto: M2 followed by ACK"""
8859 pin = "12345670"
fab49f61 8860 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8861 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8862 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8863
8864 logger.debug("Receive WSC/Start from AP")
8865 msg = get_wsc_msg(hapd)
8866 if msg['wsc_opcode'] != WSC_Start:
8867 raise Exception("Unexpected Op-Code for WSC/Start")
8868
8869 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8870 uuid_e = 16*b'\x11'
8871 e_nonce = 16*b'\x22'
7511ead0
JM
8872 own_private, e_pk = wsc_dh_init()
8873
8874 logger.debug("Send M1 to AP")
8875 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8876 e_nonce, e_pk)
8877 send_wsc_msg(hapd, addr, m1)
8878
8879 logger.debug("Receive M2 from AP")
8880 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8881 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8882 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8883
fab49f61
JM
8884 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8885 r_nonce)
8886 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8887
8888 logger.debug("Send WSC_ACK to AP")
fab49f61 8889 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce, eap_code=2)
7511ead0
JM
8890 send_wsc_msg(hapd, addr, ack)
8891
8892 wps_wait_eap_failure(hapd, dev[0])
8893
9fd6804d 8894@remote_compatible
7511ead0
JM
8895def test_wps_ext_m2_ack_no_msg_type(dev, apdev):
8896 """WPS proto: M2 followed by ACK missing Msg Type"""
8897 pin = "12345670"
fab49f61 8898 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8899 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8900 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8901
8902 logger.debug("Receive WSC/Start from AP")
8903 msg = get_wsc_msg(hapd)
8904 if msg['wsc_opcode'] != WSC_Start:
8905 raise Exception("Unexpected Op-Code for WSC/Start")
8906
8907 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8908 uuid_e = 16*b'\x11'
8909 e_nonce = 16*b'\x22'
7511ead0
JM
8910 own_private, e_pk = wsc_dh_init()
8911
8912 logger.debug("Send M1 to AP")
8913 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8914 e_nonce, e_pk)
8915 send_wsc_msg(hapd, addr, m1)
8916
8917 logger.debug("Receive M2 from AP")
8918 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8919 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8920 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8921
fab49f61
JM
8922 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8923 r_nonce)
8924 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8925
8926 logger.debug("Send WSC_ACK to AP")
fab49f61
JM
8927 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8928 msg_type=None, eap_code=2)
7511ead0
JM
8929 send_wsc_msg(hapd, addr, ack)
8930
8931 wps_wait_eap_failure(hapd, dev[0])
8932
9fd6804d 8933@remote_compatible
7511ead0
JM
8934def test_wps_ext_m2_ack_invalid_msg_type(dev, apdev):
8935 """WPS proto: M2 followed by ACK with invalid Msg Type"""
8936 pin = "12345670"
fab49f61 8937 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8938 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8939 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8940
8941 logger.debug("Receive WSC/Start from AP")
8942 msg = get_wsc_msg(hapd)
8943 if msg['wsc_opcode'] != WSC_Start:
8944 raise Exception("Unexpected Op-Code for WSC/Start")
8945
8946 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8947 uuid_e = 16*b'\x11'
8948 e_nonce = 16*b'\x22'
7511ead0
JM
8949 own_private, e_pk = wsc_dh_init()
8950
8951 logger.debug("Send M1 to AP")
8952 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8953 e_nonce, e_pk)
8954 send_wsc_msg(hapd, addr, m1)
8955
8956 logger.debug("Receive M2 from AP")
8957 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8958 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8959 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8960
fab49f61
JM
8961 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8962 r_nonce)
8963 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
8964
8965 logger.debug("Send WSC_ACK to AP")
fab49f61 8966 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
7511ead0
JM
8967 msg_type=WPS_WSC_NACK, eap_code=2)
8968 send_wsc_msg(hapd, addr, ack)
8969
8970 wps_wait_eap_failure(hapd, dev[0])
8971
9fd6804d 8972@remote_compatible
7511ead0
JM
8973def test_wps_ext_m2_ack_e_nonce_mismatch(dev, apdev):
8974 """WPS proto: M2 followed by ACK with e-nonce mismatch"""
8975 pin = "12345670"
fab49f61 8976 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
8977 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8978 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8979
8980 logger.debug("Receive WSC/Start from AP")
8981 msg = get_wsc_msg(hapd)
8982 if msg['wsc_opcode'] != WSC_Start:
8983 raise Exception("Unexpected Op-Code for WSC/Start")
8984
8985 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
8986 uuid_e = 16*b'\x11'
8987 e_nonce = 16*b'\x22'
7511ead0
JM
8988 own_private, e_pk = wsc_dh_init()
8989
8990 logger.debug("Send M1 to AP")
8991 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8992 e_nonce, e_pk)
8993 send_wsc_msg(hapd, addr, m1)
8994
8995 logger.debug("Receive M2 from AP")
8996 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8997 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8998 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8999
fab49f61
JM
9000 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9001 r_nonce)
9002 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
9003
9004 logger.debug("Send WSC_ACK to AP")
fab49f61
JM
9005 ack, attrs = build_ack(msg['eap_identifier'], 16*b'\x00', r_nonce,
9006 eap_code=2)
7511ead0
JM
9007 send_wsc_msg(hapd, addr, ack)
9008
9009 wps_wait_eap_failure(hapd, dev[0])
9010
9fd6804d 9011@remote_compatible
7511ead0
JM
9012def test_wps_ext_m1_invalid(dev, apdev):
9013 """WPS proto: M1 failing parsing"""
9014 pin = "12345670"
fab49f61 9015 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
9016 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9017 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9018
9019 logger.debug("Receive WSC/Start from AP")
9020 msg = get_wsc_msg(hapd)
9021 if msg['wsc_opcode'] != WSC_Start:
9022 raise Exception("Unexpected Op-Code for WSC/Start")
9023
9024 logger.debug("Send M1 to AP")
15dfcb69 9025 attrs = b'\x10\x00\x00'
7511ead0
JM
9026 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9027 send_wsc_msg(hapd, addr, m1)
9028
9029 wps_wait_eap_failure(hapd, dev[0])
9030
9031def test_wps_ext_m1_missing_msg_type(dev, apdev):
9032 """WPS proto: M1 missing Msg Type"""
9033 pin = "12345670"
fab49f61 9034 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
9035 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9036 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9037
9038 logger.debug("Receive WSC/Start from AP")
9039 msg = get_wsc_msg(hapd)
9040 if msg['wsc_opcode'] != WSC_Start:
9041 raise Exception("Unexpected Op-Code for WSC/Start")
9042
9043 logger.debug("Send M1 to AP")
9044 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9045 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9046 send_wsc_msg(hapd, addr, m1)
9047
15dfcb69 9048 wps_wait_ap_nack(hapd, dev[0], 16*b'\x00', 16*b'\x00')
7511ead0
JM
9049
9050def wps_ext_wsc_done(dev, apdev):
9051 pin = "12345670"
fab49f61 9052 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
9053 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9054 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9055
9056 logger.debug("Receive WSC/Start from AP")
9057 msg = get_wsc_msg(hapd)
9058 if msg['wsc_opcode'] != WSC_Start:
9059 raise Exception("Unexpected Op-Code for WSC/Start")
9060
9061 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
9062 uuid_e = 16*b'\x11'
9063 e_nonce = 16*b'\x22'
7511ead0
JM
9064 own_private, e_pk = wsc_dh_init()
9065
9066 logger.debug("Send M1 to AP")
9067 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9068 e_nonce, e_pk)
9069 send_wsc_msg(hapd, addr, m1)
9070
9071 logger.debug("Receive M2 from AP")
9072 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9073 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9074 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9075
fab49f61
JM
9076 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9077 r_nonce)
9078 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
9079
9080 logger.debug("Send M3 to AP")
9081 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9082 attrs += build_attr_msg_type(WPS_M3)
9083 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9084 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9085 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9086 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9087 raw_m3_attrs = attrs
9088 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9089 send_wsc_msg(hapd, addr, m3)
9090
9091 logger.debug("Receive M4 from AP")
9092 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9093
9094 logger.debug("Send M5 to AP")
9095 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9096 attrs += build_attr_msg_type(WPS_M5)
9097 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9098 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9099 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9100 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9101 raw_m5_attrs = attrs
9102 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9103 send_wsc_msg(hapd, addr, m5)
9104
9105 logger.debug("Receive M6 from AP")
9106 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9107
9108 logger.debug("Send M7 to AP")
9109 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9110 attrs += build_attr_msg_type(WPS_M7)
9111 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9112 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9113 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9114 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9115 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9116 raw_m7_attrs = attrs
9117 send_wsc_msg(hapd, addr, m7)
9118
9119 logger.debug("Receive M8 from AP")
9120 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
9121 return hapd, msg, e_nonce, r_nonce
9122
9fd6804d 9123@remote_compatible
7511ead0
JM
9124def test_wps_ext_wsc_done_invalid(dev, apdev):
9125 """WPS proto: invalid WSC_Done"""
9126 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9127
9128 logger.debug("Send WSC_Done to AP")
15dfcb69 9129 attrs = b'\x10\x00\x00'
7511ead0
JM
9130 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9131 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9132
9133 wps_wait_eap_failure(hapd, dev[0])
9134
9fd6804d 9135@remote_compatible
7511ead0
JM
9136def test_wps_ext_wsc_done_no_msg_type(dev, apdev):
9137 """WPS proto: invalid WSC_Done"""
9138 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9139
9140 logger.debug("Send WSC_Done to AP")
9141 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9142 #attrs += build_attr_msg_type(WPS_WSC_DONE)
9143 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9144 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9145 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9146 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9147
9148 wps_wait_eap_failure(hapd, dev[0])
9149
9fd6804d 9150@remote_compatible
7511ead0
JM
9151def test_wps_ext_wsc_done_wrong_msg_type(dev, apdev):
9152 """WPS proto: WSC_Done with wrong Msg Type"""
9153 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9154
9155 logger.debug("Send WSC_Done to AP")
9156 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9157 attrs += build_attr_msg_type(WPS_WSC_ACK)
9158 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9159 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9160 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9161 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9162
9163 wps_wait_eap_failure(hapd, dev[0])
9164
9fd6804d 9165@remote_compatible
7511ead0
JM
9166def test_wps_ext_wsc_done_no_e_nonce(dev, apdev):
9167 """WPS proto: WSC_Done without e_nonce"""
9168 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9169
9170 logger.debug("Send WSC_Done to AP")
9171 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9172 attrs += build_attr_msg_type(WPS_WSC_DONE)
9173 #attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9174 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9175 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9176 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9177
9178 wps_wait_eap_failure(hapd, dev[0])
9179
9180def test_wps_ext_wsc_done_no_r_nonce(dev, apdev):
9181 """WPS proto: WSC_Done without r_nonce"""
9182 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9183
9184 logger.debug("Send WSC_Done to AP")
9185 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9186 attrs += build_attr_msg_type(WPS_WSC_DONE)
9187 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9188 #attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9189 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9190 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9191
9192 wps_wait_eap_failure(hapd, dev[0])
9193
9fd6804d 9194@remote_compatible
7511ead0
JM
9195def test_wps_ext_m7_no_encr_settings(dev, apdev):
9196 """WPS proto: M7 without Encr Settings"""
9197 pin = "12345670"
fab49f61 9198 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
9199 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9200 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9201
9202 logger.debug("Receive WSC/Start from AP")
9203 msg = get_wsc_msg(hapd)
9204 if msg['wsc_opcode'] != WSC_Start:
9205 raise Exception("Unexpected Op-Code for WSC/Start")
9206
9207 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
9208 uuid_e = 16*b'\x11'
9209 e_nonce = 16*b'\x22'
7511ead0
JM
9210 own_private, e_pk = wsc_dh_init()
9211
9212 logger.debug("Send M1 to AP")
9213 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9214 e_nonce, e_pk)
9215 send_wsc_msg(hapd, addr, m1)
9216
9217 logger.debug("Receive M2 from AP")
9218 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9219 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9220 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9221
fab49f61
JM
9222 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9223 r_nonce)
9224 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7511ead0
JM
9225
9226 logger.debug("Send M3 to AP")
9227 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9228 attrs += build_attr_msg_type(WPS_M3)
9229 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9230 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9231 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9232 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9233 raw_m3_attrs = attrs
9234 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9235 send_wsc_msg(hapd, addr, m3)
9236
9237 logger.debug("Receive M4 from AP")
9238 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9239
9240 logger.debug("Send M5 to AP")
9241 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9242 attrs += build_attr_msg_type(WPS_M5)
9243 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9244 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9245 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9246 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9247 raw_m5_attrs = attrs
9248 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9249 send_wsc_msg(hapd, addr, m5)
9250
9251 logger.debug("Receive M6 from AP")
9252 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9253
9254 logger.debug("Send M7 to AP")
9255 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9256 attrs += build_attr_msg_type(WPS_M7)
9257 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9258 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9259 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9260 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9261 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9262 raw_m7_attrs = attrs
9263 send_wsc_msg(hapd, addr, m7)
9264
9265 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
9266
9fd6804d 9267@remote_compatible
7511ead0
JM
9268def test_wps_ext_m1_workaround(dev, apdev):
9269 """WPS proto: M1 Manufacturer/Model workaround"""
9270 pin = "12345670"
fab49f61 9271 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7511ead0
JM
9272 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9273 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9274
9275 logger.debug("Receive WSC/Start from AP")
9276 msg = get_wsc_msg(hapd)
9277 if msg['wsc_opcode'] != WSC_Start:
9278 raise Exception("Unexpected Op-Code for WSC/Start")
9279
9280 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
15dfcb69
MH
9281 uuid_e = 16*b'\x11'
9282 e_nonce = 16*b'\x22'
7511ead0
JM
9283 own_private, e_pk = wsc_dh_init()
9284
9285 logger.debug("Send M1 to AP")
9286 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9287 e_nonce, e_pk, manufacturer='Apple TEST',
15dfcb69 9288 model_name='AirPort', config_methods=b'\xff\xff')
7511ead0
JM
9289 send_wsc_msg(hapd, addr, m1)
9290
9291 logger.debug("Receive M2 from AP")
9292 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
53bd8653 9293
9fd6804d 9294@remote_compatible
53bd8653
JM
9295def test_ap_wps_disable_enable(dev, apdev):
9296 """WPS and DISABLE/ENABLE AP"""
9297 hapd = wps_start_ap(apdev[0])
9298 hapd.disable()
9299 hapd.enable()
9300 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
dd124ee8
JM
9301
9302def test_ap_wps_upnp_web_oom(dev, apdev, params):
9303 """hostapd WPS UPnP web OOM"""
9304 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 9305 hapd = add_ssdp_ap(apdev[0], ap_uuid)
dd124ee8
JM
9306
9307 location = ssdp_get_location(ap_uuid)
9c06eda0 9308 url = urlparse(location)
dd124ee8 9309 urls = upnp_get_urls(location)
9c06eda0
MH
9310 eventurl = urlparse(urls['event_sub_url'])
9311 ctrlurl = urlparse(urls['control_url'])
dd124ee8 9312
9c06eda0 9313 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9314 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9315 conn.request("GET", "/wps_device.xml")
9316 try:
9317 resp = conn.getresponse()
9318 except:
9319 pass
9320
9c06eda0 9321 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9322 conn.request("GET", "/unknown")
9323 resp = conn.getresponse()
9324 if resp.status != 404:
9325 raise Exception("Unexpected HTTP result for unknown URL: %d" + resp.status)
9326
9327 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9328 conn.request("GET", "/unknown")
9329 try:
9330 resp = conn.getresponse()
89896c00 9331 print(resp.status)
dd124ee8
JM
9332 except:
9333 pass
9334
9c06eda0 9335 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9336 conn.request("GET", "/wps_device.xml")
9337 resp = conn.getresponse()
9338 if resp.status != 200:
9339 raise Exception("GET /wps_device.xml failed")
9340
9c06eda0 9341 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9342 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9343 if resp.status != 200:
9344 raise Exception("GetDeviceInfo failed")
9345
9346 with alloc_fail(hapd, 1, "web_process_get_device_info"):
9c06eda0 9347 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9348 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9349 if resp.status != 500:
9350 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9351
9352 with alloc_fail(hapd, 1, "wps_build_m1;web_process_get_device_info"):
9c06eda0 9353 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9354 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9355 if resp.status != 500:
9356 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9357
9358 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_send_reply"):
9c06eda0 9359 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9360 try:
9361 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9362 except:
9363 pass
9364
9c06eda0 9365 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9366 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9367 if resp.status != 200:
9368 raise Exception("GetDeviceInfo failed")
9369
9370 # No NewWLANEventType in PutWLANResponse NewMessage
9c06eda0 9371 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9372 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse", newmsg="foo")
9373 if resp.status != 600:
9374 raise Exception("Unexpected HTTP response: %d" % resp.status)
9375
9376 # No NewWLANEventMAC in PutWLANResponse NewMessage
9c06eda0 9377 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9378 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9379 newmsg="foo", neweventtype="1")
9380 if resp.status != 600:
9381 raise Exception("Unexpected HTTP response: %d" % resp.status)
9382
9383 # Invalid NewWLANEventMAC in PutWLANResponse NewMessage
9c06eda0 9384 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9385 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9386 newmsg="foo", neweventtype="1",
9387 neweventmac="foo")
9388 if resp.status != 600:
9389 raise Exception("Unexpected HTTP response: %d" % resp.status)
9390
9391 # Workaround for NewWLANEventMAC in PutWLANResponse NewMessage
9392 # Ignored unexpected PutWLANResponse WLANEventType 1
9c06eda0 9393 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9394 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9395 newmsg="foo", neweventtype="1",
9396 neweventmac="00.11.22.33.44.55")
9397 if resp.status != 500:
9398 raise Exception("Unexpected HTTP response: %d" % resp.status)
9399
9400 # PutWLANResponse NewMessage with invalid EAP message
9c06eda0 9401 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9402 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9403 newmsg="foo", neweventtype="2",
9404 neweventmac="00:11:22:33:44:55")
9405 if resp.status != 200:
9406 raise Exception("Unexpected HTTP response: %d" % resp.status)
9407
9408 with alloc_fail(hapd, 1, "web_connection_parse_subscribe"):
9c06eda0 9409 conn = HTTPConnection(url.netloc)
fab49f61
JM
9410 headers = {"callback": '<http://127.0.0.1:12345/event>',
9411 "NT": "upnp:event",
9412 "timeout": "Second-1234"}
dd124ee8
JM
9413 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9414 try:
9415 resp = conn.getresponse()
9416 except:
9417 pass
9418
9419 with alloc_fail(hapd, 1, "dup_binstr;web_connection_parse_subscribe"):
9c06eda0 9420 conn = HTTPConnection(url.netloc)
fab49f61
JM
9421 headers = {"callback": '<http://127.0.0.1:12345/event>',
9422 "NT": "upnp:event",
9423 "timeout": "Second-1234"}
dd124ee8
JM
9424 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9425 resp = conn.getresponse()
9426 if resp.status != 500:
9427 raise Exception("Unexpected HTTP response: %d" % resp.status)
9428
9429 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_parse_unsubscribe"):
9c06eda0 9430 conn = HTTPConnection(url.netloc)
fab49f61
JM
9431 headers = {"callback": '<http://127.0.0.1:12345/event>',
9432 "NT": "upnp:event",
9433 "timeout": "Second-1234"}
dd124ee8
JM
9434 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9435 try:
9436 resp = conn.getresponse()
9437 except:
9438 pass
9439
9440 with alloc_fail(hapd, 1, "web_connection_unimplemented"):
9c06eda0 9441 conn = HTTPConnection(url.netloc)
dd124ee8
JM
9442 conn.request("HEAD", "/wps_device.xml")
9443 try:
9444 resp = conn.getresponse()
9445 except:
9446 pass
d1341917
JM
9447
9448def test_ap_wps_frag_ack_oom(dev, apdev):
9449 """WPS and fragment ack OOM"""
9450 dev[0].request("SET wps_fragment_size 50")
9451 hapd = wps_start_ap(apdev[0])
9452 with alloc_fail(hapd, 1, "eap_wsc_build_frag_ack"):
9453 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
1e35aa15
JM
9454
9455def wait_scan_stopped(dev):
9456 dev.request("ABORT_SCAN")
9457 for i in range(50):
9458 res = dev.get_driver_status_field("scan_state")
9459 if "SCAN_STARTED" not in res and "SCAN_REQUESTED" not in res:
9460 break
9461 logger.debug("Waiting for scan to complete")
9462 time.sleep(0.1)
9463
9fd6804d 9464@remote_compatible
1e35aa15
JM
9465def test_ap_wps_eap_wsc_errors(dev, apdev):
9466 """WPS and EAP-WSC error cases"""
9467 ssid = "test-wps-conf-pin"
9468 appin = "12345670"
fab49f61
JM
9469 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9470 "wpa_passphrase": "12345678", "wpa": "2",
9471 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9472 "fragment_size": "300", "ap_pin": appin}
8b8a1864 9473 hapd = hostapd.add_ap(apdev[0], params)
1e35aa15
JM
9474 bssid = apdev[0]['bssid']
9475
9476 pin = dev[0].wps_read_pin()
9477 hapd.request("WPS_PIN any " + pin)
9478 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9479 dev[0].dump_monitor()
9480
9481 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK", "CCMP",
9482 "new passphrase", no_wait=True)
9483 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9484 if ev is None:
9485 raise Exception("WPS-FAIL not reported")
9486 dev[0].request("WPS_CANCEL")
9487 dev[0].wait_disconnected()
9488 wait_scan_stopped(dev[0])
9489 dev[0].dump_monitor()
9490
9491 dev[0].wps_reg(bssid, appin, "new ssid", "FOO", "CCMP",
9492 "new passphrase", no_wait=True)
9493 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9494 if ev is None:
9495 raise Exception("WPS-FAIL not reported")
9496 dev[0].request("WPS_CANCEL")
9497 dev[0].wait_disconnected()
9498 wait_scan_stopped(dev[0])
9499 dev[0].dump_monitor()
9500
9501 dev[0].wps_reg(bssid, appin, "new ssid", "WPA2PSK", "FOO",
9502 "new passphrase", no_wait=True)
9503 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9504 if ev is None:
9505 raise Exception("WPS-FAIL not reported")
9506 dev[0].request("WPS_CANCEL")
9507 dev[0].wait_disconnected()
9508 wait_scan_stopped(dev[0])
9509 dev[0].dump_monitor()
9510
9511 dev[0].wps_reg(bssid, appin + "new_key=a", "new ssid", "WPA2PSK", "CCMP",
9512 "new passphrase", no_wait=True)
9513 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9514 if ev is None:
9515 raise Exception("WPS-FAIL not reported")
9516 dev[0].request("WPS_CANCEL")
9517 dev[0].wait_disconnected()
9518 wait_scan_stopped(dev[0])
9519 dev[0].dump_monitor()
9520
fab49f61
JM
9521 tests = ["eap_wsc_init",
9522 "eap_msg_alloc;eap_wsc_build_msg",
9523 "wpabuf_alloc;eap_wsc_process_fragment"]
1e35aa15
JM
9524 for func in tests:
9525 with alloc_fail(dev[0], 1, func):
9526 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
9527 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9528 dev[0].request("WPS_CANCEL")
9529 dev[0].wait_disconnected()
0a9ff381
JM
9530 wait_scan_stopped(dev[0])
9531 dev[0].dump_monitor()
9532
9533 tests = [(1, "wps_decrypt_encr_settings"),
9534 (2, "hmac_sha256;wps_derive_psk")]
9535 for count, func in tests:
9536 hapd.request("WPS_PIN any " + pin)
9537 with fail_test(dev[0], count, func):
9538 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
9539 wait_fail_trigger(dev[0], "GET_FAIL")
9540 dev[0].request("WPS_CANCEL")
9541 dev[0].wait_disconnected()
1e35aa15
JM
9542 wait_scan_stopped(dev[0])
9543 dev[0].dump_monitor()
d8e5a55f 9544
bd3948c0
JM
9545 with alloc_fail(dev[0], 1, "eap_msg_alloc;eap_sm_build_expanded_nak"):
9546 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK",
9547 "CCMP", "new passphrase", no_wait=True)
9548 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9549 dev[0].request("WPS_CANCEL")
9550 dev[0].wait_disconnected()
9551 wait_scan_stopped(dev[0])
9552 dev[0].dump_monitor()
9553
d8e5a55f
JM
9554def test_ap_wps_eap_wsc(dev, apdev):
9555 """WPS and EAP-WSC in network profile"""
9556 params = int_eap_server_params()
9557 params["wps_state"] = "2"
8b8a1864 9558 hapd = hostapd.add_ap(apdev[0], params)
d8e5a55f
JM
9559 bssid = apdev[0]['bssid']
9560
9561 logger.info("Unexpected identity")
9562 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9563 eap="WSC", identity="WFA-SimpleConfig-Enrollee-unexpected",
9564 wait_connect=False)
9565 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9566 if ev is None:
9567 raise Exception("No EAP-Failure seen")
9568 dev[0].request("REMOVE_NETWORK all")
9569 dev[0].wait_disconnected()
9570
9571 logger.info("No phase1 parameter")
9572 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9573 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9574 wait_connect=False)
9575 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9576 if ev is None:
9577 raise Exception("Timeout on EAP method start")
9578 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9579 if ev is None:
9580 raise Exception("No EAP-Failure seen")
9581 dev[0].request("REMOVE_NETWORK all")
9582 dev[0].wait_disconnected()
9583
9584 logger.info("No PIN/PBC in phase1")
9585 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9586 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9587 phase1="foo", wait_connect=False)
9588 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9589 if ev is None:
9590 raise Exception("Timeout on EAP method start")
9591 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9592 if ev is None:
9593 raise Exception("No EAP-Failure seen")
9594 dev[0].request("REMOVE_NETWORK all")
9595 dev[0].wait_disconnected()
9596
9597 logger.info("Invalid pkhash in phase1")
9598 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9599 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9600 phase1="foo pkhash=q pbc=1", wait_connect=False)
9601 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9602 if ev is None:
9603 raise Exception("Timeout on EAP method start")
9604 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9605 if ev is None:
9606 raise Exception("No EAP-Failure seen")
9607 dev[0].request("REMOVE_NETWORK all")
9608 dev[0].wait_disconnected()
9609
9610 logger.info("Zero fragment_size")
9611 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9612 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9613 fragment_size="0", phase1="pin=12345670", wait_connect=False)
9614 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9615 if ev is None:
9616 raise Exception("Timeout on EAP method start")
9617 ev = dev[0].wait_event(["WPS-M2D"], timeout=5)
9618 if ev is None:
9619 raise Exception("No M2D seen")
9620 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9621 if ev is None:
9622 raise Exception("No EAP-Failure seen")
9623 dev[0].request("REMOVE_NETWORK all")
9624 dev[0].wait_disconnected()
9625
9626 logger.info("Missing new_auth")
9627 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9628 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9629 phase1="pin=12345670 new_ssid=aa", wait_connect=False)
9630 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9631 if ev is None:
9632 raise Exception("Timeout on EAP method start")
9633 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9634 if ev is None:
9635 raise Exception("No EAP-Failure seen")
9636 dev[0].request("REMOVE_NETWORK all")
9637 dev[0].wait_disconnected()
9638
9639 logger.info("Missing new_encr")
9640 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9641 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9642 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa", wait_connect=False)
9643 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9644 if ev is None:
9645 raise Exception("Timeout on EAP method start")
9646 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9647 if ev is None:
9648 raise Exception("No EAP-Failure seen")
9649 dev[0].request("REMOVE_NETWORK all")
9650 dev[0].wait_disconnected()
9651
9652 logger.info("Missing new_key")
9653 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9654 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9655 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa new_encr=CCMP",
9656 wait_connect=False)
9657 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9658 if ev is None:
9659 raise Exception("Timeout on EAP method start")
9660 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9661 if ev is None:
9662 raise Exception("No EAP-Failure seen")
9663 dev[0].request("REMOVE_NETWORK all")
9664 dev[0].wait_disconnected()
4425b1ed
JM
9665
9666def test_ap_wps_and_bss_limit(dev, apdev):
9667 """WPS and wpa_supplicant BSS entry limit"""
9668 try:
9669 _test_ap_wps_and_bss_limit(dev, apdev)
9670 finally:
9671 dev[0].request("SET bss_max_count 200")
9672 pass
9673
9674def _test_ap_wps_and_bss_limit(dev, apdev):
fab49f61
JM
9675 params = {"ssid": "test-wps", "eap_server": "1", "wps_state": "2",
9676 "wpa_passphrase": "12345678", "wpa": "2",
9677 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
4425b1ed
JM
9678 hapd = hostapd.add_ap(apdev[0], params)
9679
fab49f61
JM
9680 params = {"ssid": "test-wps-2", "eap_server": "1", "wps_state": "2",
9681 "wpa_passphrase": "1234567890", "wpa": "2",
9682 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
4425b1ed
JM
9683 hapd2 = hostapd.add_ap(apdev[1], params)
9684
9685 id = dev[1].add_network()
9686 dev[1].set_network(id, "mode", "2")
9687 dev[1].set_network_quoted(id, "ssid", "wpas-ap-no-wps")
9688 dev[1].set_network_quoted(id, "psk", "12345678")
9689 dev[1].set_network(id, "frequency", "2462")
9690 dev[1].set_network(id, "scan_freq", "2462")
9691 dev[1].set_network(id, "wps_disabled", "1")
9692 dev[1].select_network(id)
9693
9694 id = dev[2].add_network()
9695 dev[2].set_network(id, "mode", "2")
9696 dev[2].set_network_quoted(id, "ssid", "wpas-ap")
9697 dev[2].set_network_quoted(id, "psk", "12345678")
9698 dev[2].set_network(id, "frequency", "2437")
9699 dev[2].set_network(id, "scan_freq", "2437")
9700 dev[2].select_network(id)
9701
9702 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9703 wpas.interface_add("wlan5")
9704 id = wpas.add_network()
9705 wpas.set_network(id, "mode", "2")
9706 wpas.set_network_quoted(id, "ssid", "wpas-ap")
9707 wpas.set_network_quoted(id, "psk", "12345678")
9708 wpas.set_network(id, "frequency", "2437")
9709 wpas.set_network(id, "scan_freq", "2437")
9710 wpas.select_network(id)
9711
9712 dev[1].wait_connected()
9713 dev[2].wait_connected()
9714 wpas.wait_connected()
9715 wpas.request("WPS_PIN any 12345670")
9716
9717 hapd.request("WPS_PBC")
9718 hapd2.request("WPS_PBC")
9719
9720 dev[0].request("SET bss_max_count 1")
9721
9722 id = dev[0].add_network()
9723 dev[0].set_network_quoted(id, "ssid", "testing")
9724
9725 id = dev[0].add_network()
9726 dev[0].set_network_quoted(id, "ssid", "testing")
9727 dev[0].set_network(id, "key_mgmt", "WPS")
9728
9729 dev[0].request("WPS_PBC")
9730 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
9731 dev[0].request("WPS_CANCEL")
9732
9733 id = dev[0].add_network()
9734 dev[0].set_network_quoted(id, "ssid", "testing")
9735 dev[0].set_network(id, "key_mgmt", "WPS")
9736
9737 dev[0].scan(freq="2412")
74b23faf
JM
9738
9739def test_ap_wps_pbc_2ap(dev, apdev):
9740 """WPS PBC with two APs advertising same SSID"""
fab49f61
JM
9741 params = {"ssid": "wps", "eap_server": "1", "wps_state": "2",
9742 "wpa_passphrase": "12345678", "wpa": "2",
9743 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9744 "wps_independent": "1"}
74b23faf 9745 hapd = hostapd.add_ap(apdev[0], params)
fab49f61
JM
9746 params = {"ssid": "wps", "eap_server": "1", "wps_state": "2",
9747 "wpa_passphrase": "123456789", "wpa": "2",
9748 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9749 "wps_independent": "1"}
74b23faf
JM
9750 hapd2 = hostapd.add_ap(apdev[1], params)
9751 hapd.request("WPS_PBC")
9752
9753 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9754 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
9755 wpas.dump_monitor()
8b944cf7 9756 wpas.flush_scan_cache()
74b23faf
JM
9757
9758 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
9759 wpas.scan_for_bss(apdev[1]['bssid'], freq="2412")
9760 wpas.request("WPS_PBC")
9761 wpas.wait_connected()
9762 wpas.request("DISCONNECT")
9763 hapd.request("DISABLE")
9764 hapd2.request("DISABLE")
9765 wpas.flush_scan_cache()
aed9e23a
JM
9766
9767def test_ap_wps_er_enrollee_to_conf_ap(dev, apdev):
9768 """WPS ER enrolling a new device to a configured AP"""
9769 try:
9770 _test_ap_wps_er_enrollee_to_conf_ap(dev, apdev)
9771 finally:
9772 dev[0].request("WPS_ER_STOP")
9773
9774def _test_ap_wps_er_enrollee_to_conf_ap(dev, apdev):
9775 ssid = "wps-er-enrollee-to-conf-ap"
9776 ap_pin = "12345670"
9777 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
fab49f61
JM
9778 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9779 "wpa_passphrase": "12345678", "wpa": "2",
9780 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9781 "device_name": "Wireless AP", "manufacturer": "Company",
9782 "model_name": "WAP", "model_number": "123",
9783 "serial_number": "12345", "device_type": "6-0050F204-1",
9784 "os_version": "01020300",
9785 "config_methods": "label push_button",
9786 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
aed9e23a
JM
9787 hapd = hostapd.add_ap(apdev[0], params)
9788 bssid = hapd.own_addr()
9789
9790 id = dev[0].connect(ssid, psk="12345678", scan_freq="2412")
9791 dev[0].dump_monitor()
9792
9793 dev[0].request("WPS_ER_START ifname=lo")
9794 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
9795 if ev is None:
9796 raise Exception("AP discovery timed out")
9797 if ap_uuid not in ev:
9798 raise Exception("Expected AP UUID not found")
9799
9800 pin = dev[2].wps_read_pin()
9801 addr2 = dev[2].own_addr()
9802 dev[0].dump_monitor()
9803 dev[2].scan_for_bss(bssid, freq=2412)
9804 dev[2].dump_monitor()
9805 dev[2].request("WPS_PIN %s %s" % (bssid, pin))
9806
9807 for i in range(3):
9808 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
9809 if ev is None:
9810 raise Exception("Enrollee not seen")
9811 if addr2 in ev:
9812 break
9813 if addr2 not in ev:
9814 raise Exception("Unexpected Enrollee MAC address")
9815 dev[0].dump_monitor()
9816
9817 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " " + str(id))
9818 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
9819 dev[2].wait_connected(timeout=30)
9820 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
9821 if ev is None:
9822 raise Exception("WPS ER did not report success")
9823
9824def test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev):
9825 """WPS ER enrolling a new device to a configured AP (2)"""
9826 try:
9827 _test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev)
9828 finally:
9829 dev[0].request("WPS_ER_STOP")
9830
9831def _test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev):
9832 ssid = "wps-er-enrollee-to-conf-ap"
9833 ap_pin = "12345670"
9834 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
fab49f61
JM
9835 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9836 "wpa_passphrase": "12345678", "wpa": "2",
9837 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9838 "device_name": "Wireless AP", "manufacturer": "Company",
9839 "model_name": "WAP", "model_number": "123",
9840 "serial_number": "12345", "device_type": "6-0050F204-1",
9841 "os_version": "01020300",
9842 "config_methods": "label push_button",
9843 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
aed9e23a
JM
9844 hapd = hostapd.add_ap(apdev[0], params)
9845 bssid = hapd.own_addr()
9846
9847 id = dev[0].connect(ssid, psk="12345678", scan_freq="2412")
9848 dev[0].dump_monitor()
9849
9850 dev[0].request("WPS_ER_START ifname=lo")
9851 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
9852 if ev is None:
9853 raise Exception("AP discovery timed out")
9854 if ap_uuid not in ev:
9855 raise Exception("Expected AP UUID not found")
9856
9857 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
9858 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
9859 if ev is None:
9860 raise Exception("AP learn timed out")
9861 if ap_uuid not in ev:
9862 raise Exception("Expected AP UUID not in settings")
9863 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
9864 if ev is None:
9865 raise Exception("WPS-FAIL after AP learn timed out")
9866 time.sleep(0.1)
9867
9868 pin = dev[1].wps_read_pin()
9869 addr1 = dev[1].own_addr()
9870 dev[0].dump_monitor()
9871 dev[0].request("WPS_ER_PIN any " + pin)
9872 time.sleep(0.1)
9873 dev[1].scan_for_bss(bssid, freq=2412)
9874 dev[1].request("WPS_PIN any %s" % pin)
9875 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
9876 if ev is None:
9877 raise Exception("Enrollee did not report success")
9878 dev[1].wait_connected(timeout=15)
9879 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
9880 if ev is None:
9881 raise Exception("WPS ER did not report success")
5026406d
JM
9882
9883def test_ap_wps_ignore_broadcast_ssid(dev, apdev):
9884 """WPS AP trying to ignore broadcast SSID"""
9885 ssid = "test-wps"
9886 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
9887 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
9888 "ignore_broadcast_ssid": "1"})
5026406d
JM
9889 if "FAIL" not in hapd.request("WPS_PBC"):
9890 raise Exception("WPS unexpectedly enabled")
9891
9892def test_ap_wps_wep(dev, apdev):
9893 """WPS AP trying to enable WEP"""
9894 ssid = "test-wps"
9895 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
9896 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
9897 "ieee80211n": "0", "wep_key0": '"hello"'})
5026406d
JM
9898 if "FAIL" not in hapd.request("WPS_PBC"):
9899 raise Exception("WPS unexpectedly enabled")
9900
9901def test_ap_wps_tkip(dev, apdev):
9902 """WPS AP trying to enable TKIP"""
9903 ssid = "test-wps"
9904 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
9905 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
9906 "ieee80211n": "0", "wpa": '1',
9907 "wpa_key_mgmt": "WPA-PSK",
9908 "wpa_passphrase": "12345678"})
5026406d
JM
9909 if "FAIL" not in hapd.request("WPS_PBC"):
9910 raise Exception("WPS unexpectedly enabled")
454b66d2
JM
9911
9912def test_ap_wps_conf_dummy_cred(dev, apdev):
9913 """WPS PIN provisioning with configured AP using dummy cred"""
9914 ssid = "test-wps-conf"
9915 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
9916 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9917 "wpa_passphrase": "12345678", "wpa": "2",
9918 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
454b66d2
JM
9919 hapd.request("WPS_PIN any 12345670")
9920 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9921 dev[0].dump_monitor()
9922 try:
9923 hapd.set("wps_testing_dummy_cred", "1")
9924 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
9925 for i in range(1, 3):
9926 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
9927 if ev is None:
9928 raise Exception("WPS credential %d not received" % i)
9929 dev[0].wait_connected(timeout=30)
9930 finally:
9931 hapd.set("wps_testing_dummy_cred", "0")
cde2143c
JM
9932
9933def test_ap_wps_rf_bands(dev, apdev):
9934 """WPS and wps_rf_bands configuration"""
9935 ssid = "test-wps-conf"
fab49f61
JM
9936 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9937 "wpa_passphrase": "12345678", "wpa": "2",
9938 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9939 "wps_rf_bands": "ag"}
cde2143c
JM
9940
9941 hapd = hostapd.add_ap(apdev[0], params)
9942 bssid = hapd.own_addr()
9943 hapd.request("WPS_PBC")
9944 dev[0].scan_for_bss(bssid, freq="2412")
9945 dev[0].dump_monitor()
9946 dev[0].request("WPS_PBC " + bssid)
9947 dev[0].wait_connected(timeout=30)
9948 bss = dev[0].get_bss(bssid)
9949 logger.info("BSS: " + str(bss))
9950 if "103c000103" not in bss['ie']:
9951 raise Exception("RF Bands attribute with expected values not found")
9952 dev[0].request("DISCONNECT")
9953 dev[0].wait_disconnected()
9954 hapd.set("wps_rf_bands", "ad")
9955 hapd.set("wps_rf_bands", "a")
9956 hapd.set("wps_rf_bands", "g")
9957 hapd.set("wps_rf_bands", "b")
9958 hapd.set("wps_rf_bands", "ga")
9959 hapd.disable()
9960 dev[0].dump_monitor()
9961 dev[0].flush_scan_cache()
93b85d44
JM
9962
9963def test_ap_wps_pbc_in_m1(dev, apdev):
9964 """WPS and pbc_in_m1"""
9965 ssid = "test-wps-conf"
fab49f61
JM
9966 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9967 "wpa_passphrase": "12345678", "wpa": "2",
9968 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9969 "config_methods": "virtual_push_button virtual_display",
9970 "pbc_in_m1": "1"}
93b85d44
JM
9971
9972 hapd = hostapd.add_ap(apdev[0], params)
9973 bssid = hapd.own_addr()
9974 hapd.request("WPS_PBC")
9975 dev[0].scan_for_bss(bssid, freq="2412")
9976 dev[0].dump_monitor()
9977 dev[0].request("WPS_PBC " + bssid)
9978 dev[0].wait_connected(timeout=30)
9979 dev[0].request("DISCONNECT")
9980 dev[0].wait_disconnected()
9981 hapd.disable()
9982 dev[0].dump_monitor()
9983 dev[0].flush_scan_cache()
35320d7a 9984
97d2d7ac
MK
9985def test_ap_wps_pbc_mac_addr_change(dev, apdev, params):
9986 """WPS M1 with MAC address change"""
9987 ssid = "test-wps-mac-addr-change"
9988 hapd = hostapd.add_ap(apdev[0],
9989 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
9990 hapd.request("WPS_PBC")
9991 if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
9992 raise Exception("PBC status not shown correctly")
9993 dev[0].flush_scan_cache()
9994
9995 test_addr = '02:11:22:33:44:55'
9996 addr = dev[0].get_status_field("address")
9997 if addr == test_addr:
9998 raise Exception("Unexpected initial MAC address")
9999
10000 try:
10001 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'down'])
10002 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'address',
10003 test_addr])
10004 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'up'])
10005 addr1 = dev[0].get_status_field("address")
10006 if addr1 != test_addr:
10007 raise Exception("Failed to change MAC address")
10008
10009 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
10010 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
10011 dev[0].wait_connected(timeout=30)
10012 status = dev[0].get_status()
10013 if status['wpa_state'] != 'COMPLETED' or \
10014 status['bssid'] != apdev[0]['bssid']:
10015 raise Exception("Not fully connected")
10016
10017 out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
10018 "wps.message_type == 0x04",
10019 display=["wps.mac_address"])
10020 res = out.splitlines()
10021
10022 if len(res) < 1:
10023 raise Exception("No M1 message with MAC address found")
10024 if res[0] != addr1:
10025 raise Exception("Wrong M1 MAC address")
10026 dev[0].request("DISCONNECT")
10027 dev[0].wait_disconnected()
10028 hapd.disable()
10029 dev[0].dump_monitor()
10030 dev[0].flush_scan_cache()
10031 finally:
10032 # Restore MAC address
10033 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'down'])
10034 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'address',
10035 addr])
10036 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'up'])
10037
35320d7a
JM
10038def test_ap_wps_pin_start_failure(dev, apdev):
10039 """WPS_PIN start failure"""
10040 with alloc_fail(dev[0], 1, "wpas_wps_start_dev_pw"):
10041 if "FAIL" not in dev[0].request("WPS_PIN any 12345670"):
10042 raise Exception("WPS_PIN not rejected during OOM")
10043 with alloc_fail(dev[0], 1, "wpas_wps_start_dev_pw"):
10044 if "FAIL" not in dev[0].request("WPS_PIN any"):
10045 raise Exception("WPS_PIN not rejected during OOM")
cc5bf65f
JM
10046
10047def test_ap_wps_ap_pin_failure(dev, apdev):
10048 """WPS_AP_PIN failure"""
10049 id = dev[0].add_network()
10050 dev[0].set_network(id, "mode", "2")
10051 dev[0].set_network_quoted(id, "ssid", "wpas-ap-wps")
10052 dev[0].set_network_quoted(id, "psk", "1234567890")
10053 dev[0].set_network(id, "frequency", "2412")
10054 dev[0].set_network(id, "scan_freq", "2412")
10055 dev[0].select_network(id)
10056 dev[0].wait_connected()
10057
10058 with fail_test(dev[0], 1,
10059 "os_get_random;wpa_supplicant_ctrl_iface_wps_ap_pin"):
10060 if "FAIL" not in dev[0].request("WPS_AP_PIN random"):
10061 raise Exception("WPS_AP_PIN random accepted")
10062 with alloc_fail(dev[0], 1, "wpas_wps_ap_pin_set"):
10063 if "FAIL" not in dev[0].request("WPS_AP_PIN set 12345670"):
10064 raise Exception("WPS_AP_PIN set accepted")
10065
10066 dev[0].request("DISCONNECT")
10067 dev[0].wait_disconnected()
2087feb6
JM
10068
10069def test_ap_wps_random_uuid(dev, apdev, params):
10070 """WPS and random UUID on Enrollee"""
10071 ssid = "test-wps-conf"
10072 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
10073 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10074 "wpa_passphrase": "12345678", "wpa": "2",
10075 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2087feb6
JM
10076
10077 config = os.path.join(params['logdir'], 'ap_wps_random_uuid.conf')
10078 with open(config, "w") as f:
10079 f.write("auto_uuid=1\n")
10080
10081 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
10082
10083 uuid = []
10084 for i in range(3):
10085 wpas.interface_add("wlan5", config=config)
10086
10087 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
10088 wpas.dump_monitor()
10089 wpas.request("WPS_PBC " + apdev[0]['bssid'])
10090
10091 ev = hapd.wait_event(["WPS-ENROLLEE-SEEN"], timeout=10)
10092 if ev is None:
10093 raise Exception("Enrollee not seen")
10094 uuid.append(ev.split(' ')[2])
10095 wpas.request("WPS_CANCEL")
10096 wpas.dump_monitor()
10097
10098 wpas.interface_remove("wlan5")
10099
10100 hapd.dump_monitor()
10101
10102 logger.info("Seen UUIDs: " + str(uuid))
10103 if uuid[0] == uuid[1] or uuid[0] == uuid[2] or uuid[1] == uuid[2]:
10104 raise Exception("Same UUID used multiple times")
1fb0c105
JM
10105
10106def test_ap_wps_conf_pin_gcmp_128(dev, apdev):
10107 """WPS PIN provisioning with configured AP using GCMP-128"""
10108 run_ap_wps_conf_pin_cipher(dev, apdev, "GCMP")
10109
10110def test_ap_wps_conf_pin_gcmp_256(dev, apdev):
10111 """WPS PIN provisioning with configured AP using GCMP-256"""
10112 run_ap_wps_conf_pin_cipher(dev, apdev, "GCMP-256")
10113
10114def test_ap_wps_conf_pin_ccmp_256(dev, apdev):
10115 """WPS PIN provisioning with configured AP using CCMP-256"""
10116 run_ap_wps_conf_pin_cipher(dev, apdev, "CCMP-256")
10117
10118def run_ap_wps_conf_pin_cipher(dev, apdev, cipher):
10119 if cipher not in dev[0].get_capability("pairwise"):
10120 raise HwsimSkip("Cipher %s not supported" % cipher)
10121 ssid = "test-wps-conf-pin"
10122 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
10123 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10124 "wpa_passphrase": "12345678", "wpa": "2",
10125 "wpa_key_mgmt": "WPA-PSK",
10126 "rsn_pairwise": cipher})
1fb0c105
JM
10127 logger.info("WPS provisioning step")
10128 pin = dev[0].wps_read_pin()
10129 hapd.request("WPS_PIN any " + pin)
10130 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10131 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
10132 dev[0].wait_connected(timeout=15)
dc0f727c
JM
10133
10134def test_ap_wps_and_sae(dev, apdev):
10135 """Initial AP configuration with first WPS Enrollee and adding SAE"""
10136 try:
10137 run_ap_wps_and_sae(dev, apdev)
10138 finally:
10139 dev[0].set("wps_cred_add_sae", "0")
10140
10141def run_ap_wps_and_sae(dev, apdev):
10142 ssid = "test-wps-sae"
10143 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
10144 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
10145 "wps_cred_add_sae": "1"})
dc0f727c
JM
10146 logger.info("WPS provisioning step")
10147 pin = dev[0].wps_read_pin()
10148 hapd.request("WPS_PIN any " + pin)
10149
10150 dev[0].set("wps_cred_add_sae", "1")
96ad141e 10151 dev[0].request("SET sae_groups ")
dc0f727c
JM
10152 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
10153 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
10154 dev[0].wait_connected(timeout=30)
10155 status = dev[0].get_status()
10156 if status['key_mgmt'] != "SAE":
10157 raise Exception("SAE not used")
10158 if 'pmf' not in status or status['pmf'] != "1":
10159 raise Exception("PMF not enabled")
10160
10161 pin = dev[1].wps_read_pin()
10162 hapd.request("WPS_PIN any " + pin)
10163 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
10164 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
10165 dev[1].wait_connected(timeout=30)
10166 status = dev[1].get_status()
10167 if status['key_mgmt'] != "WPA2-PSK":
10168 raise Exception("WPA2-PSK not used")
10169 if 'pmf' in status:
10170 raise Exception("PMF enabled")
10171
10172def test_ap_wps_conf_and_sae(dev, apdev):
10173 """WPS PBC provisioning with configured AP using PSK+SAE"""
10174 try:
10175 run_ap_wps_conf_and_sae(dev, apdev)
10176 finally:
10177 dev[0].set("wps_cred_add_sae", "0")
10178
10179def run_ap_wps_conf_and_sae(dev, apdev):
10180 ssid = "test-wps-conf-sae"
10181 hapd = hostapd.add_ap(apdev[0],
fab49f61
JM
10182 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10183 "wpa_passphrase": "12345678", "wpa": "2",
10184 "ieee80211w": "1", "sae_require_mfp": "1",
10185 "wpa_key_mgmt": "WPA-PSK SAE",
10186 "rsn_pairwise": "CCMP"})
dc0f727c
JM
10187
10188 dev[0].set("wps_cred_add_sae", "1")
96ad141e 10189 dev[0].request("SET sae_groups ")
dc0f727c
JM
10190 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10191 pin = dev[0].wps_read_pin()
10192 hapd.request("WPS_PIN any " + pin)
10193 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
10194 dev[0].wait_connected(timeout=30)
10195 status = dev[0].get_status()
10196 if status['key_mgmt'] != "SAE":
10197 raise Exception("SAE not used")
10198 if 'pmf' not in status or status['pmf'] != "1":
10199 raise Exception("PMF not enabled")
10200
10201 dev[1].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
10202 key_mgmt="WPA-PSK", ieee80211w="0")
10203
10204def test_ap_wps_reg_config_and_sae(dev, apdev):
10205 """WPS registrar configuring an AP using AP PIN and using PSK+SAE"""
10206 try:
10207 run_ap_wps_reg_config_and_sae(dev, apdev)
10208 finally:
10209 dev[0].set("wps_cred_add_sae", "0")
10210
10211def run_ap_wps_reg_config_and_sae(dev, apdev):
10212 ssid = "test-wps-init-ap-pin-sae"
10213 appin = "12345670"
10214 hostapd.add_ap(apdev[0],
fab49f61
JM
10215 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10216 "ap_pin": appin, "wps_cred_add_sae": "1"})
dc0f727c
JM
10217 logger.info("WPS configuration step")
10218 dev[0].set("wps_cred_add_sae", "1")
96ad141e 10219 dev[0].request("SET sae_groups ")
dc0f727c
JM
10220 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
10221 dev[0].dump_monitor()
10222 new_ssid = "wps-new-ssid"
10223 new_passphrase = "1234567890"
10224 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
10225 new_passphrase)
10226 status = dev[0].get_status()
10227 if status['key_mgmt'] != "SAE":
10228 raise Exception("SAE not used")
10229 if 'pmf' not in status or status['pmf'] != "1":
10230 raise Exception("PMF not enabled")
10231
10232 dev[1].connect(new_ssid, psk=new_passphrase, scan_freq="2412", proto="WPA2",
10233 key_mgmt="WPA-PSK", ieee80211w="0")