9a4df5a87a43e41b9119c0da3610d754e1b03894
[mech_eap.git] / tests / hwsim / test_ap_wps.py
1 # WPS tests
2 # Copyright (c) 2013-2015, Jouni Malinen <j@w1.fi>
3 #
4 # This software may be distributed under the terms of the BSD license.
5 # See README for more details.
6
7 import base64
8 import binascii
9 from Crypto.Cipher import AES
10 import hashlib
11 import hmac
12 import os
13 import time
14 import stat
15 import subprocess
16 import logging
17 logger = logging.getLogger()
18 import re
19 import socket
20 import struct
21 import httplib
22 import urlparse
23 import urllib
24 import xml.etree.ElementTree as ET
25 import StringIO
26 import SocketServer
27
28 import hwsim_utils
29 import hostapd
30 from wpasupplicant import WpaSupplicant
31 from utils import HwsimSkip, alloc_fail, fail_test, skip_with_fips
32
33 def wps_start_ap(apdev, ssid="test-wps-conf"):
34     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
35                "wpa_passphrase": "12345678", "wpa": "2",
36                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
37     return hostapd.add_ap(apdev['ifname'], params)
38
39 def test_ap_wps_init(dev, apdev):
40     """Initial AP configuration with first WPS Enrollee"""
41     ssid = "test-wps"
42     hostapd.add_ap(apdev[0]['ifname'],
43                    { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
44     hapd = hostapd.Hostapd(apdev[0]['ifname'])
45     logger.info("WPS provisioning step")
46     hapd.request("WPS_PBC")
47     if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
48         raise Exception("PBC status not shown correctly")
49
50     id = dev[0].add_network()
51     dev[0].set_network_quoted(id, "ssid", "home")
52     dev[0].set_network_quoted(id, "psk", "12345678")
53     dev[0].request("ENABLE_NETWORK %s no-connect" % id)
54
55     id = dev[0].add_network()
56     dev[0].set_network_quoted(id, "ssid", "home2")
57     dev[0].set_network(id, "bssid", "00:11:22:33:44:55")
58     dev[0].set_network(id, "key_mgmt", "NONE")
59     dev[0].request("ENABLE_NETWORK %s no-connect" % id)
60
61     dev[0].request("WPS_PBC")
62     dev[0].wait_connected(timeout=30)
63     status = dev[0].get_status()
64     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
65         raise Exception("Not fully connected")
66     if status['ssid'] != ssid:
67         raise Exception("Unexpected SSID")
68     if status['pairwise_cipher'] != 'CCMP':
69         raise Exception("Unexpected encryption configuration")
70     if status['key_mgmt'] != 'WPA2-PSK':
71         raise Exception("Unexpected key_mgmt")
72
73     status = hapd.request("WPS_GET_STATUS")
74     if "PBC Status: Disabled" not in status:
75         raise Exception("PBC status not shown correctly")
76     if "Last WPS result: Success" not in status:
77         raise Exception("Last WPS result not shown correctly")
78     if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
79         raise Exception("Peer address not shown correctly")
80     conf = hapd.request("GET_CONFIG")
81     if "wps_state=configured" not in conf:
82         raise Exception("AP not in WPS configured state")
83     if "wpa=3" not in conf:
84         raise Exception("AP not in WPA+WPA2 configuration")
85     if "rsn_pairwise_cipher=CCMP TKIP" not in conf:
86         raise Exception("Unexpected rsn_pairwise_cipher")
87     if "wpa_pairwise_cipher=CCMP TKIP" not in conf:
88         raise Exception("Unexpected wpa_pairwise_cipher")
89     if "group_cipher=TKIP" not in conf:
90         raise Exception("Unexpected group_cipher")
91
92     if len(dev[0].list_networks()) != 3:
93         raise Exception("Unexpected number of network blocks")
94
95 def test_ap_wps_init_2ap_pbc(dev, apdev):
96     """Initial two-radio AP configuration with first WPS PBC Enrollee"""
97     ssid = "test-wps"
98     params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
99     hostapd.add_ap(apdev[0]['ifname'], params)
100     hostapd.add_ap(apdev[1]['ifname'], params)
101     hapd = hostapd.Hostapd(apdev[0]['ifname'])
102     logger.info("WPS provisioning step")
103     hapd.request("WPS_PBC")
104     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
105     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
106     bss = dev[0].get_bss(apdev[0]['bssid'])
107     if "[WPS-PBC]" not in bss['flags']:
108         raise Exception("WPS-PBC flag missing from AP1")
109     bss = dev[0].get_bss(apdev[1]['bssid'])
110     if "[WPS-PBC]" not in bss['flags']:
111         raise Exception("WPS-PBC flag missing from AP2")
112     dev[0].dump_monitor()
113     dev[0].request("SET wps_cred_processing 2")
114     dev[0].request("WPS_PBC")
115     ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=30)
116     dev[0].request("SET wps_cred_processing 0")
117     if ev is None:
118         raise Exception("WPS cred event not seen")
119     if "100e" not in ev:
120         raise Exception("WPS attributes not included in the cred event")
121     dev[0].wait_connected(timeout=30)
122
123     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
124     dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
125     bss = dev[1].get_bss(apdev[0]['bssid'])
126     if "[WPS-PBC]" in bss['flags']:
127         raise Exception("WPS-PBC flag not cleared from AP1")
128     bss = dev[1].get_bss(apdev[1]['bssid'])
129     if "[WPS-PBC]" in bss['flags']:
130         raise Exception("WPS-PBC flag not cleared from AP2")
131
132 def test_ap_wps_init_2ap_pin(dev, apdev):
133     """Initial two-radio AP configuration with first WPS PIN Enrollee"""
134     ssid = "test-wps"
135     params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
136     hostapd.add_ap(apdev[0]['ifname'], params)
137     hostapd.add_ap(apdev[1]['ifname'], params)
138     hapd = hostapd.Hostapd(apdev[0]['ifname'])
139     logger.info("WPS provisioning step")
140     pin = dev[0].wps_read_pin()
141     hapd.request("WPS_PIN any " + pin)
142     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
143     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
144     bss = dev[0].get_bss(apdev[0]['bssid'])
145     if "[WPS-AUTH]" not in bss['flags']:
146         raise Exception("WPS-AUTH flag missing from AP1")
147     bss = dev[0].get_bss(apdev[1]['bssid'])
148     if "[WPS-AUTH]" not in bss['flags']:
149         raise Exception("WPS-AUTH flag missing from AP2")
150     dev[0].dump_monitor()
151     dev[0].request("WPS_PIN any " + pin)
152     dev[0].wait_connected(timeout=30)
153
154     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
155     dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
156     bss = dev[1].get_bss(apdev[0]['bssid'])
157     if "[WPS-AUTH]" in bss['flags']:
158         raise Exception("WPS-AUTH flag not cleared from AP1")
159     bss = dev[1].get_bss(apdev[1]['bssid'])
160     if "[WPS-AUTH]" in bss['flags']:
161         raise Exception("WPS-AUTH flag not cleared from AP2")
162
163 def test_ap_wps_init_through_wps_config(dev, apdev):
164     """Initial AP configuration using wps_config command"""
165     ssid = "test-wps-init-config"
166     hostapd.add_ap(apdev[0]['ifname'],
167                    { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
168     hapd = hostapd.Hostapd(apdev[0]['ifname'])
169     if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
170         raise Exception("WPS_CONFIG command failed")
171     ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
172     if ev is None:
173         raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
174     # It takes some time for the AP to update Beacon and Probe Response frames,
175     # so wait here before requesting the scan to be started to avoid adding
176     # extra five second wait to the test due to fetching obsolete scan results.
177     hapd.ping()
178     time.sleep(0.2)
179     dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
180                    pairwise="CCMP", group="CCMP")
181
182 def test_ap_wps_init_through_wps_config_2(dev, apdev):
183     """AP configuration using wps_config and wps_cred_processing=2"""
184     ssid = "test-wps-init-config"
185     hostapd.add_ap(apdev[0]['ifname'],
186                    { "ssid": ssid, "eap_server": "1", "wps_state": "1",
187                      "wps_cred_processing": "2" })
188     hapd = hostapd.Hostapd(apdev[0]['ifname'])
189     if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
190         raise Exception("WPS_CONFIG command failed")
191     ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
192     if ev is None:
193         raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
194     if "100e" not in ev:
195         raise Exception("WPS-NEW-AP-SETTINGS did not include Credential")
196
197 def test_ap_wps_invalid_wps_config_passphrase(dev, apdev):
198     """AP configuration using wps_config command with invalid passphrase"""
199     ssid = "test-wps-init-config"
200     hostapd.add_ap(apdev[0]['ifname'],
201                    { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
202     hapd = hostapd.Hostapd(apdev[0]['ifname'])
203     if "FAIL" not in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "1234567".encode("hex")):
204         raise Exception("Invalid WPS_CONFIG command accepted")
205
206 def test_ap_wps_conf(dev, apdev):
207     """WPS PBC provisioning with configured AP"""
208     ssid = "test-wps-conf"
209     hostapd.add_ap(apdev[0]['ifname'],
210                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
211                      "wpa_passphrase": "12345678", "wpa": "2",
212                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
213     hapd = hostapd.Hostapd(apdev[0]['ifname'])
214     logger.info("WPS provisioning step")
215     hapd.request("WPS_PBC")
216     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
217     dev[0].dump_monitor()
218     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
219     dev[0].wait_connected(timeout=30)
220     status = dev[0].get_status()
221     if status['wpa_state'] != 'COMPLETED':
222         raise Exception("Not fully connected")
223     if status['bssid'] != apdev[0]['bssid']:
224         raise Exception("Unexpected BSSID")
225     if status['ssid'] != ssid:
226         raise Exception("Unexpected SSID")
227     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
228         raise Exception("Unexpected encryption configuration")
229     if status['key_mgmt'] != 'WPA2-PSK':
230         raise Exception("Unexpected key_mgmt")
231
232     sta = hapd.get_sta(dev[0].p2p_interface_addr())
233     if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
234         raise Exception("Device name not available in STA command")
235
236 def test_ap_wps_conf_5ghz(dev, apdev):
237     """WPS PBC provisioning with configured AP on 5 GHz band"""
238     try:
239         hapd = None
240         ssid = "test-wps-conf"
241         params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
242                    "wpa_passphrase": "12345678", "wpa": "2",
243                    "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
244                    "country_code": "FI", "hw_mode": "a", "channel": "36" }
245         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
246         logger.info("WPS provisioning step")
247         hapd.request("WPS_PBC")
248         dev[0].scan_for_bss(apdev[0]['bssid'], freq="5180")
249         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
250         dev[0].wait_connected(timeout=30)
251
252         sta = hapd.get_sta(dev[0].p2p_interface_addr())
253         if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
254             raise Exception("Device name not available in STA command")
255     finally:
256         dev[0].request("DISCONNECT")
257         if hapd:
258             hapd.request("DISABLE")
259         subprocess.call(['iw', 'reg', 'set', '00'])
260         dev[0].flush_scan_cache()
261
262 def test_ap_wps_conf_chan14(dev, apdev):
263     """WPS PBC provisioning with configured AP on channel 14"""
264     try:
265         hapd = None
266         ssid = "test-wps-conf"
267         params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
268                    "wpa_passphrase": "12345678", "wpa": "2",
269                    "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
270                    "country_code": "JP", "hw_mode": "b", "channel": "14" }
271         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
272         logger.info("WPS provisioning step")
273         hapd.request("WPS_PBC")
274         dev[0].request("WPS_PBC")
275         dev[0].wait_connected(timeout=30)
276
277         sta = hapd.get_sta(dev[0].p2p_interface_addr())
278         if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
279             raise Exception("Device name not available in STA command")
280     finally:
281         dev[0].request("DISCONNECT")
282         if hapd:
283             hapd.request("DISABLE")
284         subprocess.call(['iw', 'reg', 'set', '00'])
285         dev[0].flush_scan_cache()
286
287 def test_ap_wps_twice(dev, apdev):
288     """WPS provisioning with twice to change passphrase"""
289     ssid = "test-wps-twice"
290     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
291                "wpa_passphrase": "12345678", "wpa": "2",
292                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
293     hostapd.add_ap(apdev[0]['ifname'], params)
294     hapd = hostapd.Hostapd(apdev[0]['ifname'])
295     logger.info("WPS provisioning step")
296     hapd.request("WPS_PBC")
297     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
298     dev[0].dump_monitor()
299     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
300     dev[0].wait_connected(timeout=30)
301     dev[0].request("DISCONNECT")
302
303     logger.info("Restart AP with different passphrase and re-run WPS")
304     hapd_global = hostapd.HostapdGlobal()
305     hapd_global.remove(apdev[0]['ifname'])
306     params['wpa_passphrase'] = 'another passphrase'
307     hostapd.add_ap(apdev[0]['ifname'], params)
308     hapd = hostapd.Hostapd(apdev[0]['ifname'])
309     logger.info("WPS provisioning step")
310     hapd.request("WPS_PBC")
311     dev[0].dump_monitor()
312     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
313     dev[0].wait_connected(timeout=30)
314     networks = dev[0].list_networks()
315     if len(networks) > 1:
316         raise Exception("Unexpected duplicated network block present")
317
318 def test_ap_wps_incorrect_pin(dev, apdev):
319     """WPS PIN provisioning with incorrect PIN"""
320     ssid = "test-wps-incorrect-pin"
321     hostapd.add_ap(apdev[0]['ifname'],
322                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
323                      "wpa_passphrase": "12345678", "wpa": "2",
324                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
325     hapd = hostapd.Hostapd(apdev[0]['ifname'])
326
327     logger.info("WPS provisioning attempt 1")
328     hapd.request("WPS_PIN any 12345670")
329     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
330     dev[0].dump_monitor()
331     dev[0].request("WPS_PIN %s 55554444" % apdev[0]['bssid'])
332     ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
333     if ev is None:
334         raise Exception("WPS operation timed out")
335     if "config_error=18" not in ev:
336         raise Exception("Incorrect config_error reported")
337     if "msg=8" not in ev:
338         raise Exception("PIN error detected on incorrect message")
339     dev[0].wait_disconnected(timeout=10)
340     dev[0].request("WPS_CANCEL")
341     # if a scan was in progress, wait for it to complete before trying WPS again
342     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
343
344     status = hapd.request("WPS_GET_STATUS")
345     if "Last WPS result: Failed" not in status:
346         raise Exception("WPS failure result not shown correctly")
347
348     logger.info("WPS provisioning attempt 2")
349     hapd.request("WPS_PIN any 12345670")
350     dev[0].dump_monitor()
351     dev[0].request("WPS_PIN %s 12344444" % apdev[0]['bssid'])
352     ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
353     if ev is None:
354         raise Exception("WPS operation timed out")
355     if "config_error=18" not in ev:
356         raise Exception("Incorrect config_error reported")
357     if "msg=10" not in ev:
358         raise Exception("PIN error detected on incorrect message")
359     dev[0].wait_disconnected(timeout=10)
360
361 def test_ap_wps_conf_pin(dev, apdev):
362     """WPS PIN provisioning with configured AP"""
363     ssid = "test-wps-conf-pin"
364     hostapd.add_ap(apdev[0]['ifname'],
365                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
366                      "wpa_passphrase": "12345678", "wpa": "2",
367                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
368     hapd = hostapd.Hostapd(apdev[0]['ifname'])
369     logger.info("WPS provisioning step")
370     pin = dev[0].wps_read_pin()
371     hapd.request("WPS_PIN any " + pin)
372     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
373     dev[0].dump_monitor()
374     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
375     dev[0].wait_connected(timeout=30)
376     status = dev[0].get_status()
377     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
378         raise Exception("Not fully connected")
379     if status['ssid'] != ssid:
380         raise Exception("Unexpected SSID")
381     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
382         raise Exception("Unexpected encryption configuration")
383     if status['key_mgmt'] != 'WPA2-PSK':
384         raise Exception("Unexpected key_mgmt")
385
386     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
387     bss = dev[1].get_bss(apdev[0]['bssid'])
388     if "[WPS-AUTH]" in bss['flags']:
389         raise Exception("WPS-AUTH flag not cleared")
390     logger.info("Try to connect from another station using the same PIN")
391     pin = dev[1].request("WPS_PIN " + apdev[0]['bssid'])
392     ev = dev[1].wait_event(["WPS-M2D","CTRL-EVENT-CONNECTED"], timeout=30)
393     if ev is None:
394         raise Exception("Operation timed out")
395     if "WPS-M2D" not in ev:
396         raise Exception("Unexpected WPS operation started")
397     hapd.request("WPS_PIN any " + pin)
398     dev[1].wait_connected(timeout=30)
399
400 def test_ap_wps_conf_pin_v1(dev, apdev):
401     """WPS PIN provisioning with configured WPS v1.0 AP"""
402     ssid = "test-wps-conf-pin-v1"
403     hostapd.add_ap(apdev[0]['ifname'],
404                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
405                      "wpa_passphrase": "12345678", "wpa": "2",
406                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
407     hapd = hostapd.Hostapd(apdev[0]['ifname'])
408     logger.info("WPS provisioning step")
409     pin = dev[0].wps_read_pin()
410     hapd.request("SET wps_version_number 0x10")
411     hapd.request("WPS_PIN any " + pin)
412     found = False
413     for i in range(0, 10):
414         dev[0].scan(freq="2412")
415         if "[WPS-PIN]" in dev[0].request("SCAN_RESULTS"):
416             found = True
417             break
418     if not found:
419         hapd.request("SET wps_version_number 0x20")
420         raise Exception("WPS-PIN flag not seen in scan results")
421     dev[0].dump_monitor()
422     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
423     dev[0].wait_connected(timeout=30)
424     hapd.request("SET wps_version_number 0x20")
425
426 def test_ap_wps_conf_pin_2sta(dev, apdev):
427     """Two stations trying to use WPS PIN at the same time"""
428     ssid = "test-wps-conf-pin2"
429     hostapd.add_ap(apdev[0]['ifname'],
430                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
431                      "wpa_passphrase": "12345678", "wpa": "2",
432                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
433     hapd = hostapd.Hostapd(apdev[0]['ifname'])
434     logger.info("WPS provisioning step")
435     pin = "12345670"
436     pin2 = "55554444"
437     hapd.request("WPS_PIN " + dev[0].get_status_field("uuid") + " " + pin)
438     hapd.request("WPS_PIN " + dev[1].get_status_field("uuid") + " " + pin)
439     dev[0].dump_monitor()
440     dev[1].dump_monitor()
441     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
442     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
443     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
444     dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
445     dev[0].wait_connected(timeout=30)
446     dev[1].wait_connected(timeout=30)
447
448 def test_ap_wps_conf_pin_timeout(dev, apdev):
449     """WPS PIN provisioning with configured AP timing out PIN"""
450     ssid = "test-wps-conf-pin"
451     hostapd.add_ap(apdev[0]['ifname'],
452                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
453                      "wpa_passphrase": "12345678", "wpa": "2",
454                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
455     hapd = hostapd.Hostapd(apdev[0]['ifname'])
456     addr = dev[0].p2p_interface_addr()
457     pin = dev[0].wps_read_pin()
458     if "FAIL" not in hapd.request("WPS_PIN "):
459         raise Exception("Unexpected success on invalid WPS_PIN")
460     hapd.request("WPS_PIN any " + pin + " 1")
461     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
462     time.sleep(1.1)
463     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
464     ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=20)
465     if ev is None:
466         raise Exception("WPS-PIN-NEEDED event timed out")
467     ev = dev[0].wait_event(["WPS-M2D"])
468     if ev is None:
469         raise Exception("M2D not reported")
470     dev[0].request("WPS_CANCEL")
471
472     hapd.request("WPS_PIN any " + pin + " 20 " + addr)
473     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
474     dev[0].wait_connected(timeout=30)
475
476 def test_ap_wps_reg_connect(dev, apdev):
477     """WPS registrar using AP PIN to connect"""
478     ssid = "test-wps-reg-ap-pin"
479     appin = "12345670"
480     hostapd.add_ap(apdev[0]['ifname'],
481                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
482                      "wpa_passphrase": "12345678", "wpa": "2",
483                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
484                      "ap_pin": appin})
485     logger.info("WPS provisioning step")
486     dev[0].dump_monitor()
487     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
488     dev[0].wps_reg(apdev[0]['bssid'], appin)
489     status = dev[0].get_status()
490     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
491         raise Exception("Not fully connected")
492     if status['ssid'] != ssid:
493         raise Exception("Unexpected SSID")
494     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
495         raise Exception("Unexpected encryption configuration")
496     if status['key_mgmt'] != 'WPA2-PSK':
497         raise Exception("Unexpected key_mgmt")
498
499 def test_ap_wps_reg_connect_mixed_mode(dev, apdev):
500     """WPS registrar using AP PIN to connect (WPA+WPA2)"""
501     ssid = "test-wps-reg-ap-pin"
502     appin = "12345670"
503     hostapd.add_ap(apdev[0]['ifname'],
504                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
505                      "wpa_passphrase": "12345678", "wpa": "3",
506                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
507                      "wpa_pairwise": "TKIP", "ap_pin": appin})
508     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
509     dev[0].wps_reg(apdev[0]['bssid'], appin)
510     status = dev[0].get_status()
511     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
512         raise Exception("Not fully connected")
513     if status['ssid'] != ssid:
514         raise Exception("Unexpected SSID")
515     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
516         raise Exception("Unexpected encryption configuration")
517     if status['key_mgmt'] != 'WPA2-PSK':
518         raise Exception("Unexpected key_mgmt")
519
520 def test_ap_wps_reg_override_ap_settings(dev, apdev):
521     """WPS registrar and ap_settings override"""
522     ap_settings = "/tmp/ap_wps_reg_override_ap_settings"
523     try:
524         os.remove(ap_settings)
525     except:
526         pass
527     # Override AP Settings with values that point to another AP
528     data = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
529     data += build_wsc_attr(ATTR_SSID, "test")
530     data += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
531     data += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
532     data += build_wsc_attr(ATTR_NETWORK_KEY, '')
533     data += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[1]['bssid'].replace(':', '')))
534     with open(ap_settings, "w") as f:
535         f.write(data)
536     ssid = "test-wps-reg-ap-pin"
537     appin = "12345670"
538     hostapd.add_ap(apdev[0]['ifname'],
539                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
540                      "wpa_passphrase": "12345678", "wpa": "2",
541                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
542                      "ap_pin": appin, "ap_settings": ap_settings })
543     hapd2 = hostapd.add_ap(apdev[1]['ifname'], { "ssid": "test" })
544     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
545     dev[0].scan_for_bss(apdev[1]['bssid'], freq=2412)
546     dev[0].wps_reg(apdev[0]['bssid'], appin)
547     ev = hapd2.wait_event(['AP-STA-CONNECTED'], timeout=10)
548     os.remove(ap_settings)
549     if ev is None:
550         raise Exception("No connection with the other AP")
551
552 def check_wps_reg_failure(dev, ap, appin):
553     dev.request("WPS_REG " + ap['bssid'] + " " + appin)
554     ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
555     if ev is None:
556         raise Exception("WPS operation timed out")
557     if "WPS-SUCCESS" in ev:
558         raise Exception("WPS operation succeeded unexpectedly")
559     if "config_error=15" not in ev:
560         raise Exception("WPS setup locked state was not reported correctly")
561
562 def test_ap_wps_random_ap_pin(dev, apdev):
563     """WPS registrar using random AP PIN"""
564     ssid = "test-wps-reg-random-ap-pin"
565     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
566     hostapd.add_ap(apdev[0]['ifname'],
567                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
568                      "wpa_passphrase": "12345678", "wpa": "2",
569                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
570                      "device_name": "Wireless AP", "manufacturer": "Company",
571                      "model_name": "WAP", "model_number": "123",
572                      "serial_number": "12345", "device_type": "6-0050F204-1",
573                      "os_version": "01020300",
574                      "config_methods": "label push_button",
575                      "uuid": ap_uuid, "upnp_iface": "lo" })
576     hapd = hostapd.Hostapd(apdev[0]['ifname'])
577     appin = hapd.request("WPS_AP_PIN random")
578     if "FAIL" in appin:
579         raise Exception("Could not generate random AP PIN")
580     if appin not in hapd.request("WPS_AP_PIN get"):
581         raise Exception("Could not fetch current AP PIN")
582     logger.info("WPS provisioning step")
583     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
584     dev[0].wps_reg(apdev[0]['bssid'], appin)
585
586     hapd.request("WPS_AP_PIN disable")
587     logger.info("WPS provisioning step with AP PIN disabled")
588     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
589     check_wps_reg_failure(dev[1], apdev[0], appin)
590
591     logger.info("WPS provisioning step with AP PIN reset")
592     appin = "12345670"
593     hapd.request("WPS_AP_PIN set " + appin)
594     dev[1].wps_reg(apdev[0]['bssid'], appin)
595     dev[0].request("REMOVE_NETWORK all")
596     dev[1].request("REMOVE_NETWORK all")
597     dev[0].wait_disconnected(timeout=10)
598     dev[1].wait_disconnected(timeout=10)
599
600     logger.info("WPS provisioning step after AP PIN timeout")
601     hapd.request("WPS_AP_PIN disable")
602     appin = hapd.request("WPS_AP_PIN random 1")
603     time.sleep(1.1)
604     if "FAIL" not in hapd.request("WPS_AP_PIN get"):
605         raise Exception("AP PIN unexpectedly still enabled")
606     check_wps_reg_failure(dev[0], apdev[0], appin)
607
608     logger.info("WPS provisioning step after AP PIN timeout(2)")
609     hapd.request("WPS_AP_PIN disable")
610     appin = "12345670"
611     hapd.request("WPS_AP_PIN set " + appin + " 1")
612     time.sleep(1.1)
613     if "FAIL" not in hapd.request("WPS_AP_PIN get"):
614         raise Exception("AP PIN unexpectedly still enabled")
615     check_wps_reg_failure(dev[1], apdev[0], appin)
616
617     with fail_test(hapd, 1, "os_get_random;wps_generate_pin"):
618         if "FAIL" in hapd.request("WPS_AP_PIN random 1"):
619             raise Exception("Failed to generate PIN during OOM")
620         hapd.request("WPS_AP_PIN disable")
621
622     with alloc_fail(hapd, 1, "upnp_wps_set_ap_pin"):
623         hapd.request("WPS_AP_PIN set 12345670")
624         hapd.request("WPS_AP_PIN disable")
625
626 def test_ap_wps_reg_config(dev, apdev):
627     """WPS registrar configuring an AP using AP PIN"""
628     ssid = "test-wps-init-ap-pin"
629     appin = "12345670"
630     hostapd.add_ap(apdev[0]['ifname'],
631                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
632                      "ap_pin": appin})
633     logger.info("WPS configuration step")
634     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
635     dev[0].dump_monitor()
636     new_ssid = "wps-new-ssid"
637     new_passphrase = "1234567890"
638     dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
639                    new_passphrase)
640     status = dev[0].get_status()
641     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
642         raise Exception("Not fully connected")
643     if status['ssid'] != new_ssid:
644         raise Exception("Unexpected SSID")
645     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
646         raise Exception("Unexpected encryption configuration")
647     if status['key_mgmt'] != 'WPA2-PSK':
648         raise Exception("Unexpected key_mgmt")
649
650     logger.info("Re-configure back to open")
651     dev[0].request("REMOVE_NETWORK all")
652     dev[0].flush_scan_cache()
653     dev[0].dump_monitor()
654     dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-open", "OPEN", "NONE", "")
655     status = dev[0].get_status()
656     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
657         raise Exception("Not fully connected")
658     if status['ssid'] != "wps-open":
659         raise Exception("Unexpected SSID")
660     if status['key_mgmt'] != 'NONE':
661         raise Exception("Unexpected key_mgmt")
662
663 def test_ap_wps_reg_config_ext_processing(dev, apdev):
664     """WPS registrar configuring an AP with external config processing"""
665     ssid = "test-wps-init-ap-pin"
666     appin = "12345670"
667     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
668                "wps_cred_processing": "1", "ap_pin": appin}
669     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
670     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
671     new_ssid = "wps-new-ssid"
672     new_passphrase = "1234567890"
673     dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
674                    new_passphrase, no_wait=True)
675     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
676     if ev is None:
677         raise Exception("WPS registrar operation timed out")
678     ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=15)
679     if ev is None:
680         raise Exception("WPS configuration timed out")
681     if "1026" not in ev:
682         raise Exception("AP Settings missing from event")
683     hapd.request("SET wps_cred_processing 0")
684     if "FAIL" in hapd.request("WPS_CONFIG " + new_ssid.encode("hex") + " WPA2PSK CCMP " + new_passphrase.encode("hex")):
685         raise Exception("WPS_CONFIG command failed")
686     dev[0].wait_connected(timeout=15)
687
688 def test_ap_wps_reg_config_tkip(dev, apdev):
689     """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
690     skip_with_fips(dev[0])
691     ssid = "test-wps-init-ap"
692     appin = "12345670"
693     hostapd.add_ap(apdev[0]['ifname'],
694                    { "ssid": ssid, "eap_server": "1", "wps_state": "1",
695                      "ap_pin": appin})
696     logger.info("WPS configuration step")
697     dev[0].request("SET wps_version_number 0x10")
698     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
699     dev[0].dump_monitor()
700     new_ssid = "wps-new-ssid-with-tkip"
701     new_passphrase = "1234567890"
702     dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
703                    new_passphrase)
704     logger.info("Re-connect to verify WPA2 mixed mode")
705     dev[0].request("DISCONNECT")
706     id = 0
707     dev[0].set_network(id, "pairwise", "CCMP")
708     dev[0].set_network(id, "proto", "RSN")
709     dev[0].connect_network(id)
710     status = dev[0].get_status()
711     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
712         raise Exception("Not fully connected: wpa_state={} bssid={}".format(status['wpa_state'], status['bssid']))
713     if status['ssid'] != new_ssid:
714         raise Exception("Unexpected SSID")
715     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
716         raise Exception("Unexpected encryption configuration")
717     if status['key_mgmt'] != 'WPA2-PSK':
718         raise Exception("Unexpected key_mgmt")
719
720 def test_ap_wps_setup_locked(dev, apdev):
721     """WPS registrar locking up AP setup on AP PIN failures"""
722     ssid = "test-wps-incorrect-ap-pin"
723     appin = "12345670"
724     hostapd.add_ap(apdev[0]['ifname'],
725                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
726                      "wpa_passphrase": "12345678", "wpa": "2",
727                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
728                      "ap_pin": appin})
729     new_ssid = "wps-new-ssid-test"
730     new_passphrase = "1234567890"
731
732     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
733     ap_setup_locked=False
734     for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
735         dev[0].dump_monitor()
736         logger.info("Try incorrect AP PIN - attempt " + pin)
737         dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
738                        "CCMP", new_passphrase, no_wait=True)
739         ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
740         if ev is None:
741             raise Exception("Timeout on receiving WPS operation failure event")
742         if "CTRL-EVENT-CONNECTED" in ev:
743             raise Exception("Unexpected connection")
744         if "config_error=15" in ev:
745             logger.info("AP Setup Locked")
746             ap_setup_locked=True
747         elif "config_error=18" not in ev:
748             raise Exception("config_error=18 not reported")
749         dev[0].wait_disconnected(timeout=10)
750         time.sleep(0.1)
751     if not ap_setup_locked:
752         raise Exception("AP setup was not locked")
753     dev[0].request("WPS_CANCEL")
754     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True,
755                         only_new=True)
756     bss = dev[0].get_bss(apdev[0]['bssid'])
757     if 'wps_ap_setup_locked' not in bss or bss['wps_ap_setup_locked'] != '1':
758         logger.info("BSS: " + str(bss))
759         raise Exception("AP Setup Locked not indicated in scan results")
760
761     hapd = hostapd.Hostapd(apdev[0]['ifname'])
762     status = hapd.request("WPS_GET_STATUS")
763     if "Last WPS result: Failed" not in status:
764         raise Exception("WPS failure result not shown correctly")
765     if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
766         raise Exception("Peer address not shown correctly")
767
768     time.sleep(0.5)
769     dev[0].dump_monitor()
770     logger.info("WPS provisioning step")
771     pin = dev[0].wps_read_pin()
772     hapd = hostapd.Hostapd(apdev[0]['ifname'])
773     hapd.request("WPS_PIN any " + pin)
774     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
775     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
776     if ev is None:
777         raise Exception("WPS success was not reported")
778     dev[0].wait_connected(timeout=30)
779
780     appin = hapd.request("WPS_AP_PIN random")
781     if "FAIL" in appin:
782         raise Exception("Could not generate random AP PIN")
783     ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=10)
784     if ev is None:
785         raise Exception("Failed to unlock AP PIN")
786
787 def test_ap_wps_setup_locked_timeout(dev, apdev):
788     """WPS re-enabling AP PIN after timeout"""
789     ssid = "test-wps-incorrect-ap-pin"
790     appin = "12345670"
791     hostapd.add_ap(apdev[0]['ifname'],
792                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
793                      "wpa_passphrase": "12345678", "wpa": "2",
794                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
795                      "ap_pin": appin})
796     new_ssid = "wps-new-ssid-test"
797     new_passphrase = "1234567890"
798
799     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
800     ap_setup_locked=False
801     for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
802         dev[0].dump_monitor()
803         logger.info("Try incorrect AP PIN - attempt " + pin)
804         dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
805                        "CCMP", new_passphrase, no_wait=True)
806         ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"], timeout=15)
807         if ev is None:
808             raise Exception("Timeout on receiving WPS operation failure event")
809         if "CTRL-EVENT-CONNECTED" in ev:
810             raise Exception("Unexpected connection")
811         if "config_error=15" in ev:
812             logger.info("AP Setup Locked")
813             ap_setup_locked=True
814             break
815         elif "config_error=18" not in ev:
816             raise Exception("config_error=18 not reported")
817         dev[0].wait_disconnected(timeout=10)
818         time.sleep(0.1)
819     if not ap_setup_locked:
820         raise Exception("AP setup was not locked")
821     hapd = hostapd.Hostapd(apdev[0]['ifname'])
822     ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=80)
823     if ev is None:
824         raise Exception("AP PIN did not get unlocked on 60 second timeout")
825
826 def test_ap_wps_setup_locked_2(dev, apdev):
827     """WPS AP configured for special ap_setup_locked=2 mode"""
828     ssid = "test-wps-ap-pin"
829     appin = "12345670"
830     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
831                "wpa_passphrase": "12345678", "wpa": "2",
832                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
833                "ap_pin": appin, "ap_setup_locked": "2" }
834     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
835     new_ssid = "wps-new-ssid-test"
836     new_passphrase = "1234567890"
837
838     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
839     dev[0].wps_reg(apdev[0]['bssid'], appin)
840     dev[0].request("REMOVE_NETWORK all")
841     dev[0].wait_disconnected()
842
843     hapd.dump_monitor()
844     dev[0].dump_monitor()
845     dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK",
846                    "CCMP", new_passphrase, no_wait=True)
847
848     ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
849     if ev is None:
850         raise Exception("hostapd did not report WPS failure")
851     if "msg=12 config_error=15" not in ev:
852         raise Exception("Unexpected failure reason (AP): " + ev)
853
854     ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
855     if ev is None:
856         raise Exception("Timeout on receiving WPS operation failure event")
857     if "CTRL-EVENT-CONNECTED" in ev:
858         raise Exception("Unexpected connection")
859     if "config_error=15" not in ev:
860         raise Exception("Unexpected failure reason (STA): " + ev)
861     dev[0].request("WPS_CANCEL")
862     dev[0].wait_disconnected()
863
864 def test_ap_wps_pbc_overlap_2ap(dev, apdev):
865     """WPS PBC session overlap with two active APs"""
866     hostapd.add_ap(apdev[0]['ifname'],
867                    { "ssid": "wps1", "eap_server": "1", "wps_state": "2",
868                      "wpa_passphrase": "12345678", "wpa": "2",
869                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
870                      "wps_independent": "1"})
871     hostapd.add_ap(apdev[1]['ifname'],
872                    { "ssid": "wps2", "eap_server": "1", "wps_state": "2",
873                      "wpa_passphrase": "123456789", "wpa": "2",
874                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
875                      "wps_independent": "1"})
876     hapd = hostapd.Hostapd(apdev[0]['ifname'])
877     hapd.request("WPS_PBC")
878     hapd2 = hostapd.Hostapd(apdev[1]['ifname'])
879     hapd2.request("WPS_PBC")
880     logger.info("WPS provisioning step")
881     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
882     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
883     dev[0].request("WPS_PBC")
884     ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
885     if ev is None:
886         raise Exception("PBC session overlap not detected")
887     hapd.request("DISABLE")
888     hapd2.request("DISABLE")
889     dev[0].flush_scan_cache()
890
891 def test_ap_wps_pbc_overlap_2sta(dev, apdev):
892     """WPS PBC session overlap with two active STAs"""
893     ssid = "test-wps-pbc-overlap"
894     hostapd.add_ap(apdev[0]['ifname'],
895                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
896                      "wpa_passphrase": "12345678", "wpa": "2",
897                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
898     hapd = hostapd.Hostapd(apdev[0]['ifname'])
899     logger.info("WPS provisioning step")
900     hapd.request("WPS_PBC")
901     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
902     dev[0].dump_monitor()
903     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
904     dev[1].dump_monitor()
905     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
906     dev[1].request("WPS_PBC " + apdev[0]['bssid'])
907     ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
908     if ev is None:
909         raise Exception("PBC session overlap not detected (dev0)")
910     if "config_error=12" not in ev:
911         raise Exception("PBC session overlap not correctly reported (dev0)")
912     dev[0].request("WPS_CANCEL")
913     dev[0].request("DISCONNECT")
914     ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
915     if ev is None:
916         raise Exception("PBC session overlap not detected (dev1)")
917     if "config_error=12" not in ev:
918         raise Exception("PBC session overlap not correctly reported (dev1)")
919     dev[1].request("WPS_CANCEL")
920     dev[1].request("DISCONNECT")
921     hapd.request("WPS_CANCEL")
922     ret = hapd.request("WPS_PBC")
923     if "FAIL" not in ret:
924         raise Exception("PBC mode allowed to be started while PBC overlap still active")
925     hapd.request("DISABLE")
926     dev[0].flush_scan_cache()
927     dev[1].flush_scan_cache()
928
929 def test_ap_wps_cancel(dev, apdev):
930     """WPS AP cancelling enabled config method"""
931     ssid = "test-wps-ap-cancel"
932     hostapd.add_ap(apdev[0]['ifname'],
933                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
934                      "wpa_passphrase": "12345678", "wpa": "2",
935                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
936     bssid = apdev[0]['bssid']
937     hapd = hostapd.Hostapd(apdev[0]['ifname'])
938
939     logger.info("Verify PBC enable/cancel")
940     hapd.request("WPS_PBC")
941     dev[0].scan(freq="2412")
942     dev[0].scan(freq="2412")
943     bss = dev[0].get_bss(apdev[0]['bssid'])
944     if "[WPS-PBC]" not in bss['flags']:
945         raise Exception("WPS-PBC flag missing")
946     if "FAIL" in hapd.request("WPS_CANCEL"):
947         raise Exception("WPS_CANCEL failed")
948     dev[0].scan(freq="2412")
949     dev[0].scan(freq="2412")
950     bss = dev[0].get_bss(apdev[0]['bssid'])
951     if "[WPS-PBC]" in bss['flags']:
952         raise Exception("WPS-PBC flag not cleared")
953
954     logger.info("Verify PIN enable/cancel")
955     hapd.request("WPS_PIN any 12345670")
956     dev[0].scan(freq="2412")
957     dev[0].scan(freq="2412")
958     bss = dev[0].get_bss(apdev[0]['bssid'])
959     if "[WPS-AUTH]" not in bss['flags']:
960         raise Exception("WPS-AUTH flag missing")
961     if "FAIL" in hapd.request("WPS_CANCEL"):
962         raise Exception("WPS_CANCEL failed")
963     dev[0].scan(freq="2412")
964     dev[0].scan(freq="2412")
965     bss = dev[0].get_bss(apdev[0]['bssid'])
966     if "[WPS-AUTH]" in bss['flags']:
967         raise Exception("WPS-AUTH flag not cleared")
968
969 def test_ap_wps_er_add_enrollee(dev, apdev):
970     """WPS ER configuring AP and adding a new enrollee using PIN"""
971     try:
972         _test_ap_wps_er_add_enrollee(dev, apdev)
973     finally:
974         dev[0].request("WPS_ER_STOP")
975
976 def _test_ap_wps_er_add_enrollee(dev, apdev):
977     ssid = "wps-er-add-enrollee"
978     ap_pin = "12345670"
979     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
980     hostapd.add_ap(apdev[0]['ifname'],
981                    { "ssid": ssid, "eap_server": "1", "wps_state": "1",
982                      "device_name": "Wireless AP", "manufacturer": "Company",
983                      "model_name": "WAP", "model_number": "123",
984                      "serial_number": "12345", "device_type": "6-0050F204-1",
985                      "os_version": "01020300",
986                      'friendly_name': "WPS AP - <>&'\" - TEST",
987                      "config_methods": "label push_button",
988                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
989     logger.info("WPS configuration step")
990     new_passphrase = "1234567890"
991     dev[0].dump_monitor()
992     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
993     dev[0].wps_reg(apdev[0]['bssid'], ap_pin, ssid, "WPA2PSK", "CCMP",
994                    new_passphrase)
995     status = dev[0].get_status()
996     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
997         raise Exception("Not fully connected")
998     if status['ssid'] != ssid:
999         raise Exception("Unexpected SSID")
1000     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
1001         raise Exception("Unexpected encryption configuration")
1002     if status['key_mgmt'] != 'WPA2-PSK':
1003         raise Exception("Unexpected key_mgmt")
1004
1005     logger.info("Start ER")
1006     dev[0].request("WPS_ER_START ifname=lo")
1007     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1008     if ev is None:
1009         raise Exception("AP discovery timed out")
1010     if ap_uuid not in ev:
1011         raise Exception("Expected AP UUID not found")
1012     if "|WPS AP - &lt;&gt;&amp;&apos;&quot; - TEST|Company|" not in ev:
1013         raise Exception("Expected friendly name not found")
1014
1015     logger.info("Learn AP configuration through UPnP")
1016     dev[0].dump_monitor()
1017     dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1018     ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1019     if ev is None:
1020         raise Exception("AP learn timed out")
1021     if ap_uuid not in ev:
1022         raise Exception("Expected AP UUID not in settings")
1023     if "ssid=" + ssid not in ev:
1024         raise Exception("Expected SSID not in settings")
1025     if "key=" + new_passphrase not in ev:
1026         raise Exception("Expected passphrase not in settings")
1027     ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1028     if ev is None:
1029         raise Exception("WPS-FAIL after AP learn timed out")
1030     time.sleep(0.1)
1031
1032     logger.info("Add Enrollee using ER")
1033     pin = dev[1].wps_read_pin()
1034     dev[0].dump_monitor()
1035     dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1036     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1037     dev[1].dump_monitor()
1038     dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1039     ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
1040     if ev is None:
1041         raise Exception("Enrollee did not report success")
1042     dev[1].wait_connected(timeout=15)
1043     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1044     if ev is None:
1045         raise Exception("WPS ER did not report success")
1046     hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1047
1048     logger.info("Add a specific Enrollee using ER")
1049     pin = dev[2].wps_read_pin()
1050     addr2 = dev[2].p2p_interface_addr()
1051     dev[0].dump_monitor()
1052     dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1053     dev[2].dump_monitor()
1054     dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1055     ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1056     if ev is None:
1057         raise Exception("Enrollee not seen")
1058     if addr2 not in ev:
1059         raise Exception("Unexpected Enrollee MAC address")
1060     dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
1061     dev[2].wait_connected(timeout=30)
1062     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1063     if ev is None:
1064         raise Exception("WPS ER did not report success")
1065
1066     logger.info("Verify registrar selection behavior")
1067     dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1068     dev[1].request("DISCONNECT")
1069     dev[1].wait_disconnected(timeout=10)
1070     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1071     dev[1].scan(freq="2412")
1072     bss = dev[1].get_bss(apdev[0]['bssid'])
1073     if "[WPS-AUTH]" not in bss['flags']:
1074         # It is possible for scan to miss an update especially when running
1075         # tests under load with multiple VMs, so allow another attempt.
1076         dev[1].scan(freq="2412")
1077         bss = dev[1].get_bss(apdev[0]['bssid'])
1078         if "[WPS-AUTH]" not in bss['flags']:
1079             raise Exception("WPS-AUTH flag missing")
1080
1081     logger.info("Stop ER")
1082     dev[0].dump_monitor()
1083     dev[0].request("WPS_ER_STOP")
1084     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
1085     if ev is None:
1086         raise Exception("WPS ER unsubscription timed out")
1087     # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
1088     # a bit before verifying that the scan results have changed.
1089     time.sleep(0.2)
1090
1091     for i in range(0, 10):
1092         dev[1].request("BSS_FLUSH 0")
1093         dev[1].scan(freq="2412", only_new=True)
1094         bss = dev[1].get_bss(apdev[0]['bssid'])
1095         if bss and 'flags' in bss and "[WPS-AUTH]" not in bss['flags']:
1096             break
1097         logger.debug("WPS-AUTH flag was still in place - wait a bit longer")
1098         time.sleep(0.1)
1099     if "[WPS-AUTH]" in bss['flags']:
1100         raise Exception("WPS-AUTH flag not removed")
1101
1102 def test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1103     """WPS ER adding a new enrollee identified by UUID"""
1104     try:
1105         _test_ap_wps_er_add_enrollee_uuid(dev, apdev)
1106     finally:
1107         dev[0].request("WPS_ER_STOP")
1108
1109 def _test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1110     ssid = "wps-er-add-enrollee"
1111     ap_pin = "12345670"
1112     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1113     hostapd.add_ap(apdev[0]['ifname'],
1114                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1115                      "wpa_passphrase": "12345678", "wpa": "2",
1116                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1117                      "device_name": "Wireless AP", "manufacturer": "Company",
1118                      "model_name": "WAP", "model_number": "123",
1119                      "serial_number": "12345", "device_type": "6-0050F204-1",
1120                      "os_version": "01020300",
1121                      "config_methods": "label push_button",
1122                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1123     logger.info("WPS configuration step")
1124     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1125     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1126
1127     logger.info("Start ER")
1128     dev[0].request("WPS_ER_START ifname=lo")
1129     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1130     if ev is None:
1131         raise Exception("AP discovery timed out")
1132     if ap_uuid not in ev:
1133         raise Exception("Expected AP UUID not found")
1134
1135     logger.info("Learn AP configuration through UPnP")
1136     dev[0].dump_monitor()
1137     dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1138     ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1139     if ev is None:
1140         raise Exception("AP learn timed out")
1141     if ap_uuid not in ev:
1142         raise Exception("Expected AP UUID not in settings")
1143     ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1144     if ev is None:
1145         raise Exception("WPS-FAIL after AP learn timed out")
1146     time.sleep(0.1)
1147
1148     logger.info("Add a specific Enrollee using ER (PBC/UUID)")
1149     addr1 = dev[1].p2p_interface_addr()
1150     dev[0].dump_monitor()
1151     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1152     dev[1].dump_monitor()
1153     dev[1].request("WPS_PBC %s" % apdev[0]['bssid'])
1154     ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1155     if ev is None:
1156         raise Exception("Enrollee not seen")
1157     if addr1 not in ev:
1158         raise Exception("Unexpected Enrollee MAC address")
1159     uuid = ev.split(' ')[1]
1160     dev[0].request("WPS_ER_PBC " + uuid)
1161     dev[1].wait_connected(timeout=30)
1162     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1163     if ev is None:
1164         raise Exception("WPS ER did not report success")
1165
1166     logger.info("Add a specific Enrollee using ER (PIN/UUID)")
1167     pin = dev[2].wps_read_pin()
1168     addr2 = dev[2].p2p_interface_addr()
1169     dev[0].dump_monitor()
1170     dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1171     dev[2].dump_monitor()
1172     dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1173     ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1174     if ev is None:
1175         raise Exception("Enrollee not seen")
1176     if addr2 not in ev:
1177         raise Exception("Unexpected Enrollee MAC address")
1178     uuid = ev.split(' ')[1]
1179     dev[0].request("WPS_ER_PIN " + uuid + " " + pin)
1180     dev[2].wait_connected(timeout=30)
1181     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1182     if ev is None:
1183         raise Exception("WPS ER did not report success")
1184
1185     ev = dev[0].wait_event(["WPS-ER-ENROLLEE-REMOVE"], timeout=15)
1186     if ev is None:
1187         raise Exception("No Enrollee STA entry timeout seen")
1188
1189     logger.info("Stop ER")
1190     dev[0].dump_monitor()
1191     dev[0].request("WPS_ER_STOP")
1192
1193 def test_ap_wps_er_multi_add_enrollee(dev, apdev):
1194     """Multiple WPS ERs adding a new enrollee using PIN"""
1195     try:
1196         _test_ap_wps_er_multi_add_enrollee(dev, apdev)
1197     finally:
1198         dev[0].request("WPS_ER_STOP")
1199
1200 def _test_ap_wps_er_multi_add_enrollee(dev, apdev):
1201     ssid = "wps-er-add-enrollee"
1202     ap_pin = "12345670"
1203     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1204     hostapd.add_ap(apdev[0]['ifname'],
1205                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1206                      "wpa_passphrase": "12345678", "wpa": "2",
1207                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1208                      "device_name": "Wireless AP", "manufacturer": "Company",
1209                      "model_name": "WAP", "model_number": "123",
1210                      "serial_number": "12345", "device_type": "6-0050F204-1",
1211                      "os_version": "01020300",
1212                      'friendly_name': "WPS AP",
1213                      "config_methods": "label push_button",
1214                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1215
1216     for i in range(2):
1217         dev[i].scan_for_bss(apdev[0]['bssid'], freq=2412)
1218         dev[i].wps_reg(apdev[0]['bssid'], ap_pin)
1219         dev[i].request("WPS_ER_START ifname=lo")
1220     for i in range(2):
1221         ev = dev[i].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1222         if ev is None:
1223             raise Exception("AP discovery timed out")
1224         dev[i].dump_monitor()
1225         dev[i].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1226         ev = dev[i].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1227         if ev is None:
1228             raise Exception("AP learn timed out")
1229         ev = dev[i].wait_event(["WPS-FAIL"], timeout=15)
1230         if ev is None:
1231             raise Exception("WPS-FAIL after AP learn timed out")
1232
1233     time.sleep(0.1)
1234
1235     pin = dev[2].wps_read_pin()
1236     addr = dev[2].own_addr()
1237     dev[0].dump_monitor()
1238     dev[0].request("WPS_ER_PIN any " + pin + " " + addr)
1239     dev[1].dump_monitor()
1240     dev[1].request("WPS_ER_PIN any " + pin + " " + addr)
1241
1242     dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1243     dev[2].dump_monitor()
1244     dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1245     ev = dev[2].wait_event(["WPS-SUCCESS"], timeout=30)
1246     if ev is None:
1247         raise Exception("Enrollee did not report success")
1248     dev[2].wait_connected(timeout=15)
1249
1250 def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1251     """WPS ER connected to AP and adding a new enrollee using PBC"""
1252     try:
1253         _test_ap_wps_er_add_enrollee_pbc(dev, apdev)
1254     finally:
1255         dev[0].request("WPS_ER_STOP")
1256
1257 def _test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1258     ssid = "wps-er-add-enrollee-pbc"
1259     ap_pin = "12345670"
1260     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1261     hostapd.add_ap(apdev[0]['ifname'],
1262                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1263                      "wpa_passphrase": "12345678", "wpa": "2",
1264                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1265                      "device_name": "Wireless AP", "manufacturer": "Company",
1266                      "model_name": "WAP", "model_number": "123",
1267                      "serial_number": "12345", "device_type": "6-0050F204-1",
1268                      "os_version": "01020300",
1269                      "config_methods": "label push_button",
1270                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1271     logger.info("Learn AP configuration")
1272     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1273     dev[0].dump_monitor()
1274     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1275     status = dev[0].get_status()
1276     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1277         raise Exception("Not fully connected")
1278
1279     logger.info("Start ER")
1280     dev[0].request("WPS_ER_START ifname=lo")
1281     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1282     if ev is None:
1283         raise Exception("AP discovery timed out")
1284     if ap_uuid not in ev:
1285         raise Exception("Expected AP UUID not found")
1286
1287     enrollee = dev[1].p2p_interface_addr()
1288
1289     if "FAIL-UNKNOWN-UUID" not in dev[0].request("WPS_ER_PBC " + enrollee):
1290         raise Exception("Unknown UUID not reported")
1291
1292     logger.info("Add Enrollee using ER and PBC")
1293     dev[0].dump_monitor()
1294     dev[1].dump_monitor()
1295     dev[1].request("WPS_PBC")
1296
1297     for i in range(0, 2):
1298         ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1299         if ev is None:
1300             raise Exception("Enrollee discovery timed out")
1301         if enrollee in ev:
1302             break
1303         if i == 1:
1304             raise Exception("Expected Enrollee not found")
1305     if "FAIL-NO-AP-SETTINGS" not in dev[0].request("WPS_ER_PBC " + enrollee):
1306         raise Exception("Unknown UUID not reported")
1307     logger.info("Use learned network configuration on ER")
1308     dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1309     if "OK" not in dev[0].request("WPS_ER_PBC " + enrollee):
1310         raise Exception("WPS_ER_PBC failed")
1311
1312     ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
1313     if ev is None:
1314         raise Exception("Enrollee did not report success")
1315     dev[1].wait_connected(timeout=15)
1316     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1317     if ev is None:
1318         raise Exception("WPS ER did not report success")
1319     hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1320
1321 def test_ap_wps_er_pbc_overlap(dev, apdev):
1322     """WPS ER connected to AP and PBC session overlap"""
1323     try:
1324         _test_ap_wps_er_pbc_overlap(dev, apdev)
1325     finally:
1326         dev[0].request("WPS_ER_STOP")
1327
1328 def _test_ap_wps_er_pbc_overlap(dev, apdev):
1329     ssid = "wps-er-add-enrollee-pbc"
1330     ap_pin = "12345670"
1331     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1332     hostapd.add_ap(apdev[0]['ifname'],
1333                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1334                      "wpa_passphrase": "12345678", "wpa": "2",
1335                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1336                      "device_name": "Wireless AP", "manufacturer": "Company",
1337                      "model_name": "WAP", "model_number": "123",
1338                      "serial_number": "12345", "device_type": "6-0050F204-1",
1339                      "os_version": "01020300",
1340                      "config_methods": "label push_button",
1341                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1342     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1343     dev[0].dump_monitor()
1344     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1345
1346     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1347     dev[2].scan_for_bss(apdev[0]['bssid'], freq="2412")
1348     # avoid leaving dev 1 or 2 as the last Probe Request to the AP
1349     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True)
1350
1351     dev[0].dump_monitor()
1352     dev[0].request("WPS_ER_START ifname=lo")
1353
1354     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1355     if ev is None:
1356         raise Exception("AP discovery timed out")
1357     if ap_uuid not in ev:
1358         raise Exception("Expected AP UUID not found")
1359
1360     # verify BSSID selection of the AP instead of UUID
1361     if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
1362         raise Exception("Could not select AP based on BSSID")
1363
1364     dev[0].dump_monitor()
1365     dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1366     dev[2].request("WPS_PBC " + apdev[0]['bssid'])
1367     ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1368     if ev is None:
1369         raise Exception("PBC scan failed")
1370     ev = dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1371     if ev is None:
1372         raise Exception("PBC scan failed")
1373     found1 = False
1374     found2 = False
1375     addr1 = dev[1].own_addr()
1376     addr2 = dev[2].own_addr()
1377     for i in range(3):
1378         ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1379         if ev is None:
1380             raise Exception("Enrollee discovery timed out")
1381         if addr1 in ev:
1382             found1 = True
1383             if found2:
1384                 break
1385         if addr2 in ev:
1386             found2 = True
1387             if found1:
1388                 break
1389     if dev[0].request("WPS_ER_PBC " + ap_uuid) != "FAIL-PBC-OVERLAP\n":
1390         raise Exception("PBC overlap not reported")
1391     dev[1].request("WPS_CANCEL")
1392     dev[2].request("WPS_CANCEL")
1393     if dev[0].request("WPS_ER_PBC foo") != "FAIL\n":
1394         raise Exception("Invalid WPS_ER_PBC accepted")
1395
1396 def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1397     """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
1398     try:
1399         _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev)
1400     finally:
1401         dev[0].request("WPS_ER_STOP")
1402
1403 def _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1404     ssid = "wps-er-add-enrollee-pbc"
1405     ap_pin = "12345670"
1406     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1407     hostapd.add_ap(apdev[0]['ifname'],
1408                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1409                      "wpa_passphrase": "12345678", "wpa": "2",
1410                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1411                      "device_name": "Wireless AP", "manufacturer": "Company",
1412                      "model_name": "WAP", "model_number": "123",
1413                      "serial_number": "12345", "device_type": "6-0050F204-1",
1414                      "os_version": "01020300",
1415                      "config_methods": "label push_button",
1416                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1417     logger.info("Learn AP configuration")
1418     dev[0].request("SET wps_version_number 0x10")
1419     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1420     dev[0].dump_monitor()
1421     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1422     status = dev[0].get_status()
1423     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1424         raise Exception("Not fully connected")
1425
1426     logger.info("Start ER")
1427     dev[0].request("WPS_ER_START ifname=lo")
1428     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1429     if ev is None:
1430         raise Exception("AP discovery timed out")
1431     if ap_uuid not in ev:
1432         raise Exception("Expected AP UUID not found")
1433
1434     logger.info("Use learned network configuration on ER")
1435     dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1436
1437     logger.info("Add Enrollee using ER and PIN")
1438     enrollee = dev[1].p2p_interface_addr()
1439     pin = dev[1].wps_read_pin()
1440     dev[0].dump_monitor()
1441     dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
1442     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1443     dev[1].dump_monitor()
1444     dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1445     dev[1].wait_connected(timeout=30)
1446     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1447     if ev is None:
1448         raise Exception("WPS ER did not report success")
1449
1450 def test_ap_wps_er_config_ap(dev, apdev):
1451     """WPS ER configuring AP over UPnP"""
1452     try:
1453         _test_ap_wps_er_config_ap(dev, apdev)
1454     finally:
1455         dev[0].request("WPS_ER_STOP")
1456
1457 def _test_ap_wps_er_config_ap(dev, apdev):
1458     ssid = "wps-er-ap-config"
1459     ap_pin = "12345670"
1460     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1461     hostapd.add_ap(apdev[0]['ifname'],
1462                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1463                      "wpa_passphrase": "12345678", "wpa": "2",
1464                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1465                      "device_name": "Wireless AP", "manufacturer": "Company",
1466                      "model_name": "WAP", "model_number": "123",
1467                      "serial_number": "12345", "device_type": "6-0050F204-1",
1468                      "os_version": "01020300",
1469                      "config_methods": "label push_button",
1470                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1471
1472     logger.info("Connect ER to the AP")
1473     dev[0].connect(ssid, psk="12345678", scan_freq="2412")
1474
1475     logger.info("WPS configuration step")
1476     dev[0].request("WPS_ER_START ifname=lo")
1477     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1478     if ev is None:
1479         raise Exception("AP discovery timed out")
1480     if ap_uuid not in ev:
1481         raise Exception("Expected AP UUID not found")
1482     new_passphrase = "1234567890"
1483     dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
1484                    ssid.encode("hex") + " WPA2PSK CCMP " +
1485                    new_passphrase.encode("hex"))
1486     ev = dev[0].wait_event(["WPS-SUCCESS"])
1487     if ev is None:
1488         raise Exception("WPS ER configuration operation timed out")
1489     dev[0].wait_disconnected(timeout=10)
1490     dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
1491
1492     logger.info("WPS ER restart")
1493     dev[0].request("WPS_ER_START")
1494     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1495     if ev is None:
1496         raise Exception("AP discovery timed out on ER restart")
1497     if ap_uuid not in ev:
1498         raise Exception("Expected AP UUID not found on ER restart")
1499     if "OK" not in dev[0].request("WPS_ER_STOP"):
1500         raise Exception("WPS_ER_STOP failed")
1501     if "OK" not in dev[0].request("WPS_ER_STOP"):
1502         raise Exception("WPS_ER_STOP failed")
1503
1504 def test_ap_wps_er_cache_ap_settings(dev, apdev):
1505     """WPS ER caching AP settings"""
1506     try:
1507         _test_ap_wps_er_cache_ap_settings(dev, apdev)
1508     finally:
1509         dev[0].request("WPS_ER_STOP")
1510
1511 def _test_ap_wps_er_cache_ap_settings(dev, apdev):
1512     ssid = "wps-er-add-enrollee"
1513     ap_pin = "12345670"
1514     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1515     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1516                "wpa_passphrase": "12345678", "wpa": "2",
1517                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1518                "device_name": "Wireless AP", "manufacturer": "Company",
1519                "model_name": "WAP", "model_number": "123",
1520                "serial_number": "12345", "device_type": "6-0050F204-1",
1521                "os_version": "01020300",
1522                "config_methods": "label push_button",
1523                "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
1524     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1525     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1526     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1527     id = int(dev[0].list_networks()[0]['id'])
1528     dev[0].set_network(id, "scan_freq", "2412")
1529
1530     dev[0].request("WPS_ER_START ifname=lo")
1531     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1532     if ev is None:
1533         raise Exception("AP discovery timed out")
1534     if ap_uuid not in ev:
1535         raise Exception("Expected AP UUID not found")
1536
1537     dev[0].dump_monitor()
1538     dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1539     ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1540     if ev is None:
1541         raise Exception("AP learn timed out")
1542     ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1543     if ev is None:
1544         raise Exception("WPS-FAIL after AP learn timed out")
1545     time.sleep(0.1)
1546
1547     hapd.disable()
1548
1549     for i in range(2):
1550         ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1551                                  "CTRL-EVENT-DISCONNECTED" ],
1552                                timeout=15)
1553         if ev is None:
1554             raise Exception("AP removal or disconnection timed out")
1555
1556     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1557     for i in range(2):
1558         ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1559                                timeout=15)
1560         if ev is None:
1561             raise Exception("AP discovery or connection timed out")
1562
1563     pin = dev[1].wps_read_pin()
1564     dev[0].dump_monitor()
1565     dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1566
1567     time.sleep(0.2)
1568
1569     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1570     dev[1].dump_monitor()
1571     dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1572     ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
1573     if ev is None:
1574         raise Exception("Enrollee did not report success")
1575     dev[1].wait_connected(timeout=15)
1576     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1577     if ev is None:
1578         raise Exception("WPS ER did not report success")
1579
1580     dev[0].dump_monitor()
1581     dev[0].request("WPS_ER_STOP")
1582
1583 def test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1584     """WPS ER caching AP settings (OOM)"""
1585     try:
1586         _test_ap_wps_er_cache_ap_settings_oom(dev, apdev)
1587     finally:
1588         dev[0].request("WPS_ER_STOP")
1589
1590 def _test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1591     ssid = "wps-er-add-enrollee"
1592     ap_pin = "12345670"
1593     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1594     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1595                "wpa_passphrase": "12345678", "wpa": "2",
1596                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1597                "device_name": "Wireless AP", "manufacturer": "Company",
1598                "model_name": "WAP", "model_number": "123",
1599                "serial_number": "12345", "device_type": "6-0050F204-1",
1600                "os_version": "01020300",
1601                "config_methods": "label push_button",
1602                "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
1603     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1604     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1605     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1606     id = int(dev[0].list_networks()[0]['id'])
1607     dev[0].set_network(id, "scan_freq", "2412")
1608
1609     dev[0].request("WPS_ER_START ifname=lo")
1610     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1611     if ev is None:
1612         raise Exception("AP discovery timed out")
1613     if ap_uuid not in ev:
1614         raise Exception("Expected AP UUID not found")
1615
1616     dev[0].dump_monitor()
1617     dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1618     ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1619     if ev is None:
1620         raise Exception("AP learn timed out")
1621     ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1622     if ev is None:
1623         raise Exception("WPS-FAIL after AP learn timed out")
1624     time.sleep(0.1)
1625
1626     with alloc_fail(dev[0], 1, "=wps_er_ap_use_cached_settings"):
1627         hapd.disable()
1628
1629         for i in range(2):
1630             ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1631                                      "CTRL-EVENT-DISCONNECTED" ],
1632                                    timeout=15)
1633             if ev is None:
1634                 raise Exception("AP removal or disconnection timed out")
1635
1636         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1637         for i in range(2):
1638             ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1639                                    timeout=15)
1640             if ev is None:
1641                 raise Exception("AP discovery or connection timed out")
1642
1643     dev[0].request("WPS_ER_STOP")
1644
1645 def test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1646     """WPS ER caching AP settings (OOM 2)"""
1647     try:
1648         _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev)
1649     finally:
1650         dev[0].request("WPS_ER_STOP")
1651
1652 def _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1653     ssid = "wps-er-add-enrollee"
1654     ap_pin = "12345670"
1655     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1656     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1657                "wpa_passphrase": "12345678", "wpa": "2",
1658                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1659                "device_name": "Wireless AP", "manufacturer": "Company",
1660                "model_name": "WAP", "model_number": "123",
1661                "serial_number": "12345", "device_type": "6-0050F204-1",
1662                "os_version": "01020300",
1663                "config_methods": "label push_button",
1664                "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
1665     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1666     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1667     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1668     id = int(dev[0].list_networks()[0]['id'])
1669     dev[0].set_network(id, "scan_freq", "2412")
1670
1671     dev[0].request("WPS_ER_START ifname=lo")
1672     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1673     if ev is None:
1674         raise Exception("AP discovery timed out")
1675     if ap_uuid not in ev:
1676         raise Exception("Expected AP UUID not found")
1677
1678     dev[0].dump_monitor()
1679     dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1680     ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1681     if ev is None:
1682         raise Exception("AP learn timed out")
1683     ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1684     if ev is None:
1685         raise Exception("WPS-FAIL after AP learn timed out")
1686     time.sleep(0.1)
1687
1688     with alloc_fail(dev[0], 1, "=wps_er_ap_cache_settings"):
1689         hapd.disable()
1690
1691         for i in range(2):
1692             ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1693                                      "CTRL-EVENT-DISCONNECTED" ],
1694                                    timeout=15)
1695             if ev is None:
1696                 raise Exception("AP removal or disconnection timed out")
1697
1698         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1699         for i in range(2):
1700             ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1701                                    timeout=15)
1702             if ev is None:
1703                 raise Exception("AP discovery or connection timed out")
1704
1705     dev[0].request("WPS_ER_STOP")
1706
1707 def test_ap_wps_er_subscribe_oom(dev, apdev):
1708     """WPS ER subscribe OOM"""
1709     try:
1710         _test_ap_wps_er_subscribe_oom(dev, apdev)
1711     finally:
1712         dev[0].request("WPS_ER_STOP")
1713
1714 def _test_ap_wps_er_subscribe_oom(dev, apdev):
1715     ssid = "wps-er-add-enrollee"
1716     ap_pin = "12345670"
1717     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1718     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1719                "wpa_passphrase": "12345678", "wpa": "2",
1720                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1721                "device_name": "Wireless AP", "manufacturer": "Company",
1722                "model_name": "WAP", "model_number": "123",
1723                "serial_number": "12345", "device_type": "6-0050F204-1",
1724                "os_version": "01020300",
1725                "config_methods": "label push_button",
1726                "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
1727     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1728     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1729     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1730     id = int(dev[0].list_networks()[0]['id'])
1731     dev[0].set_network(id, "scan_freq", "2412")
1732
1733     with alloc_fail(dev[0], 1, "http_client_addr;wps_er_subscribe"):
1734         dev[0].request("WPS_ER_START ifname=lo")
1735         for i in range(50):
1736             res = dev[0].request("GET_ALLOC_FAIL")
1737             if res.startswith("0:"):
1738                 break
1739             time.sleep(0.1)
1740         ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=0)
1741         if ev:
1742             raise Exception("Unexpected AP discovery during OOM")
1743
1744     dev[0].request("WPS_ER_STOP")
1745
1746 def test_ap_wps_fragmentation(dev, apdev):
1747     """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
1748     ssid = "test-wps-fragmentation"
1749     appin = "12345670"
1750     hostapd.add_ap(apdev[0]['ifname'],
1751                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1752                      "wpa_passphrase": "12345678", "wpa": "3",
1753                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1754                      "wpa_pairwise": "TKIP", "ap_pin": appin,
1755                      "fragment_size": "50" })
1756     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1757     logger.info("WPS provisioning step (PBC)")
1758     hapd.request("WPS_PBC")
1759     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1760     dev[0].dump_monitor()
1761     dev[0].request("SET wps_fragment_size 50")
1762     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1763     dev[0].wait_connected(timeout=30)
1764     status = dev[0].get_status()
1765     if status['wpa_state'] != 'COMPLETED':
1766         raise Exception("Not fully connected")
1767     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1768         raise Exception("Unexpected encryption configuration")
1769     if status['key_mgmt'] != 'WPA2-PSK':
1770         raise Exception("Unexpected key_mgmt")
1771
1772     logger.info("WPS provisioning step (PIN)")
1773     pin = dev[1].wps_read_pin()
1774     hapd.request("WPS_PIN any " + pin)
1775     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1776     dev[1].request("SET wps_fragment_size 50")
1777     dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1778     dev[1].wait_connected(timeout=30)
1779     status = dev[1].get_status()
1780     if status['wpa_state'] != 'COMPLETED':
1781         raise Exception("Not fully connected")
1782     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1783         raise Exception("Unexpected encryption configuration")
1784     if status['key_mgmt'] != 'WPA2-PSK':
1785         raise Exception("Unexpected key_mgmt")
1786
1787     logger.info("WPS connection as registrar")
1788     dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1789     dev[2].request("SET wps_fragment_size 50")
1790     dev[2].wps_reg(apdev[0]['bssid'], appin)
1791     status = dev[2].get_status()
1792     if status['wpa_state'] != 'COMPLETED':
1793         raise Exception("Not fully connected")
1794     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1795         raise Exception("Unexpected encryption configuration")
1796     if status['key_mgmt'] != 'WPA2-PSK':
1797         raise Exception("Unexpected key_mgmt")
1798
1799 def test_ap_wps_new_version_sta(dev, apdev):
1800     """WPS compatibility with new version number on the station"""
1801     ssid = "test-wps-ver"
1802     hostapd.add_ap(apdev[0]['ifname'],
1803                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1804                      "wpa_passphrase": "12345678", "wpa": "2",
1805                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1806     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1807     logger.info("WPS provisioning step")
1808     hapd.request("WPS_PBC")
1809     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1810     dev[0].dump_monitor()
1811     dev[0].request("SET wps_version_number 0x43")
1812     dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
1813     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1814     dev[0].wait_connected(timeout=30)
1815
1816 def test_ap_wps_new_version_ap(dev, apdev):
1817     """WPS compatibility with new version number on the AP"""
1818     ssid = "test-wps-ver"
1819     hostapd.add_ap(apdev[0]['ifname'],
1820                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1821                      "wpa_passphrase": "12345678", "wpa": "2",
1822                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1823     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1824     logger.info("WPS provisioning step")
1825     if "FAIL" in hapd.request("SET wps_version_number 0x43"):
1826         raise Exception("Failed to enable test functionality")
1827     hapd.request("WPS_PBC")
1828     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1829     dev[0].dump_monitor()
1830     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1831     dev[0].wait_connected(timeout=30)
1832     hapd.request("SET wps_version_number 0x20")
1833
1834 def test_ap_wps_check_pin(dev, apdev):
1835     """Verify PIN checking through control interface"""
1836     hostapd.add_ap(apdev[0]['ifname'],
1837                    { "ssid": "wps", "eap_server": "1", "wps_state": "2",
1838                      "wpa_passphrase": "12345678", "wpa": "2",
1839                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1840     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1841     for t in [ ("12345670", "12345670"),
1842                ("12345678", "FAIL-CHECKSUM"),
1843                ("12345", "FAIL"),
1844                ("123456789", "FAIL"),
1845                ("1234-5670", "12345670"),
1846                ("1234 5670", "12345670"),
1847                ("1-2.3:4 5670", "12345670") ]:
1848         res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
1849         res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
1850         if res != res2:
1851             raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
1852         if res != t[1]:
1853             raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
1854
1855     if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
1856         raise Exception("Unexpected WPS_CHECK_PIN success")
1857     if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
1858         raise Exception("Unexpected WPS_CHECK_PIN success")
1859
1860     for i in range(0, 10):
1861         pin = dev[0].request("WPS_PIN get")
1862         rpin = dev[0].request("WPS_CHECK_PIN " + pin).rstrip('\n')
1863         if pin != rpin:
1864             raise Exception("Random PIN validation failed for " + pin)
1865
1866 def test_ap_wps_wep_config(dev, apdev):
1867     """WPS 2.0 AP rejecting WEP configuration"""
1868     ssid = "test-wps-config"
1869     appin = "12345670"
1870     hostapd.add_ap(apdev[0]['ifname'],
1871                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1872                      "ap_pin": appin})
1873     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1874     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1875     dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
1876                    "hello", no_wait=True)
1877     ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
1878     if ev is None:
1879         raise Exception("WPS-FAIL timed out")
1880     if "reason=2" not in ev:
1881         raise Exception("Unexpected reason code in WPS-FAIL")
1882     status = hapd.request("WPS_GET_STATUS")
1883     if "Last WPS result: Failed" not in status:
1884         raise Exception("WPS failure result not shown correctly")
1885     if "Failure Reason: WEP Prohibited" not in status:
1886         raise Exception("Failure reason not reported correctly")
1887     if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
1888         raise Exception("Peer address not shown correctly")
1889
1890 def test_ap_wps_wep_enroll(dev, apdev):
1891     """WPS 2.0 STA rejecting WEP configuration"""
1892     ssid = "test-wps-wep"
1893     hostapd.add_ap(apdev[0]['ifname'],
1894                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1895                      "skip_cred_build": "1", "extra_cred": "wps-wep-cred" })
1896     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1897     hapd.request("WPS_PBC")
1898     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1899     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1900     ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1901     if ev is None:
1902         raise Exception("WPS-FAIL event timed out")
1903     if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
1904         raise Exception("Unexpected WPS-FAIL event: " + ev)
1905
1906 def test_ap_wps_ie_fragmentation(dev, apdev):
1907     """WPS AP using fragmented WPS IE"""
1908     ssid = "test-wps-ie-fragmentation"
1909     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1910                "wpa_passphrase": "12345678", "wpa": "2",
1911                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1912                "device_name": "1234567890abcdef1234567890abcdef",
1913                "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
1914                "model_name": "1234567890abcdef1234567890abcdef",
1915                "model_number": "1234567890abcdef1234567890abcdef",
1916                "serial_number": "1234567890abcdef1234567890abcdef" }
1917     hostapd.add_ap(apdev[0]['ifname'], params)
1918     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1919     hapd.request("WPS_PBC")
1920     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1921     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1922     dev[0].wait_connected(timeout=30)
1923     bss = dev[0].get_bss(apdev[0]['bssid'])
1924     if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
1925         logger.info("Device Name not received correctly")
1926         logger.info(bss)
1927         # This can fail if Probe Response frame is missed and Beacon frame was
1928         # used to fill in the BSS entry. This can happen, e.g., during heavy
1929         # load every now and then and is not really an error, so try to
1930         # workaround by runnign another scan.
1931         dev[0].scan(freq="2412", only_new=True)
1932         bss = dev[0].get_bss(apdev[0]['bssid'])
1933         if not bss or "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
1934             logger.info(bss)
1935             raise Exception("Device Name not received correctly")
1936     if len(re.findall("dd..0050f204", bss['ie'])) != 2:
1937         raise Exception("Unexpected number of WPS IEs")
1938
1939 def get_psk(pskfile):
1940     psks = {}
1941     with open(pskfile, "r") as f:
1942         lines = f.read().splitlines()
1943         for l in lines:
1944             if l == "# WPA PSKs":
1945                 continue
1946             (addr,psk) = l.split(' ')
1947             psks[addr] = psk
1948     return psks
1949
1950 def test_ap_wps_per_station_psk(dev, apdev):
1951     """WPS PBC provisioning with per-station PSK"""
1952     addr0 = dev[0].own_addr()
1953     addr1 = dev[1].own_addr()
1954     addr2 = dev[2].own_addr()
1955     ssid = "wps"
1956     appin = "12345670"
1957     pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
1958     try:
1959         os.remove(pskfile)
1960     except:
1961         pass
1962
1963     try:
1964         with open(pskfile, "w") as f:
1965             f.write("# WPA PSKs\n")
1966
1967         params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1968                    "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
1969                    "rsn_pairwise": "CCMP", "ap_pin": appin,
1970                    "wpa_psk_file": pskfile }
1971         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1972
1973         logger.info("First enrollee")
1974         hapd.request("WPS_PBC")
1975         dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1976         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1977         dev[0].wait_connected(timeout=30)
1978
1979         logger.info("Second enrollee")
1980         hapd.request("WPS_PBC")
1981         dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1982         dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1983         dev[1].wait_connected(timeout=30)
1984
1985         logger.info("External registrar")
1986         dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1987         dev[2].wps_reg(apdev[0]['bssid'], appin)
1988
1989         logger.info("Verifying PSK results")
1990         psks = get_psk(pskfile)
1991         if addr0 not in psks:
1992             raise Exception("No PSK recorded for sta0")
1993         if addr1 not in psks:
1994             raise Exception("No PSK recorded for sta1")
1995         if addr2 not in psks:
1996             raise Exception("No PSK recorded for sta2")
1997         if psks[addr0] == psks[addr1]:
1998             raise Exception("Same PSK recorded for sta0 and sta1")
1999         if psks[addr0] == psks[addr2]:
2000             raise Exception("Same PSK recorded for sta0 and sta2")
2001         if psks[addr1] == psks[addr2]:
2002             raise Exception("Same PSK recorded for sta1 and sta2")
2003
2004         dev[0].request("REMOVE_NETWORK all")
2005         logger.info("Second external registrar")
2006         dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2007         dev[0].wps_reg(apdev[0]['bssid'], appin)
2008         psks2 = get_psk(pskfile)
2009         if addr0 not in psks2:
2010             raise Exception("No PSK recorded for sta0(reg)")
2011         if psks[addr0] == psks2[addr0]:
2012             raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
2013     finally:
2014         os.remove(pskfile)
2015
2016 def test_ap_wps_per_station_psk_failure(dev, apdev):
2017     """WPS PBC provisioning with per-station PSK (file not writable)"""
2018     addr0 = dev[0].p2p_dev_addr()
2019     addr1 = dev[1].p2p_dev_addr()
2020     addr2 = dev[2].p2p_dev_addr()
2021     ssid = "wps"
2022     appin = "12345670"
2023     pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2024     try:
2025         os.remove(pskfile)
2026     except:
2027         pass
2028
2029     try:
2030         with open(pskfile, "w") as f:
2031             f.write("# WPA PSKs\n")
2032
2033         params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2034                    "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2035                    "rsn_pairwise": "CCMP", "ap_pin": appin,
2036                    "wpa_psk_file": pskfile }
2037         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2038         if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
2039             raise Exception("Failed to set wpa_psk_file")
2040
2041         logger.info("First enrollee")
2042         hapd.request("WPS_PBC")
2043         dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2044         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2045         dev[0].wait_connected(timeout=30)
2046
2047         logger.info("Second enrollee")
2048         hapd.request("WPS_PBC")
2049         dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2050         dev[1].request("WPS_PBC " + apdev[0]['bssid'])
2051         dev[1].wait_connected(timeout=30)
2052
2053         logger.info("External registrar")
2054         dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2055         dev[2].wps_reg(apdev[0]['bssid'], appin)
2056
2057         logger.info("Verifying PSK results")
2058         psks = get_psk(pskfile)
2059         if len(psks) > 0:
2060             raise Exception("PSK recorded unexpectedly")
2061     finally:
2062         os.remove(pskfile)
2063
2064 def test_ap_wps_pin_request_file(dev, apdev):
2065     """WPS PIN provisioning with configured AP"""
2066     ssid = "wps"
2067     pinfile = "/tmp/ap_wps_pin_request_file.log"
2068     if os.path.exists(pinfile):
2069         os.remove(pinfile)
2070     hostapd.add_ap(apdev[0]['ifname'],
2071                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2072                      "wps_pin_requests": pinfile,
2073                      "wpa_passphrase": "12345678", "wpa": "2",
2074                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2075     hapd = hostapd.Hostapd(apdev[0]['ifname'])
2076     uuid = dev[0].get_status_field("uuid")
2077     pin = dev[0].wps_read_pin()
2078     try:
2079         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2080         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
2081         ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
2082         if ev is None:
2083             raise Exception("PIN needed event not shown")
2084         if uuid not in ev:
2085             raise Exception("UUID mismatch")
2086         dev[0].request("WPS_CANCEL")
2087         success = False
2088         with open(pinfile, "r") as f:
2089             lines = f.readlines()
2090             for l in lines:
2091                 if uuid in l:
2092                     success = True
2093                     break
2094         if not success:
2095             raise Exception("PIN request entry not in the log file")
2096     finally:
2097         try:
2098             os.remove(pinfile)
2099         except:
2100             pass
2101
2102 def test_ap_wps_auto_setup_with_config_file(dev, apdev):
2103     """WPS auto-setup with configuration file"""
2104     conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
2105     ifname = apdev[0]['ifname']
2106     try:
2107         with open(conffile, "w") as f:
2108             f.write("driver=nl80211\n")
2109             f.write("hw_mode=g\n")
2110             f.write("channel=1\n")
2111             f.write("ieee80211n=1\n")
2112             f.write("interface=%s\n" % ifname)
2113             f.write("ctrl_interface=/var/run/hostapd\n")
2114             f.write("ssid=wps\n")
2115             f.write("eap_server=1\n")
2116             f.write("wps_state=1\n")
2117         hostapd.add_bss('phy3', ifname, conffile)
2118         hapd = hostapd.Hostapd(ifname)
2119         hapd.request("WPS_PBC")
2120         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2121         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2122         dev[0].wait_connected(timeout=30)
2123         with open(conffile, "r") as f:
2124             lines = f.read().splitlines()
2125             vals = dict()
2126             for l in lines:
2127                 try:
2128                     [name,value] = l.split('=', 1)
2129                     vals[name] = value
2130                 except ValueError, e:
2131                     if "# WPS configuration" in l:
2132                         pass
2133                     else:
2134                         raise Exception("Unexpected configuration line: " + l)
2135         if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
2136             raise Exception("Incorrect configuration: " + str(vals))
2137     finally:
2138         try:
2139             os.remove(conffile)
2140         except:
2141             pass
2142
2143 def test_ap_wps_pbc_timeout(dev, apdev, params):
2144     """wpa_supplicant PBC walk time and WPS ER SelReg timeout [long]"""
2145     if not params['long']:
2146         raise HwsimSkip("Skip test case with long duration due to --long not specified")
2147     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2148     hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2149
2150     location = ssdp_get_location(ap_uuid)
2151     urls = upnp_get_urls(location)
2152     eventurl = urlparse.urlparse(urls['event_sub_url'])
2153     ctrlurl = urlparse.urlparse(urls['control_url'])
2154
2155     url = urlparse.urlparse(location)
2156     conn = httplib.HTTPConnection(url.netloc)
2157
2158     class WPSERHTTPServer(SocketServer.StreamRequestHandler):
2159         def handle(self):
2160             data = self.rfile.readline().strip()
2161             logger.debug(data)
2162             self.wfile.write(gen_wps_event())
2163
2164     server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
2165     server.timeout = 1
2166
2167     headers = { "callback": '<http://127.0.0.1:12345/event>',
2168                 "NT": "upnp:event",
2169                 "timeout": "Second-1234" }
2170     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2171     resp = conn.getresponse()
2172     if resp.status != 200:
2173         raise Exception("Unexpected HTTP response: %d" % resp.status)
2174     sid = resp.getheader("sid")
2175     logger.debug("Subscription SID " + sid)
2176
2177     msg = '''<?xml version="1.0"?>
2178 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
2179 <s:Body>
2180 <u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
2181 <NewMessage>EEoAARAQQQABARASAAIAABBTAAIxSBBJAA4ANyoAASABBv///////xBIABA2LbR7pTpRkYj7
2182 VFi5hrLk
2183 </NewMessage>
2184 </u:SetSelectedRegistrar>
2185 </s:Body>
2186 </s:Envelope>'''
2187     headers = { "Content-type": 'text/xml; charset="utf-8"' }
2188     headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
2189     conn.request("POST", ctrlurl.path, msg, headers)
2190     resp = conn.getresponse()
2191     if resp.status != 200:
2192         raise Exception("Unexpected HTTP response: %d" % resp.status)
2193
2194     server.handle_request()
2195
2196     logger.info("Start WPS_PBC and wait for PBC walk time expiration")
2197     if "OK" not in dev[0].request("WPS_PBC"):
2198         raise Exception("WPS_PBC failed")
2199
2200     start = os.times()[4]
2201
2202     server.handle_request()
2203     dev[1].request("BSS_FLUSH 0")
2204     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2205                         only_new=True)
2206     bss = dev[1].get_bss(apdev[0]['bssid'])
2207     logger.debug("BSS: " + str(bss))
2208     if '[WPS-AUTH]' not in bss['flags']:
2209         raise Exception("WPS not indicated authorized")
2210
2211     server.handle_request()
2212
2213     wps_timeout_seen = False
2214
2215     while True:
2216         hapd.dump_monitor()
2217         dev[1].dump_monitor()
2218         if not wps_timeout_seen:
2219             ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=0)
2220             if ev is not None:
2221                 logger.info("PBC timeout seen")
2222                 wps_timeout_seen = True
2223         else:
2224             dev[0].dump_monitor()
2225         now = os.times()[4]
2226         if now - start > 130:
2227             raise Exception("Selected registration information not removed")
2228         dev[1].request("BSS_FLUSH 0")
2229         dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2230                             only_new=True)
2231         bss = dev[1].get_bss(apdev[0]['bssid'])
2232         logger.debug("BSS: " + str(bss))
2233         if '[WPS-AUTH]' not in bss['flags']:
2234             break
2235         server.handle_request()
2236
2237     server.server_close()
2238
2239     if wps_timeout_seen:
2240         return
2241
2242     now = os.times()[4]
2243     if now < start + 150:
2244         dur = start + 150 - now
2245     else:
2246         dur = 1
2247     logger.info("Continue waiting for PBC timeout (%d sec)" % dur)
2248     ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=dur)
2249     if ev is None:
2250         raise Exception("WPS-TIMEOUT not reported")
2251
2252 def add_ssdp_ap(ifname, ap_uuid):
2253     ssid = "wps-ssdp"
2254     ap_pin = "12345670"
2255     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2256                "wpa_passphrase": "12345678", "wpa": "2",
2257                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2258                "device_name": "Wireless AP", "manufacturer": "Company",
2259                "model_name": "WAP", "model_number": "123",
2260                "serial_number": "12345", "device_type": "6-0050F204-1",
2261                "os_version": "01020300",
2262                "config_methods": "label push_button",
2263                "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
2264                "friendly_name": "WPS Access Point",
2265                "manufacturer_url": "http://www.example.com/",
2266                "model_description": "Wireless Access Point",
2267                "model_url": "http://www.example.com/model/",
2268                "upc": "123456789012" }
2269     return hostapd.add_ap(ifname, params)
2270
2271 def ssdp_send(msg, no_recv=False):
2272     socket.setdefaulttimeout(1)
2273     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2274     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2275     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2276     sock.bind(("127.0.0.1", 0))
2277     sock.sendto(msg, ("239.255.255.250", 1900))
2278     if no_recv:
2279         return None
2280     return sock.recv(1000)
2281
2282 def ssdp_send_msearch(st, no_recv=False):
2283     msg = '\r\n'.join([
2284             'M-SEARCH * HTTP/1.1',
2285             'HOST: 239.255.255.250:1900',
2286             'MX: 1',
2287             'MAN: "ssdp:discover"',
2288             'ST: ' + st,
2289             '', ''])
2290     return ssdp_send(msg, no_recv=no_recv)
2291
2292 def test_ap_wps_ssdp_msearch(dev, apdev):
2293     """WPS AP and SSDP M-SEARCH messages"""
2294     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2295     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2296
2297     msg = '\r\n'.join([
2298             'M-SEARCH * HTTP/1.1',
2299             'Host: 239.255.255.250:1900',
2300             'Mx: 1',
2301             'Man: "ssdp:discover"',
2302             'St: urn:schemas-wifialliance-org:device:WFADevice:1',
2303             '', ''])
2304     ssdp_send(msg)
2305
2306     msg = '\r\n'.join([
2307             'M-SEARCH * HTTP/1.1',
2308             'host:\t239.255.255.250:1900\t\t\t\t \t\t',
2309             'mx: \t1\t\t   ',
2310             'man: \t \t "ssdp:discover"   ',
2311             'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
2312             '', ''])
2313     ssdp_send(msg)
2314
2315     ssdp_send_msearch("ssdp:all")
2316     ssdp_send_msearch("upnp:rootdevice")
2317     ssdp_send_msearch("uuid:" + ap_uuid)
2318     ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
2319     ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1");
2320
2321     msg = '\r\n'.join([
2322             'M-SEARCH * HTTP/1.1',
2323             'HOST:\t239.255.255.250:1900',
2324             'MAN: "ssdp:discover"',
2325             'MX: 130',
2326             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2327             '', ''])
2328     ssdp_send(msg, no_recv=True)
2329
2330 def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
2331     """WPS AP and invalid SSDP M-SEARCH messages"""
2332     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2333     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2334
2335     socket.setdefaulttimeout(1)
2336     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2337     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2338     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2339     sock.bind(("127.0.0.1", 0))
2340
2341     logger.debug("Missing MX")
2342     msg = '\r\n'.join([
2343             'M-SEARCH * HTTP/1.1',
2344             'HOST: 239.255.255.250:1900',
2345             'MAN: "ssdp:discover"',
2346             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2347             '', ''])
2348     sock.sendto(msg, ("239.255.255.250", 1900))
2349
2350     logger.debug("Negative MX")
2351     msg = '\r\n'.join([
2352             'M-SEARCH * HTTP/1.1',
2353             'HOST: 239.255.255.250:1900',
2354             'MX: -1',
2355             'MAN: "ssdp:discover"',
2356             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2357             '', ''])
2358     sock.sendto(msg, ("239.255.255.250", 1900))
2359
2360     logger.debug("Invalid MX")
2361     msg = '\r\n'.join([
2362             'M-SEARCH * HTTP/1.1',
2363             'HOST: 239.255.255.250:1900',
2364             'MX; 1',
2365             'MAN: "ssdp:discover"',
2366             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2367             '', ''])
2368     sock.sendto(msg, ("239.255.255.250", 1900))
2369
2370     logger.debug("Missing MAN")
2371     msg = '\r\n'.join([
2372             'M-SEARCH * HTTP/1.1',
2373             'HOST: 239.255.255.250:1900',
2374             'MX: 1',
2375             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2376             '', ''])
2377     sock.sendto(msg, ("239.255.255.250", 1900))
2378
2379     logger.debug("Invalid MAN")
2380     msg = '\r\n'.join([
2381             'M-SEARCH * HTTP/1.1',
2382             'HOST: 239.255.255.250:1900',
2383             'MX: 1',
2384             'MAN: foo',
2385             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2386             '', ''])
2387     sock.sendto(msg, ("239.255.255.250", 1900))
2388     msg = '\r\n'.join([
2389             'M-SEARCH * HTTP/1.1',
2390             'HOST: 239.255.255.250:1900',
2391             'MX: 1',
2392             'MAN; "ssdp:discover"',
2393             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2394             '', ''])
2395     sock.sendto(msg, ("239.255.255.250", 1900))
2396
2397     logger.debug("Missing HOST")
2398     msg = '\r\n'.join([
2399             'M-SEARCH * HTTP/1.1',
2400             'MAN: "ssdp:discover"',
2401             'MX: 1',
2402             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2403             '', ''])
2404     sock.sendto(msg, ("239.255.255.250", 1900))
2405
2406     logger.debug("Missing ST")
2407     msg = '\r\n'.join([
2408             'M-SEARCH * HTTP/1.1',
2409             'HOST: 239.255.255.250:1900',
2410             'MAN: "ssdp:discover"',
2411             'MX: 1',
2412             '', ''])
2413     sock.sendto(msg, ("239.255.255.250", 1900))
2414
2415     logger.debug("Mismatching ST")
2416     msg = '\r\n'.join([
2417             'M-SEARCH * HTTP/1.1',
2418             'HOST: 239.255.255.250:1900',
2419             'MAN: "ssdp:discover"',
2420             'MX: 1',
2421             'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
2422             '', ''])
2423     sock.sendto(msg, ("239.255.255.250", 1900))
2424     msg = '\r\n'.join([
2425             'M-SEARCH * HTTP/1.1',
2426             'HOST: 239.255.255.250:1900',
2427             'MAN: "ssdp:discover"',
2428             'MX: 1',
2429             'ST: foo:bar',
2430             '', ''])
2431     sock.sendto(msg, ("239.255.255.250", 1900))
2432     msg = '\r\n'.join([
2433             'M-SEARCH * HTTP/1.1',
2434             'HOST: 239.255.255.250:1900',
2435             'MAN: "ssdp:discover"',
2436             'MX: 1',
2437             'ST: foobar',
2438             '', ''])
2439     sock.sendto(msg, ("239.255.255.250", 1900))
2440
2441     logger.debug("Invalid ST")
2442     msg = '\r\n'.join([
2443             'M-SEARCH * HTTP/1.1',
2444             'HOST: 239.255.255.250:1900',
2445             'MAN: "ssdp:discover"',
2446             'MX: 1',
2447             'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
2448             '', ''])
2449     sock.sendto(msg, ("239.255.255.250", 1900))
2450
2451     logger.debug("Invalid M-SEARCH")
2452     msg = '\r\n'.join([
2453             'M+SEARCH * HTTP/1.1',
2454             'HOST: 239.255.255.250:1900',
2455             'MAN: "ssdp:discover"',
2456             'MX: 1',
2457             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2458             '', ''])
2459     sock.sendto(msg, ("239.255.255.250", 1900))
2460     msg = '\r\n'.join([
2461             'M-SEARCH-* HTTP/1.1',
2462             'HOST: 239.255.255.250:1900',
2463             'MAN: "ssdp:discover"',
2464             'MX: 1',
2465             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2466             '', ''])
2467     sock.sendto(msg, ("239.255.255.250", 1900))
2468
2469     logger.debug("Invalid message format")
2470     sock.sendto("NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
2471     msg = '\r'.join([
2472             'M-SEARCH * HTTP/1.1',
2473             'HOST: 239.255.255.250:1900',
2474             'MAN: "ssdp:discover"',
2475             'MX: 1',
2476             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2477             '', ''])
2478     sock.sendto(msg, ("239.255.255.250", 1900))
2479
2480     try:
2481         r = sock.recv(1000)
2482         raise Exception("Unexpected M-SEARCH response: " + r)
2483     except socket.timeout:
2484         pass
2485
2486     logger.debug("Valid M-SEARCH")
2487     msg = '\r\n'.join([
2488             'M-SEARCH * HTTP/1.1',
2489             'HOST: 239.255.255.250:1900',
2490             'MAN: "ssdp:discover"',
2491             'MX: 1',
2492             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2493             '', ''])
2494     sock.sendto(msg, ("239.255.255.250", 1900))
2495
2496     try:
2497         r = sock.recv(1000)
2498         pass
2499     except socket.timeout:
2500         raise Exception("No SSDP response")
2501
2502 def test_ap_wps_ssdp_burst(dev, apdev):
2503     """WPS AP and SSDP burst"""
2504     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2505     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2506
2507     msg = '\r\n'.join([
2508             'M-SEARCH * HTTP/1.1',
2509             'HOST: 239.255.255.250:1900',
2510             'MAN: "ssdp:discover"',
2511             'MX: 1',
2512             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2513             '', ''])
2514     socket.setdefaulttimeout(1)
2515     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2516     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2517     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2518     sock.bind(("127.0.0.1", 0))
2519     for i in range(0, 25):
2520         sock.sendto(msg, ("239.255.255.250", 1900))
2521     resp = 0
2522     while True:
2523         try:
2524             r = sock.recv(1000)
2525             if not r.startswith("HTTP/1.1 200 OK\r\n"):
2526                 raise Exception("Unexpected message: " + r)
2527             resp += 1
2528         except socket.timeout:
2529             break
2530     if resp < 20:
2531         raise Exception("Too few SSDP responses")
2532
2533     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2534     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2535     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2536     sock.bind(("127.0.0.1", 0))
2537     for i in range(0, 25):
2538         sock.sendto(msg, ("239.255.255.250", 1900))
2539     while True:
2540         try:
2541             r = sock.recv(1000)
2542             if ap_uuid in r:
2543                 break
2544         except socket.timeout:
2545             raise Exception("No SSDP response")
2546
2547 def ssdp_get_location(uuid):
2548     res = ssdp_send_msearch("uuid:" + uuid)
2549     location = None
2550     for l in res.splitlines():
2551         if l.lower().startswith("location:"):
2552             location = l.split(':', 1)[1].strip()
2553             break
2554     if location is None:
2555         raise Exception("No UPnP location found")
2556     return location
2557
2558 def upnp_get_urls(location):
2559     conn = urllib.urlopen(location)
2560     tree = ET.parse(conn)
2561     root = tree.getroot()
2562     urn = '{urn:schemas-upnp-org:device-1-0}'
2563     service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
2564     res = {}
2565     res['scpd_url'] = urlparse.urljoin(location, service.find(urn + 'SCPDURL').text)
2566     res['control_url'] = urlparse.urljoin(location, service.find(urn + 'controlURL').text)
2567     res['event_sub_url'] = urlparse.urljoin(location, service.find(urn + 'eventSubURL').text)
2568     return res
2569
2570 def upnp_soap_action(conn, path, action, include_soap_action=True, soap_action_override=None):
2571     soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
2572     wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
2573     ET.register_namespace('soapenv', soapns)
2574     ET.register_namespace('wfa', wpsns)
2575     attrib = {}
2576     attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
2577     root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
2578     body = ET.SubElement(root, "{%s}Body" % soapns)
2579     act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
2580     tree = ET.ElementTree(root)
2581     soap = StringIO.StringIO()
2582     tree.write(soap, xml_declaration=True, encoding='utf-8')
2583
2584     headers = { "Content-type": 'text/xml; charset="utf-8"' }
2585     if include_soap_action:
2586         headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
2587     elif soap_action_override:
2588         headers["SOAPAction"] = soap_action_override
2589     conn.request("POST", path, soap.getvalue(), headers)
2590     return conn.getresponse()
2591
2592 def test_ap_wps_upnp(dev, apdev):
2593     """WPS AP and UPnP operations"""
2594     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2595     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2596
2597     location = ssdp_get_location(ap_uuid)
2598     urls = upnp_get_urls(location)
2599
2600     conn = urllib.urlopen(urls['scpd_url'])
2601     scpd = conn.read()
2602
2603     conn = urllib.urlopen(urlparse.urljoin(location, "unknown.html"))
2604     if conn.getcode() != 404:
2605         raise Exception("Unexpected HTTP response to GET unknown URL")
2606
2607     url = urlparse.urlparse(location)
2608     conn = httplib.HTTPConnection(url.netloc)
2609     #conn.set_debuglevel(1)
2610     headers = { "Content-type": 'text/xml; charset="utf-8"',
2611                 "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"' }
2612     conn.request("POST", "hello", "\r\n\r\n", headers)
2613     resp = conn.getresponse()
2614     if resp.status != 404:
2615         raise Exception("Unexpected HTTP response: %d" % resp.status)
2616
2617     conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
2618     resp = conn.getresponse()
2619     if resp.status != 501:
2620         raise Exception("Unexpected HTTP response: %d" % resp.status)
2621
2622     headers = { "Content-type": 'text/xml; charset="utf-8"',
2623                 "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"' }
2624     ctrlurl = urlparse.urlparse(urls['control_url'])
2625     conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
2626     resp = conn.getresponse()
2627     if resp.status != 401:
2628         raise Exception("Unexpected HTTP response: %d" % resp.status)
2629
2630     logger.debug("GetDeviceInfo without SOAPAction header")
2631     resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2632                             include_soap_action=False)
2633     if resp.status != 401:
2634         raise Exception("Unexpected HTTP response: %d" % resp.status)
2635
2636     logger.debug("GetDeviceInfo with invalid SOAPAction header")
2637     for act in [ "foo",
2638                  "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
2639                  '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
2640                  '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
2641         resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2642                                 include_soap_action=False,
2643                                 soap_action_override=act)
2644         if resp.status != 401:
2645             raise Exception("Unexpected HTTP response: %d" % resp.status)
2646
2647     resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
2648     if resp.status != 200:
2649         raise Exception("Unexpected HTTP response: %d" % resp.status)
2650     dev = resp.read()
2651     if "NewDeviceInfo" not in dev:
2652         raise Exception("Unexpected GetDeviceInfo response")
2653
2654     logger.debug("PutMessage without required parameters")
2655     resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
2656     if resp.status != 600:
2657         raise Exception("Unexpected HTTP response: %d" % resp.status)
2658
2659     logger.debug("PutWLANResponse without required parameters")
2660     resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
2661     if resp.status != 600:
2662         raise Exception("Unexpected HTTP response: %d" % resp.status)
2663
2664     logger.debug("SetSelectedRegistrar from unregistered ER")
2665     resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
2666     if resp.status != 501:
2667         raise Exception("Unexpected HTTP response: %d" % resp.status)
2668
2669     logger.debug("Unknown action")
2670     resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
2671     if resp.status != 401:
2672         raise Exception("Unexpected HTTP response: %d" % resp.status)
2673
2674 def test_ap_wps_upnp_subscribe(dev, apdev):
2675     """WPS AP and UPnP event subscription"""
2676     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2677     hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2678
2679     location = ssdp_get_location(ap_uuid)
2680     urls = upnp_get_urls(location)
2681     eventurl = urlparse.urlparse(urls['event_sub_url'])
2682
2683     url = urlparse.urlparse(location)
2684     conn = httplib.HTTPConnection(url.netloc)
2685     #conn.set_debuglevel(1)
2686     headers = { "callback": '<http://127.0.0.1:12345/event>',
2687                 "timeout": "Second-1234" }
2688     conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
2689     resp = conn.getresponse()
2690     if resp.status != 412:
2691         raise Exception("Unexpected HTTP response: %d" % resp.status)
2692
2693     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2694     resp = conn.getresponse()
2695     if resp.status != 412:
2696         raise Exception("Unexpected HTTP response: %d" % resp.status)
2697
2698     headers = { "NT": "upnp:event",
2699                 "timeout": "Second-1234" }
2700     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2701     resp = conn.getresponse()
2702     if resp.status != 412:
2703         raise Exception("Unexpected HTTP response: %d" % resp.status)
2704
2705     headers = { "callback": '<http://127.0.0.1:12345/event>',
2706                 "NT": "upnp:foobar",
2707                 "timeout": "Second-1234" }
2708     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2709     resp = conn.getresponse()
2710     if resp.status != 400:
2711         raise Exception("Unexpected HTTP response: %d" % resp.status)
2712
2713     logger.debug("Valid subscription")
2714     headers = { "callback": '<http://127.0.0.1:12345/event>',
2715                 "NT": "upnp:event",
2716                 "timeout": "Second-1234" }
2717     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2718     resp = conn.getresponse()
2719     if resp.status != 200:
2720         raise Exception("Unexpected HTTP response: %d" % resp.status)
2721     sid = resp.getheader("sid")
2722     logger.debug("Subscription SID " + sid)
2723
2724     logger.debug("Invalid re-subscription")
2725     headers = { "NT": "upnp:event",
2726                 "sid": "123456734567854",
2727                 "timeout": "Second-1234" }
2728     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2729     resp = conn.getresponse()
2730     if resp.status != 400:
2731         raise Exception("Unexpected HTTP response: %d" % resp.status)
2732
2733     logger.debug("Invalid re-subscription")
2734     headers = { "NT": "upnp:event",
2735                 "sid": "uuid:123456734567854",
2736                 "timeout": "Second-1234" }
2737     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2738     resp = conn.getresponse()
2739     if resp.status != 400:
2740         raise Exception("Unexpected HTTP response: %d" % resp.status)
2741
2742     logger.debug("Invalid re-subscription")
2743     headers = { "callback": '<http://127.0.0.1:12345/event>',
2744                 "NT": "upnp:event",
2745                 "sid": sid,
2746                 "timeout": "Second-1234" }
2747     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2748     resp = conn.getresponse()
2749     if resp.status != 400:
2750         raise Exception("Unexpected HTTP response: %d" % resp.status)
2751
2752     logger.debug("SID mismatch in re-subscription")
2753     headers = { "NT": "upnp:event",
2754                 "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
2755                 "timeout": "Second-1234" }
2756     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2757     resp = conn.getresponse()
2758     if resp.status != 412:
2759         raise Exception("Unexpected HTTP response: %d" % resp.status)
2760
2761     logger.debug("Valid re-subscription")
2762     headers = { "NT": "upnp:event",
2763                 "sid": sid,
2764                 "timeout": "Second-1234" }
2765     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2766     resp = conn.getresponse()
2767     if resp.status != 200:
2768         raise Exception("Unexpected HTTP response: %d" % resp.status)
2769     sid2 = resp.getheader("sid")
2770     logger.debug("Subscription SID " + sid2)
2771
2772     if sid != sid2:
2773         raise Exception("Unexpected SID change")
2774
2775     logger.debug("Valid re-subscription")
2776     headers = { "NT": "upnp:event",
2777                 "sid": "uuid: \t \t" + sid.split(':')[1],
2778                 "timeout": "Second-1234" }
2779     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2780     resp = conn.getresponse()
2781     if resp.status != 200:
2782         raise Exception("Unexpected HTTP response: %d" % resp.status)
2783
2784     logger.debug("Invalid unsubscription")
2785     headers = { "sid": sid }
2786     conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
2787     resp = conn.getresponse()
2788     if resp.status != 412:
2789         raise Exception("Unexpected HTTP response: %d" % resp.status)
2790     headers = { "foo": "bar" }
2791     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2792     resp = conn.getresponse()
2793     if resp.status != 412:
2794         raise Exception("Unexpected HTTP response: %d" % resp.status)
2795
2796     logger.debug("Valid unsubscription")
2797     headers = { "sid": sid }
2798     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2799     resp = conn.getresponse()
2800     if resp.status != 200:
2801         raise Exception("Unexpected HTTP response: %d" % resp.status)
2802
2803     logger.debug("Unsubscription for not existing SID")
2804     headers = { "sid": sid }
2805     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2806     resp = conn.getresponse()
2807     if resp.status != 412:
2808         raise Exception("Unexpected HTTP response: %d" % resp.status)
2809
2810     logger.debug("Invalid unsubscription")
2811     headers = { "sid": " \t \tfoo" }
2812     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2813     resp = conn.getresponse()
2814     if resp.status != 400:
2815         raise Exception("Unexpected HTTP response: %d" % resp.status)
2816
2817     logger.debug("Invalid unsubscription")
2818     headers = { "sid": "uuid:\t \tfoo" }
2819     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2820     resp = conn.getresponse()
2821     if resp.status != 400:
2822         raise Exception("Unexpected HTTP response: %d" % resp.status)
2823
2824     logger.debug("Invalid unsubscription")
2825     headers = { "NT": "upnp:event",
2826                 "sid": sid }
2827     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2828     resp = conn.getresponse()
2829     if resp.status != 400:
2830         raise Exception("Unexpected HTTP response: %d" % resp.status)
2831     headers = { "callback": '<http://127.0.0.1:12345/event>',
2832                 "sid": sid }
2833     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2834     resp = conn.getresponse()
2835     if resp.status != 400:
2836         raise Exception("Unexpected HTTP response: %d" % resp.status)
2837
2838     logger.debug("Valid subscription with multiple callbacks")
2839     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>',
2840                 "NT": "upnp:event",
2841                 "timeout": "Second-1234" }
2842     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2843     resp = conn.getresponse()
2844     if resp.status != 200:
2845         raise Exception("Unexpected HTTP response: %d" % resp.status)
2846     sid = resp.getheader("sid")
2847     logger.debug("Subscription SID " + sid)
2848
2849     # Force subscription to be deleted due to errors
2850     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2851     dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2852     with alloc_fail(hapd, 1, "event_build_message"):
2853         for i in range(10):
2854             dev[1].dump_monitor()
2855             dev[2].dump_monitor()
2856             dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2857             dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2858             dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2859             dev[1].request("WPS_CANCEL")
2860             dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2861             dev[2].request("WPS_CANCEL")
2862             if i % 4 == 1:
2863                 time.sleep(1)
2864             else:
2865                 time.sleep(0.1)
2866     time.sleep(0.2)
2867
2868     headers = { "sid": sid }
2869     conn.request("UNSUBSCRIBE", eventurl.path, "", headers)
2870     resp = conn.getresponse()
2871     if resp.status != 200 and resp.status != 412:
2872         raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
2873
2874     headers = { "callback": '<http://127.0.0.1:12345/event>',
2875                 "NT": "upnp:event",
2876                 "timeout": "Second-1234" }
2877     with alloc_fail(hapd, 1, "http_client_addr;event_send_start"):
2878         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2879         resp = conn.getresponse()
2880         if resp.status != 200:
2881             raise Exception("Unexpected HTTP response for SUBSCRIBE: %d" % resp.status)
2882         sid = resp.getheader("sid")
2883         logger.debug("Subscription SID " + sid)
2884
2885     headers = { "sid": sid }
2886     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2887     resp = conn.getresponse()
2888     if resp.status != 200:
2889         raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
2890
2891     headers = { "callback": '<http://127.0.0.1:12345/event>',
2892                 "NT": "upnp:event",
2893                 "timeout": "Second-1234" }
2894     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2895     resp = conn.getresponse()
2896     if resp.status != 200:
2897         raise Exception("Unexpected HTTP response: %d" % resp.status)
2898     sid = resp.getheader("sid")
2899     logger.debug("Subscription SID " + sid)
2900
2901     with alloc_fail(hapd, 1, "=event_add"):
2902         for i in range(2):
2903             dev[1].dump_monitor()
2904             dev[2].dump_monitor()
2905             dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2906             dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2907             dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2908             dev[1].request("WPS_CANCEL")
2909             dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2910             dev[2].request("WPS_CANCEL")
2911             if i == 0:
2912                 time.sleep(1)
2913             else:
2914                 time.sleep(0.1)
2915
2916     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2917     resp = conn.getresponse()
2918     if resp.status != 200:
2919         raise Exception("Unexpected HTTP response: %d" % resp.status)
2920
2921     with alloc_fail(hapd, 1, "wpabuf_dup;event_add"):
2922         dev[1].dump_monitor()
2923         dev[2].dump_monitor()
2924         dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2925         dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2926         dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2927         dev[1].request("WPS_CANCEL")
2928         dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2929         dev[2].request("WPS_CANCEL")
2930         time.sleep(0.1)
2931
2932     with fail_test(hapd, 1, "os_get_random;uuid_make;subscription_start"):
2933         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2934         resp = conn.getresponse()
2935         if resp.status != 500:
2936             raise Exception("Unexpected HTTP response: %d" % resp.status)
2937
2938     with alloc_fail(hapd, 1, "=subscription_start"):
2939         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2940         resp = conn.getresponse()
2941         if resp.status != 500:
2942             raise Exception("Unexpected HTTP response: %d" % resp.status)
2943
2944     headers = { "callback": '',
2945                 "NT": "upnp:event",
2946                 "timeout": "Second-1234" }
2947     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2948     resp = conn.getresponse()
2949     if resp.status != 500:
2950         raise Exception("Unexpected HTTP response: %d" % resp.status)
2951
2952     headers = { "callback": ' <',
2953                 "NT": "upnp:event",
2954                 "timeout": "Second-1234" }
2955     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2956     resp = conn.getresponse()
2957     if resp.status != 500:
2958         raise Exception("Unexpected HTTP response: %d" % resp.status)
2959
2960     headers = { "callback": '<http://127.0.0.1:12345/event>',
2961                 "NT": "upnp:event",
2962                 "timeout": "Second-1234" }
2963     with alloc_fail(hapd, 1, "wpabuf_alloc;subscription_first_event"):
2964         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2965         resp = conn.getresponse()
2966         if resp.status != 500:
2967             raise Exception("Unexpected HTTP response: %d" % resp.status)
2968
2969     with alloc_fail(hapd, 1, "event_add;subscription_first_event"):
2970         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2971         resp = conn.getresponse()
2972         if resp.status != 500:
2973             raise Exception("Unexpected HTTP response: %d" % resp.status)
2974
2975     with alloc_fail(hapd, 1, "subscr_addr_add_url"):
2976         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2977         resp = conn.getresponse()
2978         if resp.status != 500:
2979             raise Exception("Unexpected HTTP response: %d" % resp.status)
2980
2981     with alloc_fail(hapd, 2, "subscr_addr_add_url"):
2982         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2983         resp = conn.getresponse()
2984         if resp.status != 500:
2985             raise Exception("Unexpected HTTP response: %d" % resp.status)
2986
2987     for i in range(6):
2988         headers = { "callback": '<http://127.0.0.1:%d/event>' % (12345 + i),
2989                     "NT": "upnp:event",
2990                     "timeout": "Second-1234" }
2991         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2992         resp = conn.getresponse()
2993         if resp.status != 200:
2994             raise Exception("Unexpected HTTP response: %d" % resp.status)
2995
2996     with alloc_fail(hapd, 1, "=upnp_wps_device_send_wlan_event"):
2997         dev[1].dump_monitor()
2998         dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2999         dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3000         dev[1].request("WPS_CANCEL")
3001         time.sleep(0.1)
3002
3003     with alloc_fail(hapd, 1, "wpabuf_alloc;upnp_wps_device_send_event"):
3004         dev[1].dump_monitor()
3005         dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3006         dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3007         dev[1].request("WPS_CANCEL")
3008         time.sleep(0.1)
3009
3010     with alloc_fail(hapd, 1, "base64_encode;upnp_wps_device_send_wlan_event"):
3011         dev[1].dump_monitor()
3012         dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3013         dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3014         dev[1].request("WPS_CANCEL")
3015         time.sleep(0.1)
3016
3017     hapd.disable()
3018     with alloc_fail(hapd, 1, "get_netif_info"):
3019         if "FAIL" not in hapd.request("ENABLE"):
3020             raise Exception("ENABLE succeeded during OOM")
3021
3022 def test_ap_wps_upnp_subscribe_events(dev, apdev):
3023     """WPS AP and UPnP event subscription and many events"""
3024     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3025     hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
3026
3027     location = ssdp_get_location(ap_uuid)
3028     urls = upnp_get_urls(location)
3029     eventurl = urlparse.urlparse(urls['event_sub_url'])
3030
3031     class WPSERHTTPServer(SocketServer.StreamRequestHandler):
3032         def handle(self):
3033             data = self.rfile.readline().strip()
3034             logger.debug(data)
3035             self.wfile.write(gen_wps_event())
3036
3037     server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
3038     server.timeout = 1
3039
3040     url = urlparse.urlparse(location)
3041     conn = httplib.HTTPConnection(url.netloc)
3042
3043     headers = { "callback": '<http://127.0.0.1:12345/event>',
3044                 "NT": "upnp:event",
3045                 "timeout": "Second-1234" }
3046     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3047     resp = conn.getresponse()
3048     if resp.status != 200:
3049         raise Exception("Unexpected HTTP response: %d" % resp.status)
3050     sid = resp.getheader("sid")
3051     logger.debug("Subscription SID " + sid)
3052
3053     # Fetch the first event message
3054     server.handle_request()
3055
3056     # Force subscription event queue to reach the maximum length by generating
3057     # new proxied events without the ER fetching any of the pending events.
3058     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3059     dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3060     for i in range(16):
3061         dev[1].dump_monitor()
3062         dev[2].dump_monitor()
3063         dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3064         dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3065         dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3066         dev[1].request("WPS_CANCEL")
3067         dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3068         dev[2].request("WPS_CANCEL")
3069         if i % 4 == 1:
3070             time.sleep(1)
3071         else:
3072             time.sleep(0.1)
3073
3074     hapd.request("WPS_PIN any 12345670")
3075     dev[1].dump_monitor()
3076     dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3077     ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=10)
3078     if ev is None:
3079         raise Exception("WPS success not reported")
3080
3081     # Close the WPS ER HTTP server without fetching all the pending events.
3082     # This tests hostapd code path that clears subscription and the remaining
3083     # event queue when the interface is deinitialized.
3084     server.handle_request()
3085     server.server_close()
3086
3087     dev[1].wait_connected()
3088
3089 def test_ap_wps_upnp_http_proto(dev, apdev):
3090     """WPS AP and UPnP/HTTP protocol testing"""
3091     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3092     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
3093
3094     location = ssdp_get_location(ap_uuid)
3095
3096     url = urlparse.urlparse(location)
3097     conn = httplib.HTTPConnection(url.netloc, timeout=0.2)
3098     #conn.set_debuglevel(1)
3099
3100     conn.request("HEAD", "hello")
3101     resp = conn.getresponse()
3102     if resp.status != 501:
3103         raise Exception("Unexpected response to HEAD: " + str(resp.status))
3104     conn.close()
3105
3106     for cmd in [ "PUT", "DELETE", "TRACE", "CONNECT", "M-SEARCH", "M-POST" ]:
3107         try:
3108             conn.request(cmd, "hello")
3109             resp = conn.getresponse()
3110         except Exception, e:
3111             pass
3112         conn.close()
3113
3114     headers = { "Content-Length": 'abc' }
3115     conn.request("HEAD", "hello", "\r\n\r\n", headers)
3116     try:
3117         resp = conn.getresponse()
3118     except Exception, e:
3119         pass
3120     conn.close()
3121
3122     headers = { "Content-Length": '-10' }
3123     conn.request("HEAD", "hello", "\r\n\r\n", headers)
3124     try:
3125         resp = conn.getresponse()
3126     except Exception, e:
3127         pass
3128     conn.close()
3129
3130     headers = { "Content-Length": '10000000000000' }
3131     conn.request("HEAD", "hello", "\r\n\r\nhello", headers)
3132     try:
3133         resp = conn.getresponse()
3134     except Exception, e:
3135         pass
3136     conn.close()
3137
3138     headers = { "Transfer-Encoding": 'abc' }
3139     conn.request("HEAD", "hello", "\r\n\r\n", headers)
3140     resp = conn.getresponse()
3141     if resp.status != 501:
3142         raise Exception("Unexpected response to HEAD: " + str(resp.status))
3143     conn.close()
3144
3145     headers = { "Transfer-Encoding": 'chunked' }
3146     conn.request("HEAD", "hello", "\r\n\r\n", headers)
3147     resp = conn.getresponse()
3148     if resp.status != 501:
3149         raise Exception("Unexpected response to HEAD: " + str(resp.status))
3150     conn.close()
3151
3152     # Too long a header
3153     conn.request("HEAD", 5000 * 'A')
3154     try:
3155         resp = conn.getresponse()
3156     except Exception, e:
3157         pass
3158     conn.close()
3159
3160     # Long URL but within header length limits
3161     conn.request("HEAD", 3000 * 'A')
3162     resp = conn.getresponse()
3163     if resp.status != 501:
3164         raise Exception("Unexpected response to HEAD: " + str(resp.status))
3165     conn.close()
3166
3167     headers = { "Content-Length": '20' }
3168     conn.request("POST", "hello", 10 * 'A' + "\r\n\r\n", headers)
3169     try:
3170         resp = conn.getresponse()
3171     except Exception, e:
3172         pass
3173     conn.close()
3174
3175     conn.request("POST", "hello", 5000 * 'A' + "\r\n\r\n")
3176     resp = conn.getresponse()
3177     if resp.status != 404:
3178         raise Exception("Unexpected HTTP response: %d" % resp.status)
3179     conn.close()
3180
3181     conn.request("POST", "hello", 60000 * 'A' + "\r\n\r\n")
3182     try:
3183         resp = conn.getresponse()
3184     except Exception, e:
3185         pass
3186     conn.close()
3187
3188 def test_ap_wps_upnp_http_proto_chunked(dev, apdev):
3189     """WPS AP and UPnP/HTTP protocol testing for chunked encoding"""
3190     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3191     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
3192
3193     location = ssdp_get_location(ap_uuid)
3194
3195     url = urlparse.urlparse(location)
3196     conn = httplib.HTTPConnection(url.netloc)
3197     #conn.set_debuglevel(1)
3198
3199     headers = { "Transfer-Encoding": 'chunked' }
3200     conn.request("POST", "hello",
3201                  "a\r\nabcdefghij\r\n" + "2\r\nkl\r\n" + "0\r\n\r\n",
3202                  headers)
3203     resp = conn.getresponse()
3204     if resp.status != 404:
3205         raise Exception("Unexpected HTTP response: %d" % resp.status)
3206     conn.close()
3207
3208     conn.putrequest("POST", "hello")
3209     conn.putheader('Transfer-Encoding', 'chunked')
3210     conn.endheaders()
3211     conn.send("a\r\nabcdefghij\r\n")
3212     time.sleep(0.1)
3213     conn.send("2\r\nkl\r\n")
3214     conn.send("0\r\n\r\n")
3215     resp = conn.getresponse()
3216     if resp.status != 404:
3217         raise Exception("Unexpected HTTP response: %d" % resp.status)
3218     conn.close()
3219
3220     conn.putrequest("POST", "hello")
3221     conn.putheader('Transfer-Encoding', 'chunked')
3222     conn.endheaders()
3223     completed = False
3224     try:
3225         for i in range(20000):
3226             conn.send("1\r\nZ\r\n")
3227         conn.send("0\r\n\r\n")
3228         resp = conn.getresponse()
3229         completed = True
3230     except Exception, e:
3231         pass
3232     conn.close()
3233     if completed:
3234         raise Exception("Too long chunked request did not result in connection reset")
3235
3236     headers = { "Transfer-Encoding": 'chunked' }
3237     conn.request("POST", "hello", "80000000\r\na", headers)
3238     try:
3239         resp = conn.getresponse()
3240     except Exception, e:
3241         pass
3242     conn.close()
3243
3244     conn.request("POST", "hello", "10000000\r\na", headers)
3245     try:
3246         resp = conn.getresponse()
3247     except Exception, e:
3248         pass
3249     conn.close()
3250
3251 def test_ap_wps_disabled(dev, apdev):
3252     """WPS operations while WPS is disabled"""
3253     ssid = "test-wps-disabled"
3254     hostapd.add_ap(apdev[0]['ifname'], { "ssid": ssid })
3255     hapd = hostapd.Hostapd(apdev[0]['ifname'])
3256     if "FAIL" not in hapd.request("WPS_PBC"):
3257         raise Exception("WPS_PBC succeeded unexpectedly")
3258     if "FAIL" not in hapd.request("WPS_CANCEL"):
3259         raise Exception("WPS_CANCEL succeeded unexpectedly")
3260
3261 def test_ap_wps_mixed_cred(dev, apdev):
3262     """WPS 2.0 STA merging mixed mode WPA/WPA2 credentials"""
3263     ssid = "test-wps-wep"
3264     hostapd.add_ap(apdev[0]['ifname'],
3265                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3266                      "skip_cred_build": "1", "extra_cred": "wps-mixed-cred" })
3267     hapd = hostapd.Hostapd(apdev[0]['ifname'])
3268     hapd.request("WPS_PBC")
3269     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3270     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3271     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
3272     if ev is None:
3273         raise Exception("WPS-SUCCESS event timed out")
3274     nets = dev[0].list_networks()
3275     if len(nets) != 1:
3276         raise Exception("Unexpected number of network blocks")
3277     id = nets[0]['id']
3278     proto = dev[0].get_network(id, "proto")
3279     if proto != "WPA RSN":
3280         raise Exception("Unexpected merged proto field value: " + proto)
3281     pairwise = dev[0].get_network(id, "pairwise")
3282     if pairwise != "CCMP TKIP" and pairwise != "CCMP GCMP TKIP":
3283         raise Exception("Unexpected merged pairwise field value: " + pairwise)
3284
3285 def test_ap_wps_while_connected(dev, apdev):
3286     """WPS PBC provisioning while connected to another AP"""
3287     ssid = "test-wps-conf"
3288     hostapd.add_ap(apdev[0]['ifname'],
3289                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3290                      "wpa_passphrase": "12345678", "wpa": "2",
3291                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3292     hapd = hostapd.Hostapd(apdev[0]['ifname'])
3293
3294     hostapd.add_ap(apdev[1]['ifname'], { "ssid": "open" })
3295     dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3296
3297     logger.info("WPS provisioning step")
3298     hapd.request("WPS_PBC")
3299     dev[0].dump_monitor()
3300     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3301     dev[0].wait_connected(timeout=30)
3302     status = dev[0].get_status()
3303     if status['bssid'] != apdev[0]['bssid']:
3304         raise Exception("Unexpected BSSID")
3305
3306 def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
3307     """WPS PBC provisioning while connected to another AP and STA_AUTOCONNECT disabled"""
3308     ssid = "test-wps-conf"
3309     hostapd.add_ap(apdev[0]['ifname'],
3310                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3311                      "wpa_passphrase": "12345678", "wpa": "2",
3312                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3313     hapd = hostapd.Hostapd(apdev[0]['ifname'])
3314
3315     hostapd.add_ap(apdev[1]['ifname'], { "ssid": "open" })
3316
3317     try:
3318         dev[0].request("STA_AUTOCONNECT 0")
3319         dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3320
3321         logger.info("WPS provisioning step")
3322         hapd.request("WPS_PBC")
3323         dev[0].dump_monitor()
3324         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3325         dev[0].wait_connected(timeout=30)
3326         status = dev[0].get_status()
3327         if status['bssid'] != apdev[0]['bssid']:
3328             raise Exception("Unexpected BSSID")
3329     finally:
3330         dev[0].request("STA_AUTOCONNECT 1")
3331
3332 def test_ap_wps_from_event(dev, apdev):
3333     """WPS PBC event on AP to enable PBC"""
3334     ssid = "test-wps-conf"
3335     hapd = hostapd.add_ap(apdev[0]['ifname'],
3336                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3337                             "wpa_passphrase": "12345678", "wpa": "2",
3338                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3339     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3340     dev[0].dump_monitor()
3341     hapd.dump_monitor()
3342     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3343
3344     ev = hapd.wait_event(['WPS-ENROLLEE-SEEN'], timeout=15)
3345     if ev is None:
3346         raise Exception("No WPS-ENROLLEE-SEEN event on AP")
3347     vals = ev.split(' ')
3348     if vals[1] != dev[0].p2p_interface_addr():
3349         raise Exception("Unexpected enrollee address: " + vals[1])
3350     if vals[5] != '4':
3351         raise Exception("Unexpected Device Password Id: " + vals[5])
3352     hapd.request("WPS_PBC")
3353     dev[0].wait_connected(timeout=30)
3354
3355 def test_ap_wps_ap_scan_2(dev, apdev):
3356     """AP_SCAN 2 for WPS"""
3357     ssid = "test-wps-conf"
3358     hapd = hostapd.add_ap(apdev[0]['ifname'],
3359                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3360                             "wpa_passphrase": "12345678", "wpa": "2",
3361                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3362     hapd.request("WPS_PBC")
3363
3364     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
3365     wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
3366
3367     if "OK" not in wpas.request("AP_SCAN 2"):
3368         raise Exception("Failed to set AP_SCAN 2")
3369
3370     wpas.flush_scan_cache()
3371     wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
3372     wpas.request("WPS_PBC " + apdev[0]['bssid'])
3373     ev = wpas.wait_event(["WPS-SUCCESS"], timeout=15)
3374     if ev is None:
3375         raise Exception("WPS-SUCCESS event timed out")
3376     wpas.wait_connected(timeout=30)
3377     wpas.request("DISCONNECT")
3378     wpas.request("BSS_FLUSH 0")
3379     wpas.dump_monitor()
3380     wpas.request("REASSOCIATE")
3381     wpas.wait_connected(timeout=30)
3382
3383 def test_ap_wps_eapol_workaround(dev, apdev):
3384     """EAPOL workaround code path for 802.1X header length mismatch"""
3385     ssid = "test-wps"
3386     hostapd.add_ap(apdev[0]['ifname'],
3387                    { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
3388     hapd = hostapd.Hostapd(apdev[0]['ifname'])
3389     bssid = apdev[0]['bssid']
3390     hapd.request("SET ext_eapol_frame_io 1")
3391     dev[0].request("SET ext_eapol_frame_io 1")
3392     hapd.request("WPS_PBC")
3393     dev[0].request("WPS_PBC")
3394
3395     ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3396     if ev is None:
3397         raise Exception("Timeout on EAPOL-TX from hostapd")
3398
3399     res = dev[0].request("EAPOL_RX " + bssid + " 020000040193000501FFFF")
3400     if "OK" not in res:
3401         raise Exception("EAPOL_RX to wpa_supplicant failed")
3402
3403 def test_ap_wps_iteration(dev, apdev):
3404     """WPS PIN and iterate through APs without selected registrar"""
3405     ssid = "test-wps-conf"
3406     hapd = hostapd.add_ap(apdev[0]['ifname'],
3407                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3408                             "wpa_passphrase": "12345678", "wpa": "2",
3409                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3410
3411     ssid2 = "test-wps-conf2"
3412     hapd2 = hostapd.add_ap(apdev[1]['ifname'],
3413                            { "ssid": ssid2, "eap_server": "1", "wps_state": "2",
3414                              "wpa_passphrase": "12345678", "wpa": "2",
3415                              "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3416
3417     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3418     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
3419     dev[0].dump_monitor()
3420     pin = dev[0].request("WPS_PIN any")
3421
3422     # Wait for iteration through all WPS APs to happen before enabling any
3423     # Registrar.
3424     for i in range(2):
3425         ev = dev[0].wait_event(["Associated with"], timeout=30)
3426         if ev is None:
3427             raise Exception("No association seen")
3428         ev = dev[0].wait_event(["WPS-M2D"], timeout=10)
3429         if ev is None:
3430             raise Exception("No M2D from AP")
3431         dev[0].wait_disconnected()
3432
3433     # Verify that each AP requested PIN
3434     ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3435     if ev is None:
3436         raise Exception("No WPS-PIN-NEEDED event from AP")
3437     ev = hapd2.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3438     if ev is None:
3439         raise Exception("No WPS-PIN-NEEDED event from AP2")
3440
3441     # Provide PIN to one of the APs and verify that connection gets formed
3442     hapd.request("WPS_PIN any " + pin)
3443     dev[0].wait_connected(timeout=30)
3444
3445 def test_ap_wps_iteration_error(dev, apdev):
3446     """WPS AP iteration on no Selected Registrar and error case with an AP"""
3447     ssid = "test-wps-conf-pin"
3448     hapd = hostapd.add_ap(apdev[0]['ifname'],
3449                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3450                             "wpa_passphrase": "12345678", "wpa": "2",
3451                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3452                             "wps_independent": "1" })
3453     hapd.request("SET ext_eapol_frame_io 1")
3454     bssid = apdev[0]['bssid']
3455     pin = dev[0].wps_read_pin()
3456     dev[0].request("WPS_PIN any " + pin)
3457
3458     ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3459     if ev is None:
3460         raise Exception("No EAPOL-TX (EAP-Request/Identity) from hostapd")
3461     dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
3462
3463     ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3464     if ev is None:
3465         raise Exception("No EAPOL-TX (EAP-WSC/Start) from hostapd")
3466     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=5)
3467     if ev is None:
3468         raise Exception("No CTRL-EVENT-EAP-STARTED")
3469
3470     # Do not forward any more EAPOL frames to test wpa_supplicant behavior for
3471     # a case with an incorrectly behaving WPS AP.
3472
3473     # Start the real target AP and activate registrar on it.
3474     hapd2 = hostapd.add_ap(apdev[1]['ifname'],
3475                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3476                             "wpa_passphrase": "12345678", "wpa": "2",
3477                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3478                             "wps_independent": "1" })
3479     hapd2.request("WPS_PIN any " + pin)
3480
3481     dev[0].wait_disconnected(timeout=15)
3482     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
3483     if ev is None:
3484         raise Exception("No CTRL-EVENT-EAP-STARTED for the second AP")
3485     ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
3486     if ev is None:
3487         raise Exception("No WPS-CRED-RECEIVED for the second AP")
3488     dev[0].wait_connected(timeout=15)
3489
3490 def test_ap_wps_priority(dev, apdev):
3491     """WPS PIN provisioning with configured AP and wps_priority"""
3492     ssid = "test-wps-conf-pin"
3493     hostapd.add_ap(apdev[0]['ifname'],
3494                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3495                      "wpa_passphrase": "12345678", "wpa": "2",
3496                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3497     hapd = hostapd.Hostapd(apdev[0]['ifname'])
3498     logger.info("WPS provisioning step")
3499     pin = dev[0].wps_read_pin()
3500     hapd.request("WPS_PIN any " + pin)
3501     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3502     dev[0].dump_monitor()
3503     try:
3504         dev[0].request("SET wps_priority 6")
3505         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3506         dev[0].wait_connected(timeout=30)
3507         netw = dev[0].list_networks()
3508         prio = dev[0].get_network(netw[0]['id'], 'priority')
3509         if prio != '6':
3510             raise Exception("Unexpected network priority: " + prio)
3511     finally:
3512         dev[0].request("SET wps_priority 0")
3513
3514 def test_ap_wps_and_non_wps(dev, apdev):
3515     """WPS and non-WPS AP in single hostapd process"""
3516     params = { "ssid": "wps", "eap_server": "1", "wps_state": "1" }
3517     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
3518
3519     params = { "ssid": "no wps" }
3520     hapd2 = hostapd.add_ap(apdev[1]['ifname'], params)
3521
3522     appin = hapd.request("WPS_AP_PIN random")
3523     if "FAIL" in appin:
3524         raise Exception("Could not generate random AP PIN")
3525     if appin not in hapd.request("WPS_AP_PIN get"):
3526         raise Exception("Could not fetch current AP PIN")
3527
3528     if "FAIL" in hapd.request("WPS_PBC"):
3529         raise Exception("WPS_PBC failed")
3530     if "FAIL" in hapd.request("WPS_CANCEL"):
3531         raise Exception("WPS_CANCEL failed")
3532
3533 def test_ap_wps_init_oom(dev, apdev):
3534     """Initial AP configuration and OOM during PSK generation"""
3535     ssid = "test-wps"
3536     params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
3537     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
3538
3539     with alloc_fail(hapd, 1, "base64_encode;wps_build_cred"):
3540         pin = dev[0].wps_read_pin()
3541         hapd.request("WPS_PIN any " + pin)
3542         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3543         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3544         dev[0].wait_disconnected()
3545
3546     hapd.request("WPS_PIN any " + pin)
3547     dev[0].wait_connected(timeout=30)
3548
3549 def test_ap_wps_er_oom(dev, apdev):
3550     """WPS ER OOM in XML processing"""
3551     try:
3552         _test_ap_wps_er_oom(dev, apdev)
3553     finally:
3554         dev[0].request("WPS_ER_STOP")
3555         dev[1].request("WPS_CANCEL")
3556         dev[0].request("DISCONNECT")
3557
3558 def _test_ap_wps_er_oom(dev, apdev):
3559     ssid = "wps-er-ap-config"
3560     ap_pin = "12345670"
3561     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3562     hostapd.add_ap(apdev[0]['ifname'],
3563                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3564                      "wpa_passphrase": "12345678", "wpa": "2",
3565                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3566                      "device_name": "Wireless AP", "manufacturer": "Company",
3567                      "model_name": "WAP", "model_number": "123",
3568                      "serial_number": "12345", "device_type": "6-0050F204-1",
3569                      "os_version": "01020300",
3570                      "config_methods": "label push_button",
3571                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
3572
3573     dev[0].connect(ssid, psk="12345678", scan_freq="2412")
3574
3575     with alloc_fail(dev[0], 1, "base64_decode;xml_get_base64_item"):
3576         dev[0].request("WPS_ER_START ifname=lo")
3577         ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=3)
3578         if ev is not None:
3579             raise Exception("Unexpected AP discovery")
3580
3581     dev[0].request("WPS_ER_STOP")
3582     dev[0].request("WPS_ER_START ifname=lo")
3583     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
3584     if ev is None:
3585         raise Exception("AP discovery timed out")
3586
3587     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3588     with alloc_fail(dev[0], 1, "base64_decode;xml_get_base64_item"):
3589         dev[1].request("WPS_PBC " + apdev[0]['bssid'])
3590         ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
3591         if ev is None:
3592             raise Exception("PBC scan failed")
3593         ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
3594         if ev is None:
3595             raise Exception("Enrollee discovery timed out")
3596
3597 def test_ap_wps_er_init_oom(dev, apdev):
3598     """WPS ER and OOM during init"""
3599     try:
3600         _test_ap_wps_er_init_oom(dev, apdev)
3601     finally:
3602         dev[0].request("WPS_ER_STOP")
3603
3604 def _test_ap_wps_er_init_oom(dev, apdev):
3605     with alloc_fail(dev[0], 1, "wps_er_init"):
3606         if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3607             raise Exception("WPS_ER_START succeeded during OOM")
3608     with alloc_fail(dev[0], 1, "http_server_init"):
3609         if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3610             raise Exception("WPS_ER_START succeeded during OOM")
3611     with alloc_fail(dev[0], 2, "http_server_init"):
3612         if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3613             raise Exception("WPS_ER_START succeeded during OOM")
3614     with alloc_fail(dev[0], 1, "eloop_register_sock;wps_er_ssdp_init"):
3615         if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3616             raise Exception("WPS_ER_START succeeded during OOM")
3617     with fail_test(dev[0], 1, "os_get_random;wps_er_init"):
3618         if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3619             raise Exception("WPS_ER_START succeeded during os_get_random failure")
3620
3621 def test_ap_wps_er_init_fail(dev, apdev):
3622     """WPS ER init failure"""
3623     if "FAIL" not in dev[0].request("WPS_ER_START ifname=does-not-exist"):
3624         dev[0].request("WPS_ER_STOP")
3625         raise Exception("WPS_ER_START with non-existing ifname succeeded")
3626
3627 def test_ap_wps_wpa_cli_action(dev, apdev, test_params):
3628     """WPS events and wpa_cli action script"""
3629     logdir = os.path.abspath(test_params['logdir'])
3630     pidfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.pid')
3631     logfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.res')
3632     actionfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.action.sh')
3633
3634     with open(actionfile, 'w') as f:
3635         f.write('#!/bin/sh\n')
3636         f.write('echo $* >> %s\n' % logfile)
3637         # Kill the process and wait some time before returning to allow all the
3638         # pending events to be processed with some of this happening after the
3639         # eloop SIGALRM signal has been scheduled.
3640         f.write('if [ $2 = "WPS-SUCCESS" -a -r %s ]; then kill `cat %s`; sleep 1; fi\n' % (pidfile, pidfile))
3641
3642     os.chmod(actionfile, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC |
3643              stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
3644
3645     ssid = "test-wps-conf"
3646     hostapd.add_ap(apdev[0]['ifname'],
3647                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3648                      "wpa_passphrase": "12345678", "wpa": "2",
3649                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3650     hapd = hostapd.Hostapd(apdev[0]['ifname'])
3651
3652     prg = os.path.join(test_params['logdir'],
3653                        'alt-wpa_supplicant/wpa_supplicant/wpa_cli')
3654     if not os.path.exists(prg):
3655         prg = '../../wpa_supplicant/wpa_cli'
3656     arg = [ prg, '-P', pidfile, '-B', '-i', dev[0].ifname, '-a', actionfile ]
3657     subprocess.call(arg)
3658
3659     arg = [ 'ps', 'ax' ]
3660     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3661     out = cmd.communicate()[0]
3662     cmd.wait()
3663     logger.debug("Processes:\n" + out)
3664     if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) not in out:
3665         raise Exception("Did not see wpa_cli running")
3666
3667     hapd.request("WPS_PIN any 12345670")
3668     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3669     dev[0].dump_monitor()
3670     dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3671     dev[0].wait_connected(timeout=30)
3672
3673     for i in range(30):
3674         if not os.path.exists(pidfile):
3675             break
3676         time.sleep(0.1)
3677
3678     if not os.path.exists(logfile):
3679         raise Exception("wpa_cli action results file not found")
3680     with open(logfile, 'r') as f:
3681         res = f.read()
3682     if "WPS-SUCCESS" not in res:
3683         raise Exception("WPS-SUCCESS event not seen in action file")
3684
3685     arg = [ 'ps', 'ax' ]
3686     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3687     out = cmd.communicate()[0]
3688     cmd.wait()
3689     logger.debug("Remaining processes:\n" + out)
3690     if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) in out:
3691         raise Exception("wpa_cli still running")
3692
3693     if os.path.exists(pidfile):
3694         raise Exception("PID file not removed")
3695
3696 def test_ap_wps_er_ssdp_proto(dev, apdev):
3697     """WPS ER SSDP protocol testing"""
3698     try:
3699         _test_ap_wps_er_ssdp_proto(dev, apdev)
3700     finally:
3701         dev[0].request("WPS_ER_STOP")
3702
3703 def _test_ap_wps_er_ssdp_proto(dev, apdev):
3704     socket.setdefaulttimeout(1)
3705     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
3706     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
3707     sock.bind(("239.255.255.250", 1900))
3708     if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo foo"):
3709         raise Exception("Invalid filter accepted")
3710     if "OK" not in dev[0].request("WPS_ER_START ifname=lo 1.2.3.4"):
3711         raise Exception("WPS_ER_START with filter failed")
3712     (msg,addr) = sock.recvfrom(1000)
3713     logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3714     if "M-SEARCH" not in msg:
3715         raise Exception("Not an M-SEARCH")
3716     sock.sendto("FOO", addr)
3717     time.sleep(0.1)
3718     dev[0].request("WPS_ER_STOP")
3719
3720     dev[0].request("WPS_ER_START ifname=lo")
3721     (msg,addr) = sock.recvfrom(1000)
3722     logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3723     if "M-SEARCH" not in msg:
3724         raise Exception("Not an M-SEARCH")
3725     sock.sendto("FOO", addr)
3726     sock.sendto("HTTP/1.1 200 OK\r\nFOO\r\n\r\n", addr)
3727     sock.sendto("HTTP/1.1 200 OK\r\nNTS:foo\r\n\r\n", addr)
3728     sock.sendto("HTTP/1.1 200 OK\r\nNTS:ssdp:byebye\r\n\r\n", addr)
3729     sock.sendto("HTTP/1.1 200 OK\r\ncache-control:   foo=1\r\n\r\n", addr)
3730     sock.sendto("HTTP/1.1 200 OK\r\ncache-control:   max-age=1\r\n\r\n", addr)
3731     sock.sendto("HTTP/1.1 200 OK\r\nusn:\r\n\r\n", addr)
3732     sock.sendto("HTTP/1.1 200 OK\r\nusn:foo\r\n\r\n", addr)
3733     sock.sendto("HTTP/1.1 200 OK\r\nusn:   uuid:\r\n\r\n", addr)
3734     sock.sendto("HTTP/1.1 200 OK\r\nusn:   uuid:     \r\n\r\n", addr)
3735     sock.sendto("HTTP/1.1 200 OK\r\nusn:   uuid:     foo\r\n\r\n", addr)
3736     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\n\r\n", addr)
3737     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nNTS:ssdp:byebye\r\n\r\n", addr)
3738     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\n\r\n", addr)
3739     with alloc_fail(dev[0], 1, "wps_er_ap_add"):
3740         sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
3741         time.sleep(0.1)
3742     with alloc_fail(dev[0], 2, "wps_er_ap_add"):
3743         sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
3744         time.sleep(0.1)
3745
3746     # Add an AP with bogus URL
3747     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
3748     # Update timeout on AP without updating URL
3749     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1:12345/foo.xml\r\ncache-control:max-age=1\r\n\r\n", addr)
3750     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
3751     if ev is None:
3752         raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3753
3754     # Add an AP with a valid URL (but no server listing to it)
3755     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1:12345/foo.xml\r\ncache-control:max-age=1\r\n\r\n", addr)
3756     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
3757     if ev is None:
3758         raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3759
3760     sock.close()
3761
3762 wps_event_url = None
3763
3764 def gen_upnp_info(eventSubURL='wps_event', controlURL='wps_control',
3765                   udn='uuid:27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'):
3766     payload = '''<?xml version="1.0"?>
3767 <root xmlns="urn:schemas-upnp-org:device-1-0">
3768 <specVersion>
3769 <major>1</major>
3770 <minor>0</minor>
3771 </specVersion>
3772 <device>
3773 <deviceType>urn:schemas-wifialliance-org:device:WFADevice:1</deviceType>
3774 <friendlyName>WPS Access Point</friendlyName>
3775 <manufacturer>Company</manufacturer>
3776 <modelName>WAP</modelName>
3777 <modelNumber>123</modelNumber>
3778 <serialNumber>12345</serialNumber>
3779 '''
3780     if udn:
3781         payload += '<UDN>' + udn + '</UDN>'
3782     payload += '''<serviceList>
3783 <service>
3784 <serviceType>urn:schemas-wifialliance-org:service:WFAWLANConfig:1</serviceType>
3785 <serviceId>urn:wifialliance-org:serviceId:WFAWLANConfig1</serviceId>
3786 <SCPDURL>wps_scpd.xml</SCPDURL>
3787 '''
3788     if controlURL:
3789         payload += '<controlURL>' + controlURL + '</controlURL>\n'
3790     if eventSubURL:
3791         payload += '<eventSubURL>' + eventSubURL + '</eventSubURL>\n'
3792     payload += '''</service>
3793 </serviceList>
3794 </device>
3795 </root>
3796 '''
3797     hdr = 'HTTP/1.1 200 OK\r\n' + \
3798           'Content-Type: text/xml; charset="utf-8"\r\n' + \
3799           'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3800           'Connection: close\r\n' + \
3801           'Content-Length: ' + str(len(payload)) + '\r\n' + \
3802           'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3803     return hdr + payload
3804
3805 def gen_wps_control(payload_override=None):
3806     payload = '''<?xml version="1.0"?>
3807 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
3808 <s:Body>
3809 <u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
3810 <NewDeviceInfo>EEoAARAQIgABBBBHABAn6oAanlxOc72C+Jy80Q1+ECAABgIAAAADABAaABCJZ7DPtbU3Ust9
3811 Z3wJF07WEDIAwH45D3i1OqB7eJGwTzqeapS71h3KyXncK2xJZ+xqScrlorNEg6LijBJzG2Ca
3812 +FZli0iliDJd397yAx/jk4nFXco3q5ylBSvSw9dhJ5u1xBKSnTilKGlUHPhLP75PUqM3fot9
3813 7zwtFZ4bx6x1sBA6oEe2d0aUJmLumQGCiKEIWlnxs44zego/2tAe81bDzdPBM7o5HH/FUhD+
3814 KoGzFXp51atP+1n9Vta6AkI0Vye99JKLcC6Md9dMJltSVBgd4Xc4lRAEAAIAIxAQAAIADRAN
3815 AAEBEAgAAgAEEEQAAQIQIQAHQ29tcGFueRAjAANXQVAQJAADMTIzEEIABTEyMzQ1EFQACAAG
3816 AFDyBAABEBEAC1dpcmVsZXNzIEFQEDwAAQEQAgACAAAQEgACAAAQCQACAAAQLQAEgQIDABBJ
3817 AAYANyoAASA=
3818 </NewDeviceInfo>
3819 </u:GetDeviceInfoResponse>
3820 </s:Body>
3821 </s:Envelope>
3822 '''
3823     if payload_override:
3824         payload = payload_override
3825     hdr = 'HTTP/1.1 200 OK\r\n' + \
3826           'Content-Type: text/xml; charset="utf-8"\r\n' + \
3827           'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3828           'Connection: close\r\n' + \
3829           'Content-Length: ' + str(len(payload)) + '\r\n' + \
3830           'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3831     return hdr + payload
3832
3833 def gen_wps_event(sid='uuid:7eb3342a-8a5f-47fe-a585-0785bfec6d8a'):
3834     payload = ""
3835     hdr = 'HTTP/1.1 200 OK\r\n' + \
3836           'Content-Type: text/xml; charset="utf-8"\r\n' + \
3837           'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3838           'Connection: close\r\n' + \
3839           'Content-Length: ' + str(len(payload)) + '\r\n'
3840     if sid:
3841         hdr += 'SID: ' + sid + '\r\n'
3842     hdr += 'Timeout: Second-1801\r\n' + \
3843           'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3844     return hdr + payload
3845
3846 class WPSAPHTTPServer(SocketServer.StreamRequestHandler):
3847     def handle(self):
3848         data = self.rfile.readline().strip()
3849         logger.info("HTTP server received: " + data)
3850         while True:
3851             hdr = self.rfile.readline().strip()
3852             if len(hdr) == 0:
3853                 break
3854             logger.info("HTTP header: " + hdr)
3855             if "CALLBACK:" in hdr:
3856                 global wps_event_url
3857                 wps_event_url = hdr.split(' ')[1].strip('<>')
3858
3859         if "GET /foo.xml" in data:
3860             self.handle_upnp_info()
3861         elif "POST /wps_control" in data:
3862             self.handle_wps_control()
3863         elif "SUBSCRIBE /wps_event" in data:
3864             self.handle_wps_event()
3865         else:
3866             self.handle_others(data)
3867
3868     def handle_upnp_info(self):
3869         self.wfile.write(gen_upnp_info())
3870
3871     def handle_wps_control(self):
3872         self.wfile.write(gen_wps_control())
3873
3874     def handle_wps_event(self):
3875         self.wfile.write(gen_wps_event())
3876
3877     def handle_others(self, data):
3878         logger.info("Ignore HTTP request: " + data)
3879
3880 class MyTCPServer(SocketServer.TCPServer):
3881     def __init__(self, addr, handler):
3882         self.allow_reuse_address = True
3883         SocketServer.TCPServer.__init__(self, addr, handler)
3884
3885 def wps_er_start(dev, http_server, max_age=1, wait_m_search=False,
3886                  location_url=None):
3887     socket.setdefaulttimeout(1)
3888     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
3889     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
3890     sock.bind(("239.255.255.250", 1900))
3891     dev.request("WPS_ER_START ifname=lo")
3892     for i in range(100):
3893         (msg,addr) = sock.recvfrom(1000)
3894         logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3895         if "M-SEARCH" in msg:
3896             break
3897         if not wait_m_search:
3898             raise Exception("Not an M-SEARCH")
3899         if i == 99:
3900             raise Exception("No M-SEARCH seen")
3901
3902     # Add an AP with a valid URL and server listing to it
3903     server = MyTCPServer(("127.0.0.1", 12345), http_server)
3904     if not location_url:
3905         location_url = 'http://127.0.0.1:12345/foo.xml'
3906     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:%s\r\ncache-control:max-age=%d\r\n\r\n" % (location_url, max_age), addr)
3907     server.timeout = 1
3908     return server,sock
3909
3910 def wps_er_stop(dev, sock, server, on_alloc_fail=False):
3911     sock.close()
3912     server.server_close()
3913
3914     if on_alloc_fail:
3915         done = False
3916         for i in range(50):
3917             res = dev.request("GET_ALLOC_FAIL")
3918             if res.startswith("0:"):
3919                 done = True
3920                 break
3921             time.sleep(0.1)
3922         if not done:
3923             raise Exception("No allocation failure reported")
3924     else:
3925         ev = dev.wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
3926         if ev is None:
3927             raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3928     dev.request("WPS_ER_STOP")
3929
3930 def run_wps_er_proto_test(dev, handler, no_event_url=False, location_url=None):
3931     try:
3932         uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
3933         server,sock = wps_er_start(dev, handler, location_url=location_url)
3934         global wps_event_url
3935         wps_event_url = None
3936         server.handle_request()
3937         server.handle_request()
3938         server.handle_request()
3939         server.server_close()
3940         if no_event_url:
3941             if wps_event_url:
3942                 raise Exception("Received event URL unexpectedly")
3943             return
3944         if wps_event_url is None:
3945             raise Exception("Did not get event URL")
3946         logger.info("Event URL: " + wps_event_url)
3947     finally:
3948             dev.request("WPS_ER_STOP")
3949
3950 def send_wlanevent(url, uuid, data, no_response=False):
3951     conn = httplib.HTTPConnection(url.netloc)
3952     payload = '''<?xml version="1.0" encoding="utf-8"?>
3953 <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
3954 <e:property><STAStatus>1</STAStatus></e:property>
3955 <e:property><APStatus>1</APStatus></e:property>
3956 <e:property><WLANEvent>'''
3957     payload += base64.b64encode(data)
3958     payload += '</WLANEvent></e:property></e:propertyset>'
3959     headers = { "Content-type": 'text/xml; charset="utf-8"',
3960                 "Server": "Unspecified, UPnP/1.0, Unspecified",
3961                 "HOST": url.netloc,
3962                 "NT": "upnp:event",
3963                 "SID": "uuid:" + uuid,
3964                 "SEQ": "0",
3965                 "Content-Length": str(len(payload)) }
3966     conn.request("NOTIFY", url.path, payload, headers)
3967     if no_response:
3968         try:
3969             conn.getresponse()
3970         except Exception, e:
3971             pass
3972         return
3973     resp = conn.getresponse()
3974     if resp.status != 200:
3975         raise Exception("Unexpected HTTP response: %d" % resp.status)
3976
3977 def test_ap_wps_er_http_proto(dev, apdev):
3978     """WPS ER HTTP protocol testing"""
3979     try:
3980         _test_ap_wps_er_http_proto(dev, apdev)
3981     finally:
3982         dev[0].request("WPS_ER_STOP")
3983
3984 def _test_ap_wps_er_http_proto(dev, apdev):
3985     uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
3986     server,sock = wps_er_start(dev[0], WPSAPHTTPServer, max_age=15)
3987     global wps_event_url
3988     wps_event_url = None
3989     server.handle_request()
3990     server.handle_request()
3991     server.handle_request()
3992     server.server_close()
3993     if wps_event_url is None:
3994         raise Exception("Did not get event URL")
3995     logger.info("Event URL: " + wps_event_url)
3996
3997     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
3998     if ev is None:
3999         raise Exception("No WPS-ER-AP-ADD event")
4000     if uuid not in ev:
4001         raise Exception("UUID mismatch")
4002
4003     sock.close()
4004
4005     logger.info("Valid Probe Request notification")
4006     url = urlparse.urlparse(wps_event_url)
4007     conn = httplib.HTTPConnection(url.netloc)
4008     payload = '''<?xml version="1.0" encoding="utf-8"?>
4009 <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4010 <e:property><STAStatus>1</STAStatus></e:property>
4011 <e:property><APStatus>1</APStatus></e:property>
4012 <e:property><WLANEvent>ATAyOjAwOjAwOjAwOjAwOjAwEEoAARAQOgABAhAIAAIxSBBHABA2LbR7pTpRkYj7VFi5hrLk
4013 EFQACAAAAAAAAAAAEDwAAQMQAgACAAAQCQACAAAQEgACAAAQIQABIBAjAAEgECQAASAQEQAI
4014 RGV2aWNlIEEQSQAGADcqAAEg
4015 </WLANEvent></e:property>
4016 </e:propertyset>
4017 '''
4018     headers = { "Content-type": 'text/xml; charset="utf-8"',
4019                 "Server": "Unspecified, UPnP/1.0, Unspecified",
4020                 "HOST": url.netloc,
4021                 "NT": "upnp:event",
4022                 "SID": "uuid:" + uuid,
4023                 "SEQ": "0",
4024                 "Content-Length": str(len(payload)) }
4025     conn.request("NOTIFY", url.path, payload, headers)
4026     resp = conn.getresponse()
4027     if resp.status != 200:
4028         raise Exception("Unexpected HTTP response: %d" % resp.status)
4029
4030     ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=5)
4031     if ev is None:
4032         raise Exception("No WPS-ER-ENROLLEE-ADD event")
4033     if "362db47b-a53a-5191-88fb-5458b986b2e4" not in ev:
4034         raise Exception("No Enrollee UUID match")
4035
4036     logger.info("Incorrect event URL AP id")
4037     conn = httplib.HTTPConnection(url.netloc)
4038     conn.request("NOTIFY", url.path + '123', payload, headers)
4039     resp = conn.getresponse()
4040     if resp.status != 404:
4041         raise Exception("Unexpected HTTP response: %d" % resp.status)
4042
4043     logger.info("Missing AP id")
4044     conn = httplib.HTTPConnection(url.netloc)
4045     conn.request("NOTIFY", '/event/' + url.path.split('/')[2],
4046                  payload, headers)
4047     time.sleep(0.1)
4048
4049     logger.info("Incorrect event URL event id")
4050     conn = httplib.HTTPConnection(url.netloc)
4051     conn.request("NOTIFY", '/event/123456789/123', payload, headers)
4052     time.sleep(0.1)
4053
4054     logger.info("Incorrect event URL prefix")
4055     conn = httplib.HTTPConnection(url.netloc)
4056     conn.request("NOTIFY", '/foobar/123456789/123', payload, headers)
4057     resp = conn.getresponse()
4058     if resp.status != 404:
4059         raise Exception("Unexpected HTTP response: %d" % resp.status)
4060
4061     logger.info("Unsupported request")
4062     conn = httplib.HTTPConnection(url.netloc)
4063     conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4064     resp = conn.getresponse()
4065     if resp.status != 501:
4066         raise Exception("Unexpected HTTP response: %d" % resp.status)
4067
4068     logger.info("Unsupported request and OOM")
4069     with alloc_fail(dev[0], 1, "wps_er_http_req"):
4070         conn = httplib.HTTPConnection(url.netloc)
4071         conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4072         time.sleep(0.5)
4073
4074     logger.info("Too short WLANEvent")
4075     data = '\x00'
4076     send_wlanevent(url, uuid, data)
4077
4078     logger.info("Invalid WLANEventMAC")
4079     data = '\x00qwertyuiopasdfghjklzxcvbnm'
4080     send_wlanevent(url, uuid, data)
4081
4082     logger.info("Unknown WLANEventType")
4083     data = '\xff02:00:00:00:00:00'
4084     send_wlanevent(url, uuid, data)
4085
4086     logger.info("Probe Request notification without any attributes")
4087     data = '\x0102:00:00:00:00:00'
4088     send_wlanevent(url, uuid, data)
4089
4090     logger.info("Probe Request notification with invalid attribute")
4091     data = '\x0102:00:00:00:00:00\xff'
4092     send_wlanevent(url, uuid, data)
4093
4094     logger.info("EAP message without any attributes")
4095     data = '\x0202:00:00:00:00:00'
4096     send_wlanevent(url, uuid, data)
4097
4098     logger.info("EAP message with invalid attribute")
4099     data = '\x0202:00:00:00:00:00\xff'
4100     send_wlanevent(url, uuid, data)
4101
4102     logger.info("EAP message from new STA and not M1")
4103     data = '\x0202:ff:ff:ff:ff:ff' + '\x10\x22\x00\x01\x05'
4104     send_wlanevent(url, uuid, data)
4105
4106     logger.info("EAP message: M1")
4107     data = '\x0202:00:00:00:00:00'
4108     data += '\x10\x22\x00\x01\x04'
4109     data += '\x10\x47\x00\x10' + 16*'\x00'
4110     data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4111     data += '\x10\x1a\x00\x10' + 16*'\x00'
4112     data += '\x10\x32\x00\xc0' + 192*'\x00'
4113     data += '\x10\x04\x00\x02\x00\x00'
4114     data += '\x10\x10\x00\x02\x00\x00'
4115     data += '\x10\x0d\x00\x01\x00'
4116     data += '\x10\x08\x00\x02\x00\x00'
4117     data += '\x10\x44\x00\x01\x00'
4118     data += '\x10\x21\x00\x00'
4119     data += '\x10\x23\x00\x00'
4120     data += '\x10\x24\x00\x00'
4121     data += '\x10\x42\x00\x00'
4122     data += '\x10\x54\x00\x08' + 8*'\x00'
4123     data += '\x10\x11\x00\x00'
4124     data += '\x10\x3c\x00\x01\x00'
4125     data += '\x10\x02\x00\x02\x00\x00'
4126     data += '\x10\x12\x00\x02\x00\x00'
4127     data += '\x10\x09\x00\x02\x00\x00'
4128     data += '\x10\x2d\x00\x04\x00\x00\x00\x00'
4129     m1 = data
4130     send_wlanevent(url, uuid, data)
4131
4132     logger.info("EAP message: WSC_ACK")
4133     data = '\x0202:00:00:00:00:00' + '\x10\x22\x00\x01\x0d'
4134     send_wlanevent(url, uuid, data)
4135
4136     logger.info("EAP message: M1")
4137     send_wlanevent(url, uuid, m1)
4138
4139     logger.info("EAP message: WSC_NACK")
4140     data = '\x0202:00:00:00:00:00' + '\x10\x22\x00\x01\x0e'
4141     send_wlanevent(url, uuid, data)
4142
4143     logger.info("EAP message: M1 - Too long attribute values")
4144     data = '\x0202:00:00:00:00:00'
4145     data += '\x10\x11\x00\x21' + 33*'\x00'
4146     data += '\x10\x45\x00\x21' + 33*'\x00'
4147     data += '\x10\x42\x00\x21' + 33*'\x00'
4148     data += '\x10\x24\x00\x21' + 33*'\x00'
4149     data += '\x10\x23\x00\x21' + 33*'\x00'
4150     data += '\x10\x21\x00\x41' + 65*'\x00'
4151     data += '\x10\x49\x00\x09\x00\x37\x2a\x05\x02\x00\x00\x05\x00'
4152     send_wlanevent(url, uuid, data)
4153
4154     logger.info("EAP message: M1 missing UUID-E")
4155     data = '\x0202:00:00:00:00:00'
4156     data += '\x10\x22\x00\x01\x04'
4157     send_wlanevent(url, uuid, data)
4158
4159     logger.info("EAP message: M1 missing MAC Address")
4160     data += '\x10\x47\x00\x10' + 16*'\x00'
4161     send_wlanevent(url, uuid, data)
4162
4163     logger.info("EAP message: M1 missing Enrollee Nonce")
4164     data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4165     send_wlanevent(url, uuid, data)
4166
4167     logger.info("EAP message: M1 missing Public Key")
4168     data += '\x10\x1a\x00\x10' + 16*'\x00'
4169     send_wlanevent(url, uuid, data)
4170
4171     logger.info("EAP message: M1 missing Authentication Type flags")
4172     data += '\x10\x32\x00\xc0' + 192*'\x00'
4173     send_wlanevent(url, uuid, data)
4174
4175     logger.info("EAP message: M1 missing Encryption Type Flags")
4176     data += '\x10\x04\x00\x02\x00\x00'
4177     send_wlanevent(url, uuid, data)
4178
4179     logger.info("EAP message: M1 missing Connection Type flags")
4180     data += '\x10\x10\x00\x02\x00\x00'
4181     send_wlanevent(url, uuid, data)
4182
4183     logger.info("EAP message: M1 missing Config Methods")
4184     data += '\x10\x0d\x00\x01\x00'
4185     send_wlanevent(url, uuid, data)
4186
4187     logger.info("EAP message: M1 missing Wi-Fi Protected Setup State")
4188     data += '\x10\x08\x00\x02\x00\x00'
4189     send_wlanevent(url, uuid, data)
4190
4191     logger.info("EAP message: M1 missing Manufacturer")
4192     data += '\x10\x44\x00\x01\x00'
4193     send_wlanevent(url, uuid, data)
4194
4195     logger.info("EAP message: M1 missing Model Name")
4196     data += '\x10\x21\x00\x00'
4197     send_wlanevent(url, uuid, data)
4198
4199     logger.info("EAP message: M1 missing Model Number")
4200     data += '\x10\x23\x00\x00'
4201     send_wlanevent(url, uuid, data)
4202
4203     logger.info("EAP message: M1 missing Serial Number")
4204     data += '\x10\x24\x00\x00'
4205     send_wlanevent(url, uuid, data)
4206
4207     logger.info("EAP message: M1 missing Primary Device Type")
4208     data += '\x10\x42\x00\x00'
4209     send_wlanevent(url, uuid, data)
4210
4211     logger.info("EAP message: M1 missing Device Name")
4212     data += '\x10\x54\x00\x08' + 8*'\x00'
4213     send_wlanevent(url, uuid, data)
4214
4215     logger.info("EAP message: M1 missing RF Bands")
4216     data += '\x10\x11\x00\x00'
4217     send_wlanevent(url, uuid, data)
4218
4219     logger.info("EAP message: M1 missing Association State")
4220     data += '\x10\x3c\x00\x01\x00'
4221     send_wlanevent(url, uuid, data)
4222
4223     logger.info("EAP message: M1 missing Device Password ID")
4224     data += '\x10\x02\x00\x02\x00\x00'
4225     send_wlanevent(url, uuid, data)
4226
4227     logger.info("EAP message: M1 missing Configuration Error")
4228     data += '\x10\x12\x00\x02\x00\x00'
4229     send_wlanevent(url, uuid, data)
4230
4231     logger.info("EAP message: M1 missing OS Version")
4232     data += '\x10\x09\x00\x02\x00\x00'
4233     send_wlanevent(url, uuid, data)
4234
4235     logger.info("Check max concurrent requests")
4236     addr = (url.hostname, url.port)
4237     socks = {}
4238     for i in range(20):
4239         socks[i] = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4240                                  socket.IPPROTO_TCP)
4241         socks[i].connect(addr)
4242     for i in range(20):
4243         socks[i].send("GET / HTTP/1.1\r\n\r\n")
4244     count = 0
4245     for i in range(20):
4246         try:
4247             res = socks[i].recv(100)
4248             if "HTTP/1" in res:
4249                 count += 1
4250         except:
4251             pass
4252         socks[i].close()
4253     logger.info("%d concurrent HTTP GET operations returned response" % count)
4254     if count < 10:
4255         raise Exception("Too few concurrent HTTP connections accepted")
4256
4257     logger.info("OOM in HTTP server")
4258     for func in [ "http_request_init", "httpread_create",
4259                   "eloop_register_timeout;httpread_create",
4260                   "eloop_register_sock;httpread_create",
4261                   "httpread_hdr_analyze" ]:
4262         with alloc_fail(dev[0], 1, func):
4263             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4264                                  socket.IPPROTO_TCP)
4265             sock.connect(addr)
4266             sock.send("GET / HTTP/1.1\r\n\r\n")
4267             try:
4268                 sock.recv(100)
4269             except:
4270                 pass
4271             sock.close()
4272
4273     logger.info("Invalid HTTP header")
4274     for req in [ " GET / HTTP/1.1\r\n\r\n",
4275                  "HTTP/1.1 200 OK\r\n\r\n",
4276                  "HTTP/\r\n\r\n",
4277                  "GET %%a%aa% HTTP/1.1\r\n\r\n",
4278                  "GET / HTTP/1.1\r\n FOO\r\n\r\n",
4279                  "NOTIFY / HTTP/1.1\r\n" + 4097*'a' + '\r\n\r\n',
4280                  "NOTIFY / HTTP/1.1\r\n\r\n" + 8193*'a',
4281                  "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n foo\r\n",
4282                  "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n1\r\nfoo\r\n",
4283                  "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\n",
4284                  "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\naa\ra\r\n\ra" ]:
4285         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4286                              socket.IPPROTO_TCP)
4287         sock.settimeout(0.1)
4288         sock.connect(addr)
4289         sock.send(req)
4290         try:
4291             sock.recv(100)
4292         except:
4293             pass
4294         sock.close()
4295
4296     with alloc_fail(dev[0], 2, "httpread_read_handler"):
4297         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4298                              socket.IPPROTO_TCP)
4299         sock.connect(addr)
4300         sock.send("NOTIFY / HTTP/1.1\r\n\r\n" + 4500*'a')
4301         try:
4302             sock.recv(100)
4303         except:
4304             pass
4305         sock.close()
4306
4307     conn = httplib.HTTPConnection(url.netloc)
4308     payload = '<foo'
4309     headers = { "Content-type": 'text/xml; charset="utf-8"',
4310                 "Server": "Unspecified, UPnP/1.0, Unspecified",
4311                 "HOST": url.netloc,
4312                 "NT": "upnp:event",
4313                 "SID": "uuid:" + uuid,
4314                 "SEQ": "0",
4315                 "Content-Length": str(len(payload)) }
4316     conn.request("NOTIFY", url.path, payload, headers)
4317     resp = conn.getresponse()
4318     if resp.status != 200:
4319         raise Exception("Unexpected HTTP response: %d" % resp.status)
4320
4321     conn = httplib.HTTPConnection(url.netloc)
4322     payload = '<WLANEvent foo></WLANEvent>'
4323     headers = { "Content-type": 'text/xml; charset="utf-8"',
4324                 "Server": "Unspecified, UPnP/1.0, Unspecified",
4325                 "HOST": url.netloc,
4326                 "NT": "upnp:event",
4327                 "SID": "uuid:" + uuid,
4328                 "SEQ": "0",
4329                 "Content-Length": str(len(payload)) }
4330     conn.request("NOTIFY", url.path, payload, headers)
4331     resp = conn.getresponse()
4332     if resp.status != 200:
4333         raise Exception("Unexpected HTTP response: %d" % resp.status)
4334
4335     with alloc_fail(dev[0], 1, "xml_get_first_item"):
4336         send_wlanevent(url, uuid, '')
4337
4338     with alloc_fail(dev[0], 1, "wpabuf_alloc_ext_data;xml_get_base64_item"):
4339         send_wlanevent(url, uuid, 'foo')
4340
4341     for func in [ "wps_init",
4342                   "wps_process_manufacturer",
4343                   "wps_process_model_name",
4344                   "wps_process_model_number",
4345                   "wps_process_serial_number",
4346                   "wps_process_dev_name" ]:
4347         with alloc_fail(dev[0], 1, func):
4348             send_wlanevent(url, uuid, m1)
4349
4350     with alloc_fail(dev[0], 1, "wps_er_http_resp_ok"):
4351         send_wlanevent(url, uuid, m1, no_response=True)
4352
4353     with alloc_fail(dev[0], 1, "wps_er_http_resp_not_found"):
4354         url2 = urlparse.urlparse(wps_event_url.replace('/event/', '/notfound/'))
4355         send_wlanevent(url2, uuid, m1, no_response=True)
4356
4357     logger.info("EAP message: M1")
4358     data = '\x0202:11:22:00:00:00'
4359     data += '\x10\x22\x00\x01\x04'
4360     data += '\x10\x47\x00\x10' + 16*'\x00'
4361     data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4362     data += '\x10\x1a\x00\x10' + 16*'\x00'
4363     data += '\x10\x32\x00\xc0' + 192*'\x00'
4364     data += '\x10\x04\x00\x02\x00\x00'
4365     data += '\x10\x10\x00\x02\x00\x00'
4366     data += '\x10\x0d\x00\x01\x00'
4367     data += '\x10\x08\x00\x02\x00\x00'
4368     data += '\x10\x44\x00\x01\x00'
4369     data += '\x10\x21\x00\x00'
4370     data += '\x10\x23\x00\x00'
4371     data += '\x10\x24\x00\x00'
4372     data += '\x10\x42\x00\x00'
4373     data += '\x10\x54\x00\x08' + 8*'\x00'
4374     data += '\x10\x11\x00\x00'
4375     data += '\x10\x3c\x00\x01\x00'
4376     data += '\x10\x02\x00\x02\x00\x00'
4377     data += '\x10\x12\x00\x02\x00\x00'
4378     data += '\x10\x09\x00\x02\x00\x00'
4379     data += '\x10\x2d\x00\x04\x00\x00\x00\x00'
4380     dev[0].dump_monitor()
4381     with alloc_fail(dev[0], 1, "wps_er_add_sta_data"):
4382         send_wlanevent(url, uuid, data)
4383         ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=0.1)
4384         if ev is not None:
4385             raise Exception("Unexpected enrollee add event")
4386     send_wlanevent(url, uuid, data)
4387     ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=2)
4388     if ev is None:
4389         raise Exception("Enrollee add event not seen")
4390
4391     with alloc_fail(dev[0], 1, "base64_encode;wps_er_soap_hdr"):
4392         send_wlanevent(url, uuid, data)
4393
4394     with alloc_fail(dev[0], 1, "wpabuf_alloc;wps_er_soap_hdr"):
4395         send_wlanevent(url, uuid, data)
4396
4397     with alloc_fail(dev[0], 1, "http_client_url_parse;wps_er_sta_send_msg"):
4398         send_wlanevent(url, uuid, data)
4399
4400     with alloc_fail(dev[0], 1, "http_client_addr;wps_er_sta_send_msg"):
4401         send_wlanevent(url, uuid, data)
4402
4403 def test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
4404     """WPS ER HTTP protocol testing - no eventSubURL"""
4405     class WPSAPHTTPServer_no_event_sub_url(WPSAPHTTPServer):
4406         def handle_upnp_info(self):
4407             self.wfile.write(gen_upnp_info(eventSubURL=None))
4408     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_event_sub_url,
4409                           no_event_url=True)
4410
4411 def test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev):
4412     """WPS ER HTTP protocol testing - DNS name in eventSubURL"""
4413     class WPSAPHTTPServer_event_sub_url_dns(WPSAPHTTPServer):
4414         def handle_upnp_info(self):
4415             self.wfile.write(gen_upnp_info(eventSubURL='http://example.com/wps_event'))
4416     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_event_sub_url_dns,
4417                           no_event_url=True)
4418
4419 def test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4420     """WPS ER HTTP protocol testing - subscribe OOM"""
4421     try:
4422         _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev)
4423     finally:
4424         dev[0].request("WPS_ER_STOP")
4425
4426 def _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4427     tests = [ (1, "http_client_url_parse"),
4428               (1, "wpabuf_alloc;wps_er_subscribe"),
4429               (1, "http_client_addr"),
4430               (1, "eloop_register_sock;http_client_addr"),
4431               (1, "eloop_register_timeout;http_client_addr") ]
4432     for count,func in tests:
4433         with alloc_fail(dev[0], count, func):
4434             server,sock = wps_er_start(dev[0], WPSAPHTTPServer)
4435             server.handle_request()
4436             server.handle_request()
4437             wps_er_stop(dev[0], sock, server, on_alloc_fail=True)
4438
4439 def test_ap_wps_er_http_proto_no_sid(dev, apdev):
4440     """WPS ER HTTP protocol testing - no SID"""
4441     class WPSAPHTTPServer_no_sid(WPSAPHTTPServer):
4442         def handle_wps_event(self):
4443             self.wfile.write(gen_wps_event(sid=None))
4444     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_sid)
4445
4446 def test_ap_wps_er_http_proto_invalid_sid_no_uuid(dev, apdev):
4447     """WPS ER HTTP protocol testing - invalid SID - no UUID"""
4448     class WPSAPHTTPServer_invalid_sid_no_uuid(WPSAPHTTPServer):
4449         def handle_wps_event(self):
4450             self.wfile.write(gen_wps_event(sid='FOO'))
4451     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_no_uuid)
4452
4453 def test_ap_wps_er_http_proto_invalid_sid_uuid(dev, apdev):
4454     """WPS ER HTTP protocol testing - invalid SID UUID"""
4455     class WPSAPHTTPServer_invalid_sid_uuid(WPSAPHTTPServer):
4456         def handle_wps_event(self):
4457             self.wfile.write(gen_wps_event(sid='uuid:FOO'))
4458     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_uuid)
4459
4460 def test_ap_wps_er_http_proto_subscribe_failing(dev, apdev):
4461     """WPS ER HTTP protocol testing - SUBSCRIBE failing"""
4462     class WPSAPHTTPServer_fail_subscribe(WPSAPHTTPServer):
4463         def handle_wps_event(self):
4464             payload = ""
4465             hdr = 'HTTP/1.1 404 Not Found\r\n' + \
4466                   'Content-Type: text/xml; charset="utf-8"\r\n' + \
4467                   'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4468                   'Connection: close\r\n' + \
4469                   'Content-Length: ' + str(len(payload)) + '\r\n' + \
4470                   'Timeout: Second-1801\r\n' + \
4471                   'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4472             self.wfile.write(hdr + payload)
4473     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_fail_subscribe)
4474
4475 def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4476     """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4477     class WPSAPHTTPServer_subscribe_invalid_response(WPSAPHTTPServer):
4478         def handle_wps_event(self):
4479             payload = ""
4480             hdr = 'HTTP/1.1 FOO\r\n' + \
4481                   'Content-Type: text/xml; charset="utf-8"\r\n' + \
4482                   'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4483                   'Connection: close\r\n' + \
4484                   'Content-Length: ' + str(len(payload)) + '\r\n' + \
4485                   'Timeout: Second-1801\r\n' + \
4486                   'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4487             self.wfile.write(hdr + payload)
4488     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_subscribe_invalid_response)
4489
4490 def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4491     """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4492     class WPSAPHTTPServer_invalid_m1(WPSAPHTTPServer):
4493         def handle_wps_control(self):
4494             payload = '''<?xml version="1.0"?>
4495 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4496 <s:Body>
4497 <u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4498 <NewDeviceInfo>Rk9P</NewDeviceInfo>
4499 </u:GetDeviceInfoResponse>
4500 </s:Body>
4501 </s:Envelope>
4502 '''
4503             self.wfile.write(gen_wps_control(payload_override=payload))
4504     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_m1, no_event_url=True)
4505
4506 def test_ap_wps_er_http_proto_upnp_info_no_device(dev, apdev):
4507     """WPS ER HTTP protocol testing - No device in UPnP info"""
4508     class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4509         def handle_upnp_info(self):
4510             payload = '''<?xml version="1.0"?>
4511 <root xmlns="urn:schemas-upnp-org:device-1-0">
4512 <specVersion>
4513 <major>1</major>
4514 <minor>0</minor>
4515 </specVersion>
4516 </root>
4517 '''
4518             hdr = 'HTTP/1.1 200 OK\r\n' + \
4519                   'Content-Type: text/xml; charset="utf-8"\r\n' + \
4520                   'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4521                   'Connection: close\r\n' + \
4522                   'Content-Length: ' + str(len(payload)) + '\r\n' + \
4523                   'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4524             self.wfile.write(hdr + payload)
4525     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4526
4527 def test_ap_wps_er_http_proto_upnp_info_no_device_type(dev, apdev):
4528     """WPS ER HTTP protocol testing - No deviceType in UPnP info"""
4529     class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4530         def handle_upnp_info(self):
4531             payload = '''<?xml version="1.0"?>
4532 <root xmlns="urn:schemas-upnp-org:device-1-0">
4533 <specVersion>
4534 <major>1</major>
4535 <minor>0</minor>
4536 </specVersion>
4537 <device>
4538 </device>
4539 </root>
4540 '''
4541             hdr = 'HTTP/1.1 200 OK\r\n' + \
4542                   'Content-Type: text/xml; charset="utf-8"\r\n' + \
4543                   'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4544                   'Connection: close\r\n' + \
4545                   'Content-Length: ' + str(len(payload)) + '\r\n' + \
4546                   'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4547             self.wfile.write(hdr + payload)
4548     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4549
4550 def test_ap_wps_er_http_proto_upnp_info_invalid_udn_uuid(dev, apdev):
4551     """WPS ER HTTP protocol testing - Invalid UDN UUID"""
4552     class WPSAPHTTPServer_invalid_udn_uuid(WPSAPHTTPServer):
4553         def handle_upnp_info(self):
4554             self.wfile.write(gen_upnp_info(udn='uuid:foo'))
4555     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_udn_uuid)
4556
4557 def test_ap_wps_er_http_proto_no_control_url(dev, apdev):
4558     """WPS ER HTTP protocol testing - no controlURL"""
4559     class WPSAPHTTPServer_no_control_url(WPSAPHTTPServer):
4560         def handle_upnp_info(self):
4561             self.wfile.write(gen_upnp_info(controlURL=None))
4562     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_control_url,
4563                           no_event_url=True)
4564
4565 def test_ap_wps_er_http_proto_control_url_dns(dev, apdev):
4566     """WPS ER HTTP protocol testing - DNS name in controlURL"""
4567     class WPSAPHTTPServer_control_url_dns(WPSAPHTTPServer):
4568         def handle_upnp_info(self):
4569             self.wfile.write(gen_upnp_info(controlURL='http://example.com/wps_control'))
4570     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_control_url_dns,
4571                           no_event_url=True)
4572
4573 def test_ap_wps_http_timeout(dev, apdev):
4574     """WPS AP/ER and HTTP timeout"""
4575     try:
4576         _test_ap_wps_http_timeout(dev, apdev)
4577     finally:
4578         dev[0].request("WPS_ER_STOP")
4579
4580 def _test_ap_wps_http_timeout(dev, apdev):
4581     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
4582     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
4583
4584     location = ssdp_get_location(ap_uuid)
4585     url = urlparse.urlparse(location)
4586     addr = (url.hostname, url.port)
4587     logger.debug("Open HTTP connection to hostapd, but do not complete request")
4588     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4589                          socket.IPPROTO_TCP)
4590     sock.connect(addr)
4591     sock.send("G")
4592
4593     class DummyServer(SocketServer.StreamRequestHandler):
4594         def handle(self):
4595             logger.debug("DummyServer - start 31 sec wait")
4596             time.sleep(31)
4597             logger.debug("DummyServer - wait done")
4598
4599     logger.debug("Start WPS ER")
4600     server,sock2 = wps_er_start(dev[0], DummyServer, max_age=40,
4601                                 wait_m_search=True)
4602
4603     logger.debug("Start server to accept, but not complete, HTTP connection from WPS ER")
4604     # This will wait for 31 seconds..
4605     server.handle_request()
4606
4607     logger.debug("Complete HTTP connection with hostapd (that should have already closed the connection)")
4608     try:
4609         sock.send("ET / HTTP/1.1\r\n\r\n")
4610         res = sock.recv(100)
4611         sock.close()
4612     except:
4613         pass
4614
4615 def test_ap_wps_er_url_parse(dev, apdev):
4616     """WPS ER and URL parsing special cases"""
4617     try:
4618         _test_ap_wps_er_url_parse(dev, apdev)
4619     finally:
4620         dev[0].request("WPS_ER_STOP")
4621
4622 def _test_ap_wps_er_url_parse(dev, apdev):
4623     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4624     sock.settimeout(1)
4625     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4626     sock.bind(("239.255.255.250", 1900))
4627     dev[0].request("WPS_ER_START ifname=lo")
4628     (msg,addr) = sock.recvfrom(1000)
4629     logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4630     if "M-SEARCH" not in msg:
4631         raise Exception("Not an M-SEARCH")
4632     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1\r\ncache-control:max-age=1\r\n\r\n", addr)
4633     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4634     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1/:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
4635     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4636     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://255.255.255.255:0/foo.xml\r\ncache-control:max-age=1\r\n\r\n", addr)
4637     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4638
4639     sock.close()
4640
4641 def test_ap_wps_er_link_update(dev, apdev):
4642     """WPS ER and link update special cases"""
4643     class WPSAPHTTPServer_link_update(WPSAPHTTPServer):
4644         def handle_upnp_info(self):
4645             self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4646     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update)
4647
4648     class WPSAPHTTPServer_link_update2(WPSAPHTTPServer):
4649         def handle_others(self, data):
4650             if "GET / " in data:
4651                 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4652     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update2,
4653                           location_url='http://127.0.0.1:12345')
4654
4655 def test_ap_wps_er_http_client(dev, apdev):
4656     """WPS ER and HTTP client special cases"""
4657     with alloc_fail(dev[0], 1, "http_link_update"):
4658         run_wps_er_proto_test(dev[0], WPSAPHTTPServer)
4659
4660     with alloc_fail(dev[0], 1, "wpabuf_alloc;http_client_url"):
4661         run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4662
4663     with alloc_fail(dev[0], 1, "httpread_create;http_client_tx_ready"):
4664         run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4665
4666     class WPSAPHTTPServer_req_as_resp(WPSAPHTTPServer):
4667         def handle_upnp_info(self):
4668             self.wfile.write("GET / HTTP/1.1\r\n\r\n")
4669     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_req_as_resp,
4670                           no_event_url=True)
4671
4672 def test_ap_wps_init_oom(dev, apdev):
4673     """wps_init OOM cases"""
4674     ssid = "test-wps"
4675     appin = "12345670"
4676     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4677                "ap_pin": appin }
4678     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4679     pin = dev[0].wps_read_pin()
4680
4681     with alloc_fail(hapd, 1, "wps_init"):
4682         hapd.request("WPS_PIN any " + pin)
4683         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4684         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4685         ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4686         if ev is None:
4687             raise Exception("No EAP failure reported")
4688         dev[0].request("WPS_CANCEL")
4689
4690     with alloc_fail(dev[0], 2, "wps_init"):
4691         hapd.request("WPS_PIN any " + pin)
4692         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4693         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4694         ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4695         if ev is None:
4696             raise Exception("No EAP failure reported")
4697         dev[0].request("WPS_CANCEL")
4698
4699     with alloc_fail(dev[0], 2, "wps_init"):
4700         hapd.request("WPS_PBC")
4701         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4702         dev[0].request("WPS_PBC %s" % (apdev[0]['bssid']))
4703         ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4704         if ev is None:
4705             raise Exception("No EAP failure reported")
4706         dev[0].request("WPS_CANCEL")
4707
4708     dev[0].dump_monitor()
4709     new_ssid = "wps-new-ssid"
4710     new_passphrase = "1234567890"
4711     with alloc_fail(dev[0], 3, "wps_init"):
4712         dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
4713                        new_passphrase, no_wait=True)
4714         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4715         if ev is None:
4716             raise Exception("No EAP failure reported")
4717
4718     dev[0].flush_scan_cache()
4719
4720 def test_ap_wps_invalid_assoc_req_elem(dev, apdev):
4721     """WPS and invalid IE in Association Request frame"""
4722     ssid = "test-wps"
4723     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4724     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4725     pin = "12345670"
4726     hapd.request("WPS_PIN any " + pin)
4727     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4728     try:
4729         dev[0].request("VENDOR_ELEM_ADD 13 dd050050f20410")
4730         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4731         for i in range(5):
4732             ev = hapd.wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=10)
4733             if ev and "vendor=14122" in ev:
4734                 break
4735         if ev is None or "vendor=14122" not in ev:
4736             raise Exception("EAP-WSC not started")
4737         dev[0].request("WPS_CANCEL")
4738     finally:
4739         dev[0].request("VENDOR_ELEM_REMOVE 13 *")
4740
4741 def test_ap_wps_pbc_pin_mismatch(dev, apdev):
4742     """WPS PBC/PIN mismatch"""
4743     ssid = "test-wps"
4744     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4745     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4746     hapd.request("SET wps_version_number 0x10")
4747     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4748     hapd.request("WPS_PBC")
4749     pin = dev[0].wps_read_pin()
4750     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4751     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4752     if ev is None:
4753         raise Exception("Scan did not complete")
4754     dev[0].request("WPS_CANCEL")
4755
4756     hapd.request("WPS_CANCEL")
4757     dev[0].flush_scan_cache()
4758
4759 def test_ap_wps_ie_invalid(dev, apdev):
4760     """WPS PIN attempt with AP that has invalid WSC IE"""
4761     ssid = "test-wps"
4762     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4763                "vendor_elements": "dd050050f20410" }
4764     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4765     params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
4766     hostapd.add_ap(apdev[1]['ifname'], params)
4767     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4768     pin = dev[0].wps_read_pin()
4769     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4770     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4771     if ev is None:
4772         raise Exception("Scan did not complete")
4773     dev[0].request("WPS_CANCEL")
4774
4775 def test_ap_wps_scan_prio_order(dev, apdev):
4776     """WPS scan priority ordering"""
4777     ssid = "test-wps"
4778     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4779     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4780     params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
4781     hostapd.add_ap(apdev[1]['ifname'], params)
4782     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4783     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
4784     pin = dev[0].wps_read_pin()
4785     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4786     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4787     if ev is None:
4788         raise Exception("Scan did not complete")
4789     dev[0].request("WPS_CANCEL")
4790
4791 def test_ap_wps_probe_req_ie_oom(dev, apdev):
4792     """WPS ProbeReq IE OOM"""
4793     ssid = "test-wps"
4794     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4795     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4796     pin = dev[0].wps_read_pin()
4797     hapd.request("WPS_PIN any " + pin)
4798     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4799     with alloc_fail(dev[0], 1, "wps_build_probe_req_ie"):
4800         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4801         ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4802         if ev is None:
4803             raise Exception("Association not seen")
4804     dev[0].request("WPS_CANCEL")
4805
4806     with alloc_fail(dev[0], 1, "wps_ie_encapsulate"):
4807         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4808         ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4809         if ev is None:
4810             raise Exception("Association not seen")
4811     dev[0].request("WPS_CANCEL")
4812
4813 def test_ap_wps_assoc_req_ie_oom(dev, apdev):
4814     """WPS AssocReq IE OOM"""
4815     ssid = "test-wps"
4816     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4817     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4818     pin = dev[0].wps_read_pin()
4819     hapd.request("WPS_PIN any " + pin)
4820     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4821     with alloc_fail(dev[0], 1, "wps_build_assoc_req_ie"):
4822         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4823         ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4824         if ev is None:
4825             raise Exception("Association not seen")
4826     dev[0].request("WPS_CANCEL")
4827
4828 def test_ap_wps_assoc_resp_ie_oom(dev, apdev):
4829     """WPS AssocResp IE OOM"""
4830     ssid = "test-wps"
4831     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4832     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4833     pin = dev[0].wps_read_pin()
4834     hapd.request("WPS_PIN any " + pin)
4835     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4836     with alloc_fail(hapd, 1, "wps_build_assoc_resp_ie"):
4837         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4838         ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4839         if ev is None:
4840             raise Exception("Association not seen")
4841     dev[0].request("WPS_CANCEL")
4842
4843 def test_ap_wps_bss_info_errors(dev, apdev):
4844     """WPS BSS info errors"""
4845     params = { "ssid": "1",
4846                "vendor_elements": "dd0e0050f20410440001ff101100010a" }
4847     hostapd.add_ap(apdev[0]['ifname'], params)
4848     params = { 'ssid': "2", "vendor_elements": "dd050050f20410" }
4849     hostapd.add_ap(apdev[1]['ifname'], params)
4850     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4851     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
4852     bss = dev[0].get_bss(apdev[0]['bssid'])
4853     logger.info("BSS: " + str(bss))
4854     if "wps_state" in bss:
4855         raise Exception("Unexpected wps_state in BSS info")
4856     if 'wps_device_name' not in bss:
4857         raise Exception("No wps_device_name in BSS info")
4858     if bss['wps_device_name'] != '_':
4859         raise Exception("Unexpected wps_device_name value")
4860     bss = dev[0].get_bss(apdev[1]['bssid'])
4861     logger.info("BSS: " + str(bss))
4862
4863     with alloc_fail(dev[0], 1, "=wps_attr_text"):
4864         bss = dev[0].get_bss(apdev[0]['bssid'])
4865         logger.info("BSS(OOM): " + str(bss))
4866
4867 def wps_run_pbc_fail_ap(apdev, dev, hapd):
4868     hapd.request("WPS_PBC")
4869     dev.scan_for_bss(apdev['bssid'], freq="2412")
4870     dev.request("WPS_PBC " + apdev['bssid'])
4871     ev = dev.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4872     if ev is None:
4873         raise Exception("No EAP failure reported")
4874     dev.request("WPS_CANCEL")
4875     dev.wait_disconnected()
4876     for i in range(5):
4877         try:
4878             dev.flush_scan_cache()
4879             break
4880         except Exception, e:
4881             if str(e).startswith("Failed to trigger scan"):
4882                 # Try again
4883                 time.sleep(1)
4884             else:
4885                 raise
4886
4887 def wps_run_pbc_fail(apdev, dev):
4888     hapd = wps_start_ap(apdev)
4889     wps_run_pbc_fail_ap(apdev, dev, hapd)
4890
4891 def test_ap_wps_pk_oom(dev, apdev):
4892     """WPS and public key OOM"""
4893     with alloc_fail(dev[0], 1, "wps_build_public_key"):
4894         wps_run_pbc_fail(apdev[0], dev[0])
4895
4896 def test_ap_wps_pk_oom_ap(dev, apdev):
4897     """WPS and public key OOM on AP"""
4898     hapd = wps_start_ap(apdev[0])
4899     with alloc_fail(hapd, 1, "wps_build_public_key"):
4900         wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
4901
4902 def test_ap_wps_encr_oom_ap(dev, apdev):
4903     """WPS and encrypted settings decryption OOM on AP"""
4904     hapd = wps_start_ap(apdev[0])
4905     pin = dev[0].wps_read_pin()
4906     hapd.request("WPS_PIN any " + pin)
4907     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4908     with alloc_fail(hapd, 1, "wps_decrypt_encr_settings"):
4909         dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
4910         ev = hapd.wait_event(["WPS-FAIL"], timeout=10)
4911         if ev is None:
4912             raise Exception("No WPS-FAIL reported")
4913         dev[0].request("WPS_CANCEL")
4914     dev[0].wait_disconnected()
4915
4916 def test_ap_wps_encr_no_random_ap(dev, apdev):
4917     """WPS and no random data available for encryption on AP"""
4918     hapd = wps_start_ap(apdev[0])
4919     with fail_test(hapd, 1, "os_get_random;wps_build_encr_settings"):
4920         wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
4921
4922 def test_ap_wps_e_hash_no_random_sta(dev, apdev):
4923     """WPS and no random data available for e-hash on STA"""
4924     with fail_test(dev[0], 1, "os_get_random;wps_build_e_hash"):
4925         wps_run_pbc_fail(apdev[0], dev[0])
4926
4927 def test_ap_wps_m1_no_random(dev, apdev):
4928     """WPS and no random for M1 on STA"""
4929     with fail_test(dev[0], 1, "os_get_random;wps_build_m1"):
4930         wps_run_pbc_fail(apdev[0], dev[0])
4931
4932 def test_ap_wps_m1_oom(dev, apdev):
4933     """WPS and OOM for M1 on STA"""
4934     with alloc_fail(dev[0], 1, "wps_build_m1"):
4935         wps_run_pbc_fail(apdev[0], dev[0])
4936
4937 def test_ap_wps_m3_oom(dev, apdev):
4938     """WPS and OOM for M3 on STA"""
4939     with alloc_fail(dev[0], 1, "wps_build_m3"):
4940         wps_run_pbc_fail(apdev[0], dev[0])
4941
4942 def test_ap_wps_m5_oom(dev, apdev):
4943     """WPS and OOM for M5 on STA"""
4944     hapd = wps_start_ap(apdev[0])
4945     hapd.request("WPS_PBC")
4946     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4947     for i in range(1, 3):
4948         with alloc_fail(dev[0], i, "wps_build_m5"):
4949             dev[0].request("WPS_PBC " + apdev[0]['bssid'])
4950             ev = dev[0].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             dev[0].wait_disconnected()
4955     dev[0].flush_scan_cache()
4956
4957 def test_ap_wps_m5_no_random(dev, apdev):
4958     """WPS and no random for M5 on STA"""
4959     with fail_test(dev[0], 1,
4960                    "os_get_random;wps_build_encr_settings;wps_build_m5"):
4961         wps_run_pbc_fail(apdev[0], dev[0])
4962
4963 def test_ap_wps_m7_oom(dev, apdev):
4964     """WPS and OOM for M7 on STA"""
4965     hapd = wps_start_ap(apdev[0])
4966     hapd.request("WPS_PBC")
4967     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4968     for i in range(1, 3):
4969         with alloc_fail(dev[0], i, "wps_build_m7"):
4970             dev[0].request("WPS_PBC " + apdev[0]['bssid'])
4971             ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4972             if ev is None:
4973                 raise Exception("No EAP failure reported")
4974             dev[0].request("WPS_CANCEL")
4975             dev[0].wait_disconnected()
4976     dev[0].flush_scan_cache()
4977
4978 def test_ap_wps_m7_no_random(dev, apdev):
4979     """WPS and no random for M7 on STA"""
4980     with fail_test(dev[0], 1,
4981                    "os_get_random;wps_build_encr_settings;wps_build_m7"):
4982         wps_run_pbc_fail(apdev[0], dev[0])
4983
4984 def test_ap_wps_wsc_done_oom(dev, apdev):
4985     """WPS and OOM for WSC_Done on STA"""
4986     with alloc_fail(dev[0], 1, "wps_build_wsc_done"):
4987         wps_run_pbc_fail(apdev[0], dev[0])
4988
4989 def test_ap_wps_random_psk_fail(dev, apdev):
4990     """WPS and no random for PSK on AP"""
4991     ssid = "test-wps"
4992     pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
4993     appin = "12345670"
4994     try:
4995         os.remove(pskfile)
4996     except:
4997         pass
4998
4999     try:
5000         with open(pskfile, "w") as f:
5001             f.write("# WPA PSKs\n")
5002
5003         params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5004                    "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
5005                    "rsn_pairwise": "CCMP", "ap_pin": appin,
5006                    "wpa_psk_file": pskfile }
5007         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
5008
5009         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5010         with fail_test(hapd, 1, "os_get_random;wps_build_cred_network_key"):
5011             dev[0].request("WPS_REG " + apdev[0]['bssid'] + " " + appin)
5012             ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5013             if ev is None:
5014                 raise Exception("No EAP failure reported")
5015             dev[0].request("WPS_CANCEL")
5016         dev[0].wait_disconnected()
5017
5018         with fail_test(hapd, 1, "os_get_random;wps_build_cred"):
5019             wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5020
5021         with alloc_fail(hapd, 1, "wps_build_cred"):
5022             wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5023
5024         with alloc_fail(hapd, 2, "wps_build_cred"):
5025             wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5026     finally:
5027         os.remove(pskfile)
5028
5029 def wps_ext_eap_identity_req(dev, hapd, bssid):
5030     logger.debug("EAP-Identity/Request")
5031     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5032     if ev is None:
5033         raise Exception("Timeout on EAPOL-TX from hostapd")
5034     res = dev.request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
5035     if "OK" not in res:
5036         raise Exception("EAPOL_RX to wpa_supplicant failed")
5037
5038 def wps_ext_eap_identity_resp(hapd, dev, addr):
5039     ev = dev.wait_event(["EAPOL-TX"], timeout=10)
5040     if ev is None:
5041         raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
5042     res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
5043     if "OK" not in res:
5044         raise Exception("EAPOL_RX to hostapd failed")
5045
5046 def wps_ext_eap_wsc(dst, src, src_addr, msg):
5047     logger.debug(msg)
5048     ev = src.wait_event(["EAPOL-TX"], timeout=10)
5049     if ev is None:
5050         raise Exception("Timeout on EAPOL-TX")
5051     res = dst.request("EAPOL_RX " + src_addr + " " + ev.split(' ')[2])
5052     if "OK" not in res:
5053         raise Exception("EAPOL_RX failed")
5054
5055 def wps_start_ext(apdev, dev, pbc=False, pin=None):
5056     addr = dev.own_addr()
5057     bssid = apdev['bssid']
5058     ssid = "test-wps-conf"
5059     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5060                "wpa_passphrase": "12345678", "wpa": "2",
5061                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
5062     hapd = hostapd.add_ap(apdev['ifname'], params)
5063
5064     if pbc:
5065         hapd.request("WPS_PBC")
5066     else:
5067         if pin is None:
5068             pin = dev.wps_read_pin()
5069         hapd.request("WPS_PIN any " + pin)
5070     dev.scan_for_bss(bssid, freq="2412")
5071     hapd.request("SET ext_eapol_frame_io 1")
5072     dev.request("SET ext_eapol_frame_io 1")
5073
5074     if pbc:
5075         dev.request("WPS_PBC " + bssid)
5076     else:
5077         dev.request("WPS_PIN " + bssid + " " + pin)
5078     return addr,bssid,hapd
5079
5080 def wps_auth_corrupt(dst, src, addr):
5081     ev = src.wait_event(["EAPOL-TX"], timeout=10)
5082     if ev is None:
5083         raise Exception("Timeout on EAPOL-TX")
5084     src.request("SET ext_eapol_frame_io 0")
5085     dst.request("SET ext_eapol_frame_io 0")
5086     msg = ev.split(' ')[2]
5087     if msg[-24:-16] != '10050008':
5088         raise Exception("Could not find Authenticator attribute")
5089     # Corrupt Authenticator value
5090     msg = msg[:-1] + '%x' % ((int(msg[-1], 16) + 1) % 16)
5091     res = dst.request("EAPOL_RX " + addr + " " + msg)
5092     if "OK" not in res:
5093         raise Exception("EAPOL_RX failed")
5094
5095 def wps_fail_finish(hapd, dev, fail_str):
5096     ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5097     if ev is None:
5098         raise Exception("WPS-FAIL not indicated")
5099     if fail_str not in ev:
5100         raise Exception("Unexpected WPS-FAIL value: " + ev)
5101     dev.request("WPS_CANCEL")
5102     dev.wait_disconnected()
5103
5104 def wps_auth_corrupt_from_ap(dev, hapd, bssid, fail_str):
5105     wps_auth_corrupt(dev, hapd, bssid)
5106     wps_fail_finish(hapd, dev, fail_str)
5107
5108 def wps_auth_corrupt_to_ap(dev, hapd, addr, fail_str):
5109     wps_auth_corrupt(hapd, dev, addr)
5110     wps_fail_finish(hapd, dev, fail_str)
5111
5112 def test_ap_wps_authenticator_mismatch_m2(dev, apdev):
5113     """WPS and Authenticator attribute mismatch in M2"""
5114     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5115     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5116     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5117     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5118     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5119     logger.debug("M2")
5120     wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=5")
5121
5122 def test_ap_wps_authenticator_mismatch_m3(dev, apdev):
5123     """WPS and Authenticator attribute mismatch in M3"""
5124     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5125     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5126     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5127     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5128     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5129     wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5130     logger.debug("M3")
5131     wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=7")
5132
5133 def test_ap_wps_authenticator_mismatch_m4(dev, apdev):
5134     """WPS and Authenticator attribute mismatch in M4"""
5135     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5136     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5137     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5138     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5139     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5140     wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5141     wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5142     logger.debug("M4")
5143     wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=8")
5144
5145 def test_ap_wps_authenticator_mismatch_m5(dev, apdev):
5146     """WPS and Authenticator attribute mismatch in M5"""
5147     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5148     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5149     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5150     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5151     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5152     wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5153     wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5154     wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5155     logger.debug("M5")
5156     wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=9")
5157
5158 def test_ap_wps_authenticator_mismatch_m6(dev, apdev):
5159     """WPS and Authenticator attribute mismatch in M6"""
5160     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5161     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5162     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5163     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5164     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5165     wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5166     wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5167     wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5168     wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5169     logger.debug("M6")
5170     wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=10")
5171
5172 def test_ap_wps_authenticator_mismatch_m7(dev, apdev):
5173     """WPS and Authenticator attribute mismatch in M7"""
5174     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5175     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5176     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5177     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5178     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5179     wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5180     wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5181     wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5182     wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5183     wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5184     logger.debug("M7")
5185     wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=11")
5186
5187 def test_ap_wps_authenticator_mismatch_m8(dev, apdev):
5188     """WPS and Authenticator attribute mismatch in M8"""
5189     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5190     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5191     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5192     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5193     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5194     wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5195     wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5196     wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5197     wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5198     wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5199     wps_ext_eap_wsc(hapd, dev[0], addr, "M7")
5200     logger.debug("M8")
5201     wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=12")
5202
5203 def test_ap_wps_authenticator_missing_m2(dev, apdev):
5204     """WPS and Authenticator attribute missing from M2"""
5205     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5206     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5207     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5208     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5209     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5210     logger.debug("M2")
5211     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5212     if ev is None:
5213         raise Exception("Timeout on EAPOL-TX")
5214     hapd.request("SET ext_eapol_frame_io 0")
5215     dev[0].request("SET ext_eapol_frame_io 0")
5216     msg = ev.split(' ')[2]
5217     if msg[-24:-16] != '10050008':
5218         raise Exception("Could not find Authenticator attribute")
5219     # Remove Authenticator value
5220     msg = msg[:-24]
5221     mlen = "%04x" % (int(msg[4:8], 16) - 12)
5222     msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:]
5223     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5224     if "OK" not in res:
5225         raise Exception("EAPOL_RX failed")
5226     wps_fail_finish(hapd, dev[0], "msg=5")
5227
5228 def test_ap_wps_m2_dev_passwd_id_p2p(dev, apdev):
5229     """WPS and M2 with different Device Password ID (P2P)"""
5230     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5231     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5232     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5233     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5234     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5235     logger.debug("M2")
5236     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5237     if ev is None:
5238         raise Exception("Timeout on EAPOL-TX")
5239     hapd.request("SET ext_eapol_frame_io 0")
5240     dev[0].request("SET ext_eapol_frame_io 0")
5241     msg = ev.split(' ')[2]
5242     if msg[722:730] != '10120002':
5243         raise Exception("Could not find Device Password ID attribute")
5244     # Replace Device Password ID value. This will fail Authenticator check, but
5245     # allows the code path in wps_process_dev_pw_id() to be checked from debug
5246     # log.
5247     msg = msg[0:730] + "0005" + msg[734:]
5248     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5249     if "OK" not in res:
5250         raise Exception("EAPOL_RX failed")
5251     wps_fail_finish(hapd, dev[0], "msg=5")
5252
5253 def test_ap_wps_m2_dev_passwd_id_change_pin_to_pbc(dev, apdev):
5254     """WPS and M2 with different Device Password ID (PIN to PBC)"""
5255     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5256     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5257     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5258     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5259     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5260     logger.debug("M2")
5261     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5262     if ev is None:
5263         raise Exception("Timeout on EAPOL-TX")
5264     hapd.request("SET ext_eapol_frame_io 0")
5265     dev[0].request("SET ext_eapol_frame_io 0")
5266     msg = ev.split(' ')[2]
5267     if msg[722:730] != '10120002':
5268         raise Exception("Could not find Device Password ID attribute")
5269     # Replace Device Password ID value (PIN --> PBC). This will be rejected.
5270     msg = msg[0:730] + "0004" + msg[734:]
5271     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5272     if "OK" not in res:
5273         raise Exception("EAPOL_RX failed")
5274     wps_fail_finish(hapd, dev[0], "msg=5")
5275
5276 def test_ap_wps_m2_dev_passwd_id_change_pbc_to_pin(dev, apdev):
5277     """WPS and M2 with different Device Password ID (PBC to PIN)"""
5278     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5279     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5280     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5281     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5282     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5283     logger.debug("M2")
5284     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5285     if ev is None:
5286         raise Exception("Timeout on EAPOL-TX")
5287     hapd.request("SET ext_eapol_frame_io 0")
5288     dev[0].request("SET ext_eapol_frame_io 0")
5289     msg = ev.split(' ')[2]
5290     if msg[722:730] != '10120002':
5291         raise Exception("Could not find Device Password ID attribute")
5292     # Replace Device Password ID value. This will fail Authenticator check, but
5293     # allows the code path in wps_process_dev_pw_id() to be checked from debug
5294     # log.
5295     msg = msg[0:730] + "0000" + msg[734:]
5296     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5297     if "OK" not in res:
5298         raise Exception("EAPOL_RX failed")
5299     wps_fail_finish(hapd, dev[0], "msg=5")
5300     dev[0].flush_scan_cache()
5301
5302 def test_ap_wps_m2_missing_dev_passwd_id(dev, apdev):
5303     """WPS and M2 without Device Password ID"""
5304     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5305     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5306     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5307     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5308     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5309     logger.debug("M2")
5310     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5311     if ev is None:
5312         raise Exception("Timeout on EAPOL-TX")
5313     hapd.request("SET ext_eapol_frame_io 0")
5314     dev[0].request("SET ext_eapol_frame_io 0")
5315     msg = ev.split(' ')[2]
5316     if msg[722:730] != '10120002':
5317         raise Exception("Could not find Device Password ID attribute")
5318     # Remove Device Password ID value. This will fail Authenticator check, but
5319     # allows the code path in wps_process_dev_pw_id() to be checked from debug
5320     # log.
5321     mlen = "%04x" % (int(msg[4:8], 16) - 6)
5322     msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:722] + msg[734:]
5323     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5324     if "OK" not in res:
5325         raise Exception("EAPOL_RX failed")
5326     wps_fail_finish(hapd, dev[0], "msg=5")
5327
5328 def test_ap_wps_m2_missing_registrar_nonce(dev, apdev):
5329     """WPS and M2 without Registrar Nonce"""
5330     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5331     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5332     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5333     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5334     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5335     logger.debug("M2")
5336     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5337     if ev is None:
5338         raise Exception("Timeout on EAPOL-TX")
5339     hapd.request("SET ext_eapol_frame_io 0")
5340     dev[0].request("SET ext_eapol_frame_io 0")
5341     msg = ev.split(' ')[2]
5342     if msg[96:104] != '10390010':
5343         raise Exception("Could not find Registrar Nonce attribute")
5344     # Remove Registrar Nonce. This will fail Authenticator check, but
5345     # allows the code path in wps_process_registrar_nonce() to be checked from
5346     # the debug log.
5347     mlen = "%04x" % (int(msg[4:8], 16) - 20)
5348     msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:96] + msg[136:]
5349     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5350     if "OK" not in res:
5351         raise Exception("EAPOL_RX failed")
5352     ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5353     if ev is None:
5354         raise Exception("Disconnect event not seen")
5355     dev[0].request("WPS_CANCEL")
5356     dev[0].flush_scan_cache()
5357
5358 def test_ap_wps_m2_missing_enrollee_nonce(dev, apdev):
5359     """WPS and M2 without Enrollee Nonce"""
5360     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5361     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5362     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5363     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5364     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5365     logger.debug("M2")
5366     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5367     if ev is None:
5368         raise Exception("Timeout on EAPOL-TX")
5369     hapd.request("SET ext_eapol_frame_io 0")
5370     dev[0].request("SET ext_eapol_frame_io 0")
5371     msg = ev.split(' ')[2]
5372     if msg[56:64] != '101a0010':
5373         raise Exception("Could not find enrollee Nonce attribute")
5374     # Remove Enrollee Nonce. This will fail Authenticator check, but
5375     # allows the code path in wps_process_enrollee_nonce() to be checked from
5376     # the debug log.
5377     mlen = "%04x" % (int(msg[4:8], 16) - 20)
5378     msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:56] + msg[96:]
5379     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5380     if "OK" not in res:
5381         raise Exception("EAPOL_RX failed")
5382     ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5383     if ev is None:
5384         raise Exception("Disconnect event not seen")
5385     dev[0].request("WPS_CANCEL")
5386     dev[0].flush_scan_cache()
5387
5388 def test_ap_wps_m2_missing_uuid_r(dev, apdev):
5389     """WPS and M2 without UUID-R"""
5390     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5391     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5392     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5393     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5394     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5395     logger.debug("M2")
5396     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5397     if ev is None:
5398         raise Exception("Timeout on EAPOL-TX")
5399     hapd.request("SET ext_eapol_frame_io 0")
5400     dev[0].request("SET ext_eapol_frame_io 0")
5401     msg = ev.split(' ')[2]
5402     if msg[136:144] != '10480010':
5403         raise Exception("Could not find enrollee Nonce attribute")
5404     # Remove UUID-R. This will fail Authenticator check, but allows the code
5405     # path in wps_process_uuid_r() to be checked from the debug log.
5406     mlen = "%04x" % (int(msg[4:8], 16) - 20)
5407     msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:136] + msg[176:]
5408     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5409     if "OK" not in res:
5410         raise Exception("EAPOL_RX failed")
5411     ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5412     if ev is None:
5413         raise Exception("Disconnect event not seen")
5414     dev[0].request("WPS_CANCEL")
5415     dev[0].flush_scan_cache()
5416
5417 def test_ap_wps_m2_invalid(dev, apdev):
5418     """WPS and M2 parsing failure"""
5419     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5420     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5421     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5422     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5423     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5424     logger.debug("M2")
5425     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5426     if ev is None:
5427         raise Exception("Timeout on EAPOL-TX")
5428     hapd.request("SET ext_eapol_frame_io 0")
5429     dev[0].request("SET ext_eapol_frame_io 0")
5430     msg = ev.split(' ')[2]
5431     if msg[136:144] != '10480010':
5432         raise Exception("Could not find enrollee Nonce attribute")
5433     # Remove UUID-R. This will fail Authenticator check, but allows the code
5434     # path in wps_process_uuid_r() to be checked from the debug log.
5435     mlen = "%04x" % (int(msg[4:8], 16) - 1)
5436     msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:-2]
5437     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5438     if "OK" not in res:
5439         raise Exception("EAPOL_RX failed")
5440     ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5441     if ev is None:
5442         raise Exception("Disconnect event not seen")
5443     dev[0].request("WPS_CANCEL")
5444     dev[0].flush_scan_cache()
5445
5446 def test_ap_wps_m2_missing_msg_type(dev, apdev):
5447     """WPS and M2 without Message Type"""
5448     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
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     logger.debug("M2")
5454     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5455     if ev is None:
5456         raise Exception("Timeout on EAPOL-TX")
5457     hapd.request("SET ext_eapol_frame_io 0")
5458     dev[0].request("SET ext_eapol_frame_io 0")
5459     msg = ev.split(' ')[2]
5460     if msg[46:54] != '10220001':
5461         raise Exception("Could not find Message Type attribute")
5462     # Remove Message Type. This will fail Authenticator check, but allows the
5463     # code path in wps_process_wsc_msg() to be checked from the debug log.
5464     mlen = "%04x" % (int(msg[4:8], 16) - 5)
5465     msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:46] + msg[56:]
5466     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5467     if "OK" not in res:
5468         raise Exception("EAPOL_RX failed")
5469     ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5470     if ev is None:
5471         raise Exception("Disconnect event not seen")
5472     dev[0].request("WPS_CANCEL")
5473     dev[0].flush_scan_cache()
5474
5475 def test_ap_wps_m2_unknown_msg_type(dev, apdev):
5476     """WPS and M2 but unknown Message Type"""
5477     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
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     logger.debug("M2")
5483     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5484     if ev is None:
5485         raise Exception("Timeout on EAPOL-TX")
5486     hapd.request("SET ext_eapol_frame_io 0")
5487     dev[0].request("SET ext_eapol_frame_io 0")
5488     msg = ev.split(' ')[2]
5489     if msg[46:54] != '10220001':
5490         raise Exception("Could not find Message Type attribute")
5491     # Replace Message Type value. This will be rejected.
5492     msg = msg[0:54] + "00" + msg[56:]
5493     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5494     if "OK" not in res:
5495         raise Exception("EAPOL_RX failed")
5496     ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5497     if ev is None:
5498         raise Exception("Disconnect event not seen")
5499     dev[0].request("WPS_CANCEL")
5500     dev[0].flush_scan_cache()
5501
5502 def test_ap_wps_m2_unknown_opcode(dev, apdev):
5503     """WPS and M2 but unknown opcode"""
5504     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5505     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5506     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5507     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5508     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5509     logger.debug("M2")
5510     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5511     if ev is None:
5512         raise Exception("Timeout on EAPOL-TX")
5513     hapd.request("SET ext_eapol_frame_io 0")
5514     dev[0].request("SET ext_eapol_frame_io 0")
5515     msg = ev.split(' ')[2]
5516     # Replace opcode. This will be discarded in EAP-WSC processing.
5517     msg = msg[0:32] + "00" + msg[34:]
5518     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5519     if "OK" not in res:
5520         raise Exception("EAPOL_RX failed")
5521     dev[0].request("WPS_CANCEL")
5522     dev[0].wait_disconnected()
5523     dev[0].flush_scan_cache()
5524
5525 def test_ap_wps_m2_unknown_opcode2(dev, apdev):
5526     """WPS and M2 but unknown opcode (WSC_Start)"""
5527     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5528     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5529     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5530     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5531     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5532     logger.debug("M2")
5533     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5534     if ev is None:
5535         raise Exception("Timeout on EAPOL-TX")
5536     hapd.request("SET ext_eapol_frame_io 0")
5537     dev[0].request("SET ext_eapol_frame_io 0")
5538     msg = ev.split(' ')[2]
5539     # Replace opcode. This will be discarded in EAP-WSC processing.
5540     msg = msg[0:32] + "01" + msg[34:]
5541     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5542     if "OK" not in res:
5543         raise Exception("EAPOL_RX failed")
5544     dev[0].request("WPS_CANCEL")
5545     dev[0].wait_disconnected()
5546     dev[0].flush_scan_cache()
5547
5548 def test_ap_wps_m2_unknown_opcode3(dev, apdev):
5549     """WPS and M2 but unknown opcode (WSC_Done)"""
5550     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5551     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5552     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5553     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5554     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5555     logger.debug("M2")
5556     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5557     if ev is None:
5558         raise Exception("Timeout on EAPOL-TX")
5559     hapd.request("SET ext_eapol_frame_io 0")
5560     dev[0].request("SET ext_eapol_frame_io 0")
5561     msg = ev.split(' ')[2]
5562     # Replace opcode. This will be discarded in WPS Enrollee processing.
5563     msg = msg[0:32] + "05" + msg[34:]
5564     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5565     if "OK" not in res:
5566         raise Exception("EAPOL_RX failed")
5567     dev[0].request("WPS_CANCEL")
5568     dev[0].wait_disconnected()
5569     dev[0].flush_scan_cache()
5570
5571 def wps_m2_but_other(dev, apdev, title, msgtype):
5572     addr,bssid,hapd = wps_start_ext(apdev, dev)
5573     wps_ext_eap_identity_req(dev, hapd, bssid)
5574     wps_ext_eap_identity_resp(hapd, dev, addr)
5575     wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5576     wps_ext_eap_wsc(hapd, dev, addr, "M1")
5577     logger.debug(title)
5578     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5579     if ev is None:
5580         raise Exception("Timeout on EAPOL-TX")
5581     hapd.request("SET ext_eapol_frame_io 0")
5582     dev.request("SET ext_eapol_frame_io 0")
5583     msg = ev.split(' ')[2]
5584     if msg[46:54] != '10220001':
5585         raise Exception("Could not find Message Type attribute")
5586     # Replace Message Type value. This will be rejected.
5587     msg = msg[0:54] + msgtype + msg[56:]
5588     res = dev.request("EAPOL_RX " + bssid + " " + msg)
5589     if "OK" not in res:
5590         raise Exception("EAPOL_RX failed")
5591     ev = dev.wait_event(["WPS-FAIL"], timeout=5)
5592     if ev is None:
5593         raise Exception("WPS-FAIL event not seen")
5594     dev.request("WPS_CANCEL")
5595     dev.wait_disconnected()
5596
5597 def wps_m4_but_other(dev, apdev, title, msgtype):
5598     addr,bssid,hapd = wps_start_ext(apdev, dev)
5599     wps_ext_eap_identity_req(dev, hapd, bssid)
5600     wps_ext_eap_identity_resp(hapd, dev, addr)
5601     wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5602     wps_ext_eap_wsc(hapd, dev, addr, "M1")
5603     wps_ext_eap_wsc(dev, hapd, bssid, "M2")
5604     wps_ext_eap_wsc(hapd, dev, addr, "M3")
5605     logger.debug(title)
5606     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5607     if ev is None:
5608         raise Exception("Timeout on EAPOL-TX")
5609     hapd.request("SET ext_eapol_frame_io 0")
5610     dev.request("SET ext_eapol_frame_io 0")
5611     msg = ev.split(' ')[2]
5612     if msg[46:54] != '10220001':
5613         raise Exception("Could not find Message Type attribute")
5614     # Replace Message Type value. This will be rejected.
5615     msg = msg[0:54] + msgtype + msg[56:]
5616     res = dev.request("EAPOL_RX " + bssid + " " + msg)
5617     if "OK" not in res:
5618         raise Exception("EAPOL_RX failed")
5619     ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5620     if ev is None:
5621         raise Exception("WPS-FAIL event not seen")
5622     dev.request("WPS_CANCEL")
5623     dev.wait_disconnected()
5624
5625 def test_ap_wps_m2_msg_type_m4(dev, apdev):
5626     """WPS and M2 but Message Type M4"""
5627     wps_m2_but_other(dev[0], apdev[0], "M2/M4", "08")
5628
5629 def test_ap_wps_m2_msg_type_m6(dev, apdev):
5630     """WPS and M2 but Message Type M6"""
5631     wps_m2_but_other(dev[0], apdev[0], "M2/M6", "0a")
5632
5633 def test_ap_wps_m2_msg_type_m8(dev, apdev):
5634     """WPS and M2 but Message Type M8"""
5635     wps_m2_but_other(dev[0], apdev[0], "M2/M8", "0c")
5636
5637 def test_ap_wps_m4_msg_type_m2(dev, apdev):
5638     """WPS and M4 but Message Type M2"""
5639     wps_m4_but_other(dev[0], apdev[0], "M4/M2", "05")
5640
5641 def test_ap_wps_m4_msg_type_m2d(dev, apdev):
5642     """WPS and M4 but Message Type M2D"""
5643     wps_m4_but_other(dev[0], apdev[0], "M4/M2D", "06")
5644
5645 def test_ap_wps_config_methods(dev, apdev):
5646     """WPS configuration method parsing"""
5647     ssid = "test-wps-conf"
5648     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5649                "wpa_passphrase": "12345678", "wpa": "2",
5650                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5651                "config_methods": "ethernet display ext_nfc_token int_nfc_token physical_display physical_push_button" }
5652     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
5653     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5654                "wpa_passphrase": "12345678", "wpa": "2",
5655                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5656                "config_methods": "display push_button" }
5657     hapd2 = hostapd.add_ap(apdev[1]['ifname'], params)
5658
5659 def test_ap_wps_set_selected_registrar_proto(dev, apdev):
5660     """WPS UPnP SetSelectedRegistrar protocol testing"""
5661     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
5662     hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
5663
5664     location = ssdp_get_location(ap_uuid)
5665     urls = upnp_get_urls(location)
5666     eventurl = urlparse.urlparse(urls['event_sub_url'])
5667     ctrlurl = urlparse.urlparse(urls['control_url'])
5668     url = urlparse.urlparse(location)
5669     conn = httplib.HTTPConnection(url.netloc)
5670
5671     class WPSERHTTPServer(SocketServer.StreamRequestHandler):
5672         def handle(self):
5673             data = self.rfile.readline().strip()
5674             logger.debug(data)
5675             self.wfile.write(gen_wps_event())
5676
5677     server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
5678     server.timeout = 1
5679
5680     headers = { "callback": '<http://127.0.0.1:12345/event>',
5681                 "NT": "upnp:event",
5682                 "timeout": "Second-1234" }
5683     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
5684     resp = conn.getresponse()
5685     if resp.status != 200:
5686         raise Exception("Unexpected HTTP response: %d" % resp.status)
5687     sid = resp.getheader("sid")
5688     logger.debug("Subscription SID " + sid)
5689     server.handle_request()
5690
5691     tests = [ (500, "10"),
5692               (200, "104a000110" + "1041000101" + "101200020000" +
5693                "105300023148" +
5694                "1049002c00372a0001200124111111111111222222222222333333333333444444444444555555555555666666666666" +
5695                "10480010362db47ba53a519188fb5458b986b2e4"),
5696               (200, "104a000110" + "1041000100" + "101200020000" +
5697                "105300020000"),
5698               (200, "104a000110" + "1041000100"),
5699               (200, "104a000110") ]
5700     for status,test in tests:
5701         tlvs = binascii.unhexlify(test)
5702         newmsg = base64.b64encode(tlvs)
5703         msg = '<?xml version="1.0"?>\n'
5704         msg += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
5705         msg += '<s:Body>'
5706         msg += '<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">'
5707         msg += '<NewMessage>'
5708         msg += newmsg
5709         msg += "</NewMessage></u:SetSelectedRegistrar></s:Body></s:Envelope>"
5710         headers = { "Content-type": 'text/xml; charset="utf-8"' }
5711         headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
5712         conn.request("POST", ctrlurl.path, msg, headers)
5713         resp = conn.getresponse()
5714         if resp.status != status:
5715             raise Exception("Unexpected HTTP response: %d (expected %d)" % (resp.status, status))
5716
5717 def test_ap_wps_adv_oom(dev, apdev):
5718     """WPS AP and advertisement OOM"""
5719     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
5720     hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
5721
5722     with alloc_fail(hapd, 1, "=msearchreply_state_machine_start"):
5723         ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
5724                           no_recv=True)
5725         time.sleep(0.2)
5726
5727     with alloc_fail(hapd, 1, "eloop_register_timeout;msearchreply_state_machine_start"):
5728         ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
5729                           no_recv=True)
5730         time.sleep(0.2)
5731
5732     with alloc_fail(hapd, 1,
5733                     "next_advertisement;advertisement_state_machine_stop"):
5734         hapd.disable()
5735
5736     with alloc_fail(hapd, 1, "ssdp_listener_start"):
5737         if "FAIL" not in hapd.request("ENABLE"):
5738             raise Exception("ENABLE succeeded during OOM")
5739
5740 def test_wps_config_methods(dev):
5741     """WPS config method update"""
5742     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
5743     wpas.interface_add("wlan5")
5744     if "OK" not in wpas.request("SET config_methods display label"):
5745         raise Exception("Failed to set config_methods")
5746     if wpas.request("GET config_methods").strip() != "display label":
5747         raise Exception("config_methods were not updated")
5748     if "OK" not in wpas.request("SET config_methods "):
5749         raise Exception("Failed to clear config_methods")
5750     if wpas.request("GET config_methods").strip() != "":
5751         raise Exception("config_methods were not cleared")
5752
5753 WPS_VENDOR_ID_WFA = 14122
5754 WPS_VENDOR_TYPE = 1
5755
5756 # EAP-WSC Op-Code values
5757 WSC_Start = 0x01
5758 WSC_ACK = 0x02
5759 WSC_NACK = 0x03
5760 WSC_MSG = 0x04
5761 WSC_Done = 0x05
5762 WSC_FRAG_ACK = 0x06
5763
5764 ATTR_AP_CHANNEL = 0x1001
5765 ATTR_ASSOC_STATE = 0x1002
5766 ATTR_AUTH_TYPE = 0x1003
5767 ATTR_AUTH_TYPE_FLAGS = 0x1004
5768 ATTR_AUTHENTICATOR = 0x1005
5769 ATTR_CONFIG_METHODS = 0x1008
5770 ATTR_CONFIG_ERROR = 0x1009
5771 ATTR_CONFIRM_URL4 = 0x100a
5772 ATTR_CONFIRM_URL6 = 0x100b
5773 ATTR_CONN_TYPE = 0x100c
5774 ATTR_CONN_TYPE_FLAGS = 0x100d
5775 ATTR_CRED = 0x100e
5776 ATTR_ENCR_TYPE = 0x100f
5777 ATTR_ENCR_TYPE_FLAGS = 0x1010
5778 ATTR_DEV_NAME = 0x1011
5779 ATTR_DEV_PASSWORD_ID = 0x1012
5780 ATTR_E_HASH1 = 0x1014
5781 ATTR_E_HASH2 = 0x1015
5782 ATTR_E_SNONCE1 = 0x1016
5783 ATTR_E_SNONCE2 = 0x1017
5784 ATTR_ENCR_SETTINGS = 0x1018
5785 ATTR_ENROLLEE_NONCE = 0x101a
5786 ATTR_FEATURE_ID = 0x101b
5787 ATTR_IDENTITY = 0x101c
5788 ATTR_IDENTITY_PROOF = 0x101d
5789 ATTR_KEY_WRAP_AUTH = 0x101e
5790 ATTR_KEY_ID = 0x101f
5791 ATTR_MAC_ADDR = 0x1020
5792 ATTR_MANUFACTURER = 0x1021
5793 ATTR_MSG_TYPE = 0x1022
5794 ATTR_MODEL_NAME = 0x1023
5795 ATTR_MODEL_NUMBER = 0x1024
5796 ATTR_NETWORK_INDEX = 0x1026
5797 ATTR_NETWORK_KEY = 0x1027
5798 ATTR_NETWORK_KEY_INDEX = 0x1028
5799 ATTR_NEW_DEVICE_NAME = 0x1029
5800 ATTR_NEW_PASSWORD = 0x102a
5801 ATTR_OOB_DEVICE_PASSWORD = 0x102c
5802 ATTR_OS_VERSION = 0x102d
5803 ATTR_POWER_LEVEL = 0x102f
5804 ATTR_PSK_CURRENT = 0x1030
5805 ATTR_PSK_MAX = 0x1031
5806 ATTR_PUBLIC_KEY = 0x1032
5807 ATTR_RADIO_ENABLE = 0x1033
5808 ATTR_REBOOT = 0x1034
5809 ATTR_REGISTRAR_CURRENT = 0x1035
5810 ATTR_REGISTRAR_ESTABLISHED = 0x1036
5811 ATTR_REGISTRAR_LIST = 0x1037
5812 ATTR_REGISTRAR_MAX = 0x1038
5813 ATTR_REGISTRAR_NONCE = 0x1039
5814 ATTR_REQUEST_TYPE = 0x103a
5815 ATTR_RESPONSE_TYPE = 0x103b
5816 ATTR_RF_BANDS = 0x103c
5817 ATTR_R_HASH1 = 0x103d
5818 ATTR_R_HASH2 = 0x103e
5819 ATTR_R_SNONCE1 = 0x103f
5820 ATTR_R_SNONCE2 = 0x1040
5821 ATTR_SELECTED_REGISTRAR = 0x1041
5822 ATTR_SERIAL_NUMBER = 0x1042
5823 ATTR_WPS_STATE = 0x1044
5824 ATTR_SSID = 0x1045
5825 ATTR_TOTAL_NETWORKS = 0x1046
5826 ATTR_UUID_E = 0x1047
5827 ATTR_UUID_R = 0x1048
5828 ATTR_VENDOR_EXT = 0x1049
5829 ATTR_VERSION = 0x104a
5830 ATTR_X509_CERT_REQ = 0x104b
5831 ATTR_X509_CERT = 0x104c
5832 ATTR_EAP_IDENTITY = 0x104d
5833 ATTR_MSG_COUNTER = 0x104e
5834 ATTR_PUBKEY_HASH = 0x104f
5835 ATTR_REKEY_KEY = 0x1050
5836 ATTR_KEY_LIFETIME = 0x1051
5837 ATTR_PERMITTED_CFG_METHODS = 0x1052
5838 ATTR_SELECTED_REGISTRAR_CONFIG_METHODS = 0x1053
5839 ATTR_PRIMARY_DEV_TYPE = 0x1054
5840 ATTR_SECONDARY_DEV_TYPE_LIST = 0x1055
5841 ATTR_PORTABLE_DEV = 0x1056
5842 ATTR_AP_SETUP_LOCKED = 0x1057
5843 ATTR_APPLICATION_EXT = 0x1058
5844 ATTR_EAP_TYPE = 0x1059
5845 ATTR_IV = 0x1060
5846 ATTR_KEY_PROVIDED_AUTO = 0x1061
5847 ATTR_802_1X_ENABLED = 0x1062
5848 ATTR_APPSESSIONKEY = 0x1063
5849 ATTR_WEPTRANSMITKEY = 0x1064
5850 ATTR_REQUESTED_DEV_TYPE = 0x106a
5851
5852 # Message Type
5853 WPS_Beacon = 0x01
5854 WPS_ProbeRequest = 0x02
5855 WPS_ProbeResponse = 0x03
5856 WPS_M1 = 0x04
5857 WPS_M2 = 0x05
5858 WPS_M2D = 0x06
5859 WPS_M3 = 0x07
5860 WPS_M4 = 0x08
5861 WPS_M5 = 0x09
5862 WPS_M6 = 0x0a
5863 WPS_M7 = 0x0b
5864 WPS_M8 = 0x0c
5865 WPS_WSC_ACK = 0x0d
5866 WPS_WSC_NACK = 0x0e
5867 WPS_WSC_DONE = 0x0f
5868
5869 def get_wsc_msg(dev):
5870     ev = dev.wait_event(["EAPOL-TX"], timeout=10)
5871     if ev is None:
5872         raise Exception("Timeout on EAPOL-TX")
5873     data = binascii.unhexlify(ev.split(' ')[2])
5874     msg = {}
5875
5876     # Parse EAPOL header
5877     if len(data) < 4:
5878         raise Exception("No room for EAPOL header")
5879     version,type,length = struct.unpack('>BBH', data[0:4])
5880     msg['eapol_version'] = version
5881     msg['eapol_type'] = type
5882     msg['eapol_length'] = length
5883     data = data[4:]
5884     if length != len(data):
5885         raise Exception("EAPOL header length mismatch (%d != %d)" % (length, len(data)))
5886     if type != 0:
5887         raise Exception("Unexpected EAPOL header type: %d" % type)
5888
5889     # Parse EAP header
5890     if len(data) < 4:
5891         raise Exception("No room for EAP header")
5892     code,identifier,length = struct.unpack('>BBH', data[0:4])
5893     msg['eap_code'] = code
5894     msg['eap_identifier'] = identifier
5895     msg['eap_length'] = length
5896     data = data[4:]
5897     if msg['eapol_length'] != msg['eap_length']:
5898         raise Exception("EAP header length mismatch (%d != %d)" % (msg['eapol_length'], length))
5899
5900     # Parse EAP expanded header
5901     if len(data) < 1:
5902         raise Exception("No EAP type included")
5903     msg['eap_type'], = struct.unpack('B', data[0])
5904     data = data[1:]
5905
5906     if msg['eap_type'] == 254:
5907         if len(data) < 3 + 4:
5908             raise Exception("Truncated EAP expanded header")
5909         msg['eap_vendor_id'], msg['eap_vendor_type'] = struct.unpack('>LL', '\0' + data[0:7])
5910         data = data[7:]
5911     else:
5912         raise Exception("Unexpected EAP type")
5913
5914     if msg['eap_vendor_id'] != WPS_VENDOR_ID_WFA:
5915         raise Exception("Unexpected Vendor-Id")
5916     if msg['eap_vendor_type'] != WPS_VENDOR_TYPE:
5917         raise Exception("Unexpected Vendor-Type")
5918
5919     # Parse EAP-WSC header
5920     if len(data) < 2:
5921         raise Exception("Truncated EAP-WSC header")
5922     msg['wsc_opcode'], msg['wsc_flags'] = struct.unpack('BB', data[0:2])
5923     data = data[2:]
5924
5925     # Parse WSC attributes
5926     msg['raw_attrs'] = data
5927     attrs = {}
5928     while len(data) > 0:
5929         if len(data) < 4:
5930             raise Exception("Truncated attribute header")
5931         attr,length = struct.unpack('>HH', data[0:4])
5932         data = data[4:]
5933         if length > len(data):
5934             raise Exception("Truncated attribute 0x%04x" % attr)
5935         attrs[attr] = data[0:length]
5936         data = data[length:]
5937     msg['wsc_attrs'] = attrs
5938
5939     if ATTR_MSG_TYPE in attrs:
5940         msg['wsc_msg_type'], = struct.unpack('B', attrs[ATTR_MSG_TYPE])
5941
5942     return msg
5943
5944 def recv_wsc_msg(dev, opcode, msg_type):
5945     msg = get_wsc_msg(dev)
5946     if msg['wsc_opcode'] != opcode or msg['wsc_msg_type'] != msg_type:
5947         raise Exception("Unexpected Op-Code/MsgType")
5948     return msg, msg['wsc_attrs'], msg['raw_attrs']
5949
5950 def build_wsc_attr(attr, payload):
5951     return struct.pack('>HH', attr, len(payload)) + payload
5952
5953 def build_attr_msg_type(msg_type):
5954     return build_wsc_attr(ATTR_MSG_TYPE, struct.pack('B', msg_type))
5955
5956 def build_eap_wsc(eap_code, eap_id, payload, opcode=WSC_MSG):
5957     length = 4 + 8 + 2 + len(payload)
5958     # EAPOL header
5959     msg = struct.pack('>BBH', 2, 0, length)
5960     # EAP header
5961     msg += struct.pack('>BBH', eap_code, eap_id, length)
5962     # EAP expanded header for EAP-WSC
5963     msg += struct.pack('B', 254)
5964     msg += struct.pack('>L', WPS_VENDOR_ID_WFA)[1:4]
5965     msg += struct.pack('>L', WPS_VENDOR_TYPE)
5966     # EAP-WSC header
5967     msg += struct.pack('BB', opcode, 0)
5968     # WSC attributes
5969     msg += payload
5970     return msg
5971
5972 def build_eap_success(eap_id):
5973     length = 4
5974     # EAPOL header
5975     msg = struct.pack('>BBH', 2, 0, length)
5976     # EAP header
5977     msg += struct.pack('>BBH', 3, eap_id, length)
5978     return msg
5979
5980 def build_eap_failure(eap_id):
5981     length = 4
5982     # EAPOL header
5983     msg = struct.pack('>BBH', 2, 0, length)
5984     # EAP header
5985     msg += struct.pack('>BBH', 4, eap_id, length)
5986     return msg
5987
5988 def send_wsc_msg(dev, src, msg):
5989     res = dev.request("EAPOL_RX " + src + " " + binascii.hexlify(msg))
5990     if "OK" not in res:
5991         raise Exception("EAPOL_RX failed")
5992
5993 group_5_prime = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF
5994 group_5_generator = 2
5995
5996 def wsc_kdf(key, label, bits):
5997     result = ''
5998     i = 1
5999     while len(result) * 8 < bits:
6000         data = struct.pack('>L', i) + label + struct.pack('>L', bits)
6001         m = hmac.new(key, data, hashlib.sha256)
6002         result += m.digest()
6003         i += 1
6004     return result[0:bits / 8]
6005
6006 def wsc_keys(kdk):
6007     keys = wsc_kdf(kdk, "Wi-Fi Easy and Secure Key Derivation", 640)
6008     authkey = keys[0:32]
6009     keywrapkey = keys[32:48]
6010     emsk = keys[48:80]
6011     return authkey,keywrapkey,emsk
6012
6013 def wsc_dev_pw_half_psk(authkey, dev_pw):
6014     m = hmac.new(authkey, dev_pw, hashlib.sha256)
6015     return m.digest()[0:16]
6016
6017 def wsc_dev_pw_psk(authkey, dev_pw):
6018     dev_pw_1 = dev_pw[0:len(dev_pw) / 2]
6019     dev_pw_2 = dev_pw[len(dev_pw) / 2:]
6020     psk1 = wsc_dev_pw_half_psk(authkey, dev_pw_1)
6021     psk2 = wsc_dev_pw_half_psk(authkey, dev_pw_2)
6022     return psk1,psk2
6023
6024 def build_attr_authenticator(authkey, prev_msg, curr_msg):
6025     m = hmac.new(authkey, prev_msg + curr_msg, hashlib.sha256)
6026     auth = m.digest()[0:8]
6027     return build_wsc_attr(ATTR_AUTHENTICATOR, auth)
6028
6029 def build_attr_encr_settings(authkey, keywrapkey, data):
6030     m = hmac.new(authkey, data, hashlib.sha256)
6031     kwa = m.digest()[0:8]
6032     data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6033     iv = 16*'\x99'
6034     aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6035     pad_len = 16 - len(data) % 16
6036     ps = pad_len * struct.pack('B', pad_len)
6037     data += ps
6038     wrapped = aes.encrypt(data)
6039     return build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6040
6041 def decrypt_attr_encr_settings(authkey, keywrapkey, data):
6042     if len(data) < 32 or len(data) % 16 != 0:
6043         raise Exception("Unexpected Encrypted Settings length: %d" % len(data))
6044     iv = data[0:16]
6045     encr = data[16:]
6046     aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6047     decrypted = aes.decrypt(encr)
6048     pad_len, = struct.unpack('B', decrypted[-1])
6049     if pad_len > len(decrypted):
6050         raise Exception("Invalid padding in Encrypted Settings")
6051     for i in range(-pad_len, -1):
6052         if decrypted[i] != decrypted[-1]:
6053             raise Exception("Invalid PS value in Encrypted Settings")
6054     
6055     decrypted = decrypted[0:len(decrypted) - pad_len]
6056     if len(decrypted) < 12:
6057         raise Exception("Truncated Encrypted Settings plaintext")
6058     kwa = decrypted[-12:]
6059     attr,length = struct.unpack(">HH", kwa[0:4])
6060     if attr != ATTR_KEY_WRAP_AUTH or length != 8:
6061         raise Exception("Invalid KWA header")
6062     kwa = kwa[4:]
6063     decrypted = decrypted[0:len(decrypted) - 12]
6064
6065     m = hmac.new(authkey, decrypted, hashlib.sha256)
6066     calc_kwa = m.digest()[0:8]
6067     if kwa != calc_kwa:
6068         raise Exception("KWA mismatch")
6069
6070     return decrypted
6071
6072 def zeropad_str(val, pad_len):
6073     while len(val) < pad_len * 2:
6074         val = '0' + val
6075     return val
6076
6077 def wsc_dh_init():
6078     # For now, use a hardcoded private key. In theory, this is supposed to be
6079     # randomly selected.
6080     own_private = 0x123456789
6081     own_public = pow(group_5_generator, own_private, group_5_prime)
6082     pk = binascii.unhexlify(zeropad_str(format(own_public, '02x'), 192))
6083     return own_private, pk
6084
6085 def wsc_dh_kdf(peer_pk, own_private, mac_addr, e_nonce, r_nonce):
6086     peer_public = long(binascii.hexlify(peer_pk), 16)
6087     if peer_public < 2 or peer_public >= group_5_prime:
6088         raise Exception("Invalid peer public key")
6089     if pow(peer_public, (group_5_prime - 1) / 2, group_5_prime) != 1:
6090         raise Exception("Unexpected Legendre symbol for peer public key")
6091
6092     shared_secret = pow(peer_public, own_private, group_5_prime)
6093     ss = zeropad_str(format(shared_secret, "02x"), 192)
6094     logger.debug("DH shared secret: " + ss)
6095
6096     dhkey = hashlib.sha256(binascii.unhexlify(ss)).digest()
6097     logger.debug("DHKey: " + binascii.hexlify(dhkey))
6098
6099     m = hmac.new(dhkey, e_nonce + mac_addr + r_nonce, hashlib.sha256)
6100     kdk = m.digest()
6101     logger.debug("KDK: " + binascii.hexlify(kdk))
6102     authkey,keywrapkey,emsk = wsc_keys(kdk)
6103     logger.debug("AuthKey: " + binascii.hexlify(authkey))
6104     logger.debug("KeyWrapKey: " + binascii.hexlify(keywrapkey))
6105     logger.debug("EMSK: " + binascii.hexlify(emsk))
6106     return authkey,keywrapkey
6107
6108 def wsc_dev_pw_hash(authkey, dev_pw, e_pk, r_pk):
6109     psk1,psk2 = wsc_dev_pw_psk(authkey, dev_pw)
6110     logger.debug("PSK1: " + binascii.hexlify(psk1))
6111     logger.debug("PSK2: " + binascii.hexlify(psk2))
6112
6113     # Note: Secret values are supposed to be random, but hardcoded values are
6114     # fine for testing.
6115     s1 = 16*'\x77'
6116     m = hmac.new(authkey, s1 + psk1 + e_pk + r_pk, hashlib.sha256)
6117     hash1 = m.digest()
6118     logger.debug("Hash1: " + binascii.hexlify(hash1))
6119
6120     s2 = 16*'\x88'
6121     m = hmac.new(authkey, s2 + psk2 + e_pk + r_pk, hashlib.sha256)
6122     hash2 = m.digest()
6123     logger.debug("Hash2: " + binascii.hexlify(hash2))
6124     return s1,s2,hash1,hash2
6125
6126 def build_m1(eap_id, uuid_e, mac_addr, e_nonce, e_pk,
6127              manufacturer='', model_name='', config_methods='\x00\x00'):
6128     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6129     attrs += build_attr_msg_type(WPS_M1)
6130     attrs += build_wsc_attr(ATTR_UUID_E, uuid_e)
6131     attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6132     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6133     attrs += build_wsc_attr(ATTR_PUBLIC_KEY, e_pk)
6134     attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6135     attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6136     attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6137     attrs += build_wsc_attr(ATTR_CONFIG_METHODS, config_methods)
6138     attrs += build_wsc_attr(ATTR_WPS_STATE, '\x00')
6139     attrs += build_wsc_attr(ATTR_MANUFACTURER, manufacturer)
6140     attrs += build_wsc_attr(ATTR_MODEL_NAME, model_name)
6141     attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6142     attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6143     attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6144     attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6145     attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6146     attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6147     attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, '\x00\x00')
6148     attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6149     attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6150     m1 = build_eap_wsc(2, eap_id, attrs)
6151     return m1, attrs
6152
6153 def build_m2(authkey, m1, eap_id, e_nonce, r_nonce, uuid_r, r_pk,
6154              dev_pw_id='\x00\x00', eap_code=1):
6155     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6156     attrs += build_attr_msg_type(WPS_M2)
6157     if e_nonce:
6158         attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6159     if r_nonce:
6160         attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6161     attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6162     if r_pk:
6163         attrs += build_wsc_attr(ATTR_PUBLIC_KEY, r_pk)
6164     attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6165     attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6166     attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6167     attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6168     attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6169     attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6170     attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6171     attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6172     attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6173     attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6174     attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6175     attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6176     attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6177     attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6178     attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6179     attrs += build_attr_authenticator(authkey, m1, attrs)
6180     m2 = build_eap_wsc(eap_code, eap_id, attrs)
6181     return m2, attrs
6182
6183 def build_m2d(m1, eap_id, e_nonce, r_nonce, uuid_r, dev_pw_id=None, eap_code=1):
6184     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6185     attrs += build_attr_msg_type(WPS_M2D)
6186     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6187     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6188     attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6189     attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6190     attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6191     attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6192     attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6193     attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6194     attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6195     #attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6196     attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6197     attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6198     attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6199     attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6200     attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6201     attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6202     attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6203     if dev_pw_id:
6204         attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6205     m2d = build_eap_wsc(eap_code, eap_id, attrs)
6206     return m2d, attrs
6207
6208 def build_ack(eap_id, e_nonce, r_nonce, msg_type=WPS_WSC_ACK, eap_code=1):
6209     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6210     if msg_type is not None:
6211         attrs += build_attr_msg_type(msg_type)
6212     if e_nonce:
6213         attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6214     if r_nonce:
6215         attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6216     msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_ACK)
6217     return msg, attrs
6218
6219 def build_nack(eap_id, e_nonce, r_nonce, config_error='\x00\x00',
6220                msg_type=WPS_WSC_NACK, eap_code=1):
6221     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6222     if msg_type is not None:
6223         attrs += build_attr_msg_type(msg_type)
6224     if e_nonce:
6225         attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6226     if r_nonce:
6227         attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6228     if config_error:
6229         attrs += build_wsc_attr(ATTR_CONFIG_ERROR, config_error)
6230     msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_NACK)
6231     return msg, attrs
6232
6233 def test_wps_ext(dev, apdev):
6234     """WPS against external implementation"""
6235     pin = "12345670"
6236     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6237     wps_ext_eap_identity_req(dev[0], hapd, bssid)
6238     wps_ext_eap_identity_resp(hapd, dev[0], addr)
6239
6240     logger.debug("Receive WSC/Start from AP")
6241     msg = get_wsc_msg(hapd)
6242     if msg['wsc_opcode'] != WSC_Start:
6243         raise Exception("Unexpected Op-Code for WSC/Start")
6244     wsc_start_id = msg['eap_identifier']
6245
6246     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6247     uuid_e = 16*'\x11'
6248     e_nonce = 16*'\x22'
6249     own_private, e_pk = wsc_dh_init()
6250
6251     logger.debug("Send M1 to AP")
6252     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
6253                                 e_nonce, e_pk)
6254     send_wsc_msg(hapd, addr, m1)
6255
6256     logger.debug("Receive M2 from AP")
6257     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
6258
6259     authkey,keywrapkey = wsc_dh_kdf(m2_attrs[ATTR_PUBLIC_KEY], own_private,
6260                                     mac_addr, e_nonce,
6261                                     m2_attrs[ATTR_REGISTRAR_NONCE])
6262     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk,
6263                                                 m2_attrs[ATTR_PUBLIC_KEY])
6264
6265     logger.debug("Send M3 to AP")
6266     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6267     attrs += build_attr_msg_type(WPS_M3)
6268     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6269                             m2_attrs[ATTR_REGISTRAR_NONCE])
6270     attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
6271     attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
6272     attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
6273     raw_m3_attrs = attrs
6274     m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6275     send_wsc_msg(hapd, addr, m3)
6276
6277     logger.debug("Receive M4 from AP")
6278     msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
6279
6280     logger.debug("Send M5 to AP")
6281     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6282     attrs += build_attr_msg_type(WPS_M5)
6283     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6284                             m2_attrs[ATTR_REGISTRAR_NONCE])
6285     data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
6286     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6287     attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
6288     raw_m5_attrs = attrs
6289     m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6290     send_wsc_msg(hapd, addr, m5)
6291
6292     logger.debug("Receive M6 from AP")
6293     msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
6294
6295     logger.debug("Send M7 to AP")
6296     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6297     attrs += build_attr_msg_type(WPS_M7)
6298     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6299                             m2_attrs[ATTR_REGISTRAR_NONCE])
6300     data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
6301     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6302     attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
6303     m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6304     raw_m7_attrs = attrs
6305     send_wsc_msg(hapd, addr, m7)
6306
6307     logger.debug("Receive M8 from AP")
6308     msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
6309     m8_cred = decrypt_attr_encr_settings(authkey, keywrapkey,
6310                                          m8_attrs[ATTR_ENCR_SETTINGS])
6311     logger.debug("M8 Credential: " + binascii.hexlify(m8_cred))
6312
6313     logger.debug("Prepare WSC_Done")
6314     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6315     attrs += build_attr_msg_type(WPS_WSC_DONE)
6316     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6317     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6318                             m2_attrs[ATTR_REGISTRAR_NONCE])
6319     wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
6320     # Do not send WSC_Done yet to allow exchangw with STA complete before the
6321     # AP disconnects.
6322
6323     uuid_r = 16*'\x33'
6324     r_nonce = 16*'\x44'
6325
6326     eap_id = wsc_start_id
6327     logger.debug("Send WSC/Start to STA")
6328     wsc_start = build_eap_wsc(1, eap_id, "", opcode=WSC_Start)
6329     send_wsc_msg(dev[0], bssid, wsc_start)
6330     eap_id = (eap_id + 1) % 256
6331
6332     logger.debug("Receive M1 from STA")
6333     msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6334
6335     authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6336                                     mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6337                                     r_nonce)
6338     r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6339                                                 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6340
6341     logger.debug("Send M2 to STA")
6342     m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6343                                 m1_attrs[ATTR_ENROLLEE_NONCE],
6344                                 r_nonce, uuid_r, e_pk)
6345     send_wsc_msg(dev[0], bssid, m2)
6346     eap_id = (eap_id + 1) % 256
6347
6348     logger.debug("Receive M3 from STA")
6349     msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6350
6351     logger.debug("Send M4 to STA")
6352     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6353     attrs += build_attr_msg_type(WPS_M4)
6354     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6355     attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6356     attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6357     data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6358     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6359     attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6360     raw_m4_attrs = attrs
6361     m4 = build_eap_wsc(1, eap_id, attrs)
6362     send_wsc_msg(dev[0], bssid, m4)
6363     eap_id = (eap_id + 1) % 256
6364
6365     logger.debug("Receive M5 from STA")
6366     msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6367
6368     logger.debug("Send M6 to STA")
6369     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6370     attrs += build_attr_msg_type(WPS_M6)
6371     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6372                             m1_attrs[ATTR_ENROLLEE_NONCE])
6373     data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6374     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6375     attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6376     raw_m6_attrs = attrs
6377     m6 = build_eap_wsc(1, eap_id, attrs)
6378     send_wsc_msg(dev[0], bssid, m6)
6379     eap_id = (eap_id + 1) % 256
6380
6381     logger.debug("Receive M7 from STA")
6382     msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6383
6384     logger.debug("Send M8 to STA")
6385     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6386     attrs += build_attr_msg_type(WPS_M8)
6387     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6388                             m1_attrs[ATTR_ENROLLEE_NONCE])
6389     attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6390     attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6391     raw_m8_attrs = attrs
6392     m8 = build_eap_wsc(1, eap_id, attrs)
6393     send_wsc_msg(dev[0], bssid, m8)
6394     eap_id = (eap_id + 1) % 256
6395
6396     ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=5)
6397     if ev is None:
6398         raise Exception("wpa_supplicant did not report credential")
6399
6400     logger.debug("Receive WSC_Done from STA")
6401     msg = get_wsc_msg(dev[0])
6402     if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6403         raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6404
6405     logger.debug("Send WSC_Done to AP")
6406     hapd.request("SET ext_eapol_frame_io 0")
6407     dev[0].request("SET ext_eapol_frame_io 0")
6408     send_wsc_msg(hapd, addr, wsc_done)
6409
6410     ev = hapd.wait_event(["WPS-REG-SUCCESS"], timeout=5)
6411     if ev is None:
6412         raise Exception("hostapd did not report WPS success")
6413
6414     dev[0].wait_connected()
6415
6416 def wps_start_kwa(dev, apdev):
6417     pin = "12345670"
6418     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6419     wps_ext_eap_identity_req(dev[0], hapd, bssid)
6420     wps_ext_eap_identity_resp(hapd, dev[0], addr)
6421     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6422
6423     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6424     uuid_r = 16*'\x33'
6425     r_nonce = 16*'\x44'
6426     own_private, e_pk = wsc_dh_init()
6427
6428     logger.debug("Receive M1 from STA")
6429     msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6430     eap_id = (msg['eap_identifier'] + 1) % 256
6431
6432     authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6433                                     mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6434                                     r_nonce)
6435     r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6436                                                 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6437
6438     logger.debug("Send M2 to STA")
6439     m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6440                                 m1_attrs[ATTR_ENROLLEE_NONCE],
6441                                 r_nonce, uuid_r, e_pk)
6442     send_wsc_msg(dev[0], bssid, m2)
6443     eap_id = (eap_id + 1) % 256
6444
6445     logger.debug("Receive M3 from STA")
6446     msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6447
6448     logger.debug("Send M4 to STA")
6449     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6450     attrs += build_attr_msg_type(WPS_M4)
6451     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6452     attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6453     attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6454
6455     return r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs
6456
6457 def wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id):
6458     attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6459     m4 = build_eap_wsc(1, eap_id, attrs)
6460     send_wsc_msg(dev[0], bssid, m4)
6461     eap_id = (eap_id + 1) % 256
6462
6463     logger.debug("Receive M5 from STA")
6464     msg = get_wsc_msg(dev[0])
6465     if msg['wsc_opcode'] != WSC_NACK:
6466         raise Exception("Unexpected message - expected WSC_Nack")
6467
6468     dev[0].request("WPS_CANCEL")
6469     send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6470     dev[0].wait_disconnected()
6471
6472 def test_wps_ext_kwa_proto_no_kwa(dev, apdev):
6473     """WPS and KWA error: No KWA attribute"""
6474     r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6475     data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6476     # Encrypted Settings without KWA
6477     iv = 16*'\x99'
6478     aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6479     pad_len = 16 - len(data) % 16
6480     ps = pad_len * struct.pack('B', pad_len)
6481     data += ps
6482     wrapped = aes.encrypt(data)
6483     attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6484     wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6485
6486 def test_wps_ext_kwa_proto_data_after_kwa(dev, apdev):
6487     """WPS and KWA error: Data after KWA"""
6488     r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6489     data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6490     # Encrypted Settings and data after KWA
6491     m = hmac.new(authkey, data, hashlib.sha256)
6492     kwa = m.digest()[0:8]
6493     data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6494     data += build_wsc_attr(ATTR_VENDOR_EXT, "1234567890")
6495     iv = 16*'\x99'
6496     aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6497     pad_len = 16 - len(data) % 16
6498     ps = pad_len * struct.pack('B', pad_len)
6499     data += ps
6500     wrapped = aes.encrypt(data)
6501     attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6502     wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6503
6504 def test_wps_ext_kwa_proto_kwa_mismatch(dev, apdev):
6505     """WPS and KWA error: KWA mismatch"""
6506     r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6507     data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6508     # Encrypted Settings and KWA with incorrect value
6509     data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, 8*'\x00')
6510     iv = 16*'\x99'
6511     aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6512     pad_len = 16 - len(data) % 16
6513     ps = pad_len * struct.pack('B', pad_len)
6514     data += ps
6515     wrapped = aes.encrypt(data)
6516     attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6517     wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6518
6519 def wps_run_cred_proto(dev, apdev, m8_cred, connect=False, no_connect=False):
6520     pin = "12345670"
6521     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6522     wps_ext_eap_identity_req(dev[0], hapd, bssid)
6523     wps_ext_eap_identity_resp(hapd, dev[0], addr)
6524     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6525
6526     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6527     uuid_r = 16*'\x33'
6528     r_nonce = 16*'\x44'
6529     own_private, e_pk = wsc_dh_init()
6530
6531     logger.debug("Receive M1 from STA")
6532     msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6533     eap_id = (msg['eap_identifier'] + 1) % 256
6534
6535     authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6536                                     mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6537                                     r_nonce)
6538     r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6539                                                 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6540
6541     logger.debug("Send M2 to STA")
6542     m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6543                                 m1_attrs[ATTR_ENROLLEE_NONCE],
6544                                 r_nonce, uuid_r, e_pk)
6545     send_wsc_msg(dev[0], bssid, m2)
6546     eap_id = (eap_id + 1) % 256
6547
6548     logger.debug("Receive M3 from STA")
6549     msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6550
6551     logger.debug("Send M4 to STA")
6552     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6553     attrs += build_attr_msg_type(WPS_M4)
6554     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6555     attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6556     attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6557     data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6558     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6559     attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6560     raw_m4_attrs = attrs
6561     m4 = build_eap_wsc(1, eap_id, attrs)
6562     send_wsc_msg(dev[0], bssid, m4)
6563     eap_id = (eap_id + 1) % 256
6564
6565     logger.debug("Receive M5 from STA")
6566     msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6567
6568     logger.debug("Send M6 to STA")
6569     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6570     attrs += build_attr_msg_type(WPS_M6)
6571     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6572                             m1_attrs[ATTR_ENROLLEE_NONCE])
6573     data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6574     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6575     attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6576     raw_m6_attrs = attrs
6577     m6 = build_eap_wsc(1, eap_id, attrs)
6578     send_wsc_msg(dev[0], bssid, m6)
6579     eap_id = (eap_id + 1) % 256
6580
6581     logger.debug("Receive M7 from STA")
6582     msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6583
6584     logger.debug("Send M8 to STA")
6585     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6586     attrs += build_attr_msg_type(WPS_M8)
6587     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6588                             m1_attrs[ATTR_ENROLLEE_NONCE])
6589     attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6590     attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6591     raw_m8_attrs = attrs
6592     m8 = build_eap_wsc(1, eap_id, attrs)
6593     send_wsc_msg(dev[0], bssid, m8)
6594     eap_id = (eap_id + 1) % 256
6595
6596     if no_connect:
6597         logger.debug("Receive WSC_Done from STA")
6598         msg = get_wsc_msg(dev[0])
6599         if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6600             raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6601
6602         hapd.request("SET ext_eapol_frame_io 0")
6603         dev[0].request("SET ext_eapol_frame_io 0")
6604
6605         send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6606
6607         dev[0].wait_disconnected()
6608         dev[0].request("REMOVE_NETWORK all")
6609     elif connect:
6610         logger.debug("Receive WSC_Done from STA")
6611         msg = get_wsc_msg(dev[0])
6612         if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6613             raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6614
6615         hapd.request("SET ext_eapol_frame_io 0")
6616         dev[0].request("SET ext_eapol_frame_io 0")
6617
6618         send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6619
6620         dev[0].wait_connected()
6621     else:
6622         # Verify STA NACK's the credential
6623         msg = get_wsc_msg(dev[0])
6624         if msg['wsc_opcode'] != WSC_NACK:
6625             raise Exception("Unexpected message - expected WSC_Nack")
6626         dev[0].request("WPS_CANCEL")
6627         send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6628         dev[0].wait_disconnected()
6629
6630 def build_cred(nw_idx='\x01', ssid='test-wps-conf', auth_type='\x00\x20',
6631                encr_type='\x00\x08', nw_key="12345678",
6632                mac_addr='\x00\x00\x00\x00\x00\x00'):
6633     attrs = ''
6634     if nw_idx is not None:
6635         attrs += build_wsc_attr(ATTR_NETWORK_INDEX, nw_idx)
6636     if ssid is not None:
6637         attrs += build_wsc_attr(ATTR_SSID, ssid)
6638     if auth_type is not None:
6639         attrs += build_wsc_attr(ATTR_AUTH_TYPE, auth_type)
6640     if encr_type is not None:
6641         attrs += build_wsc_attr(ATTR_ENCR_TYPE, encr_type)
6642     if nw_key is not None:
6643         attrs += build_wsc_attr(ATTR_NETWORK_KEY, nw_key)
6644     if mac_addr is not None:
6645         attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6646     return build_wsc_attr(ATTR_CRED, attrs)
6647
6648 def test_wps_ext_cred_proto_success(dev, apdev):
6649     """WPS and Credential: success"""
6650     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6651     m8_cred = build_cred(mac_addr=mac_addr)
6652     wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6653
6654 def test_wps_ext_cred_proto_mac_addr_mismatch(dev, apdev):
6655     """WPS and Credential: MAC Address mismatch"""
6656     m8_cred = build_cred()
6657     wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6658
6659 def test_wps_ext_cred_proto_zero_padding(dev, apdev):
6660     """WPS and Credential: zeropadded attributes"""
6661     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6662     m8_cred = build_cred(mac_addr=mac_addr, ssid='test-wps-conf\x00',
6663                          nw_key="12345678\x00")
6664     wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6665
6666 def test_wps_ext_cred_proto_ssid_missing(dev, apdev):
6667     """WPS and Credential: SSID missing"""
6668     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6669     m8_cred = build_cred(mac_addr=mac_addr, ssid=None)
6670     wps_run_cred_proto(dev, apdev, m8_cred)
6671
6672 def test_wps_ext_cred_proto_ssid_zero_len(dev, apdev):
6673     """WPS and Credential: Zero-length SSID"""
6674     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6675     m8_cred = build_cred(mac_addr=mac_addr, ssid="")
6676     wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6677
6678 def test_wps_ext_cred_proto_auth_type_missing(dev, apdev):
6679     """WPS and Credential: Auth Type missing"""
6680     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6681     m8_cred = build_cred(mac_addr=mac_addr, auth_type=None)
6682     wps_run_cred_proto(dev, apdev, m8_cred)
6683
6684 def test_wps_ext_cred_proto_encr_type_missing(dev, apdev):
6685     """WPS and Credential: Encr Type missing"""
6686     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6687     m8_cred = build_cred(mac_addr=mac_addr, encr_type=None)
6688     wps_run_cred_proto(dev, apdev, m8_cred)
6689
6690 def test_wps_ext_cred_proto_network_key_missing(dev, apdev):
6691     """WPS and Credential: Network Key missing"""
6692     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6693     m8_cred = build_cred(mac_addr=mac_addr, nw_key=None)
6694     wps_run_cred_proto(dev, apdev, m8_cred)
6695
6696 def test_wps_ext_cred_proto_network_key_missing_open(dev, apdev):
6697     """WPS and Credential: Network Key missing (open)"""
6698     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6699     m8_cred = build_cred(mac_addr=mac_addr, auth_type='\x00\x01',
6700                          encr_type='\x00\x01', nw_key=None, ssid="foo")
6701     wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6702
6703 def test_wps_ext_cred_proto_mac_addr_missing(dev, apdev):
6704     """WPS and Credential: MAC Address missing"""
6705     m8_cred = build_cred(mac_addr=None)
6706     wps_run_cred_proto(dev, apdev, m8_cred)
6707
6708 def test_wps_ext_cred_proto_invalid_encr_type(dev, apdev):
6709     """WPS and Credential: Invalid Encr Type"""
6710     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6711     m8_cred = build_cred(mac_addr=mac_addr, encr_type='\x00\x00')
6712     wps_run_cred_proto(dev, apdev, m8_cred)
6713
6714 def test_wps_ext_cred_proto_missing_cred(dev, apdev):
6715     """WPS and Credential: Missing Credential"""
6716     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6717     m8_cred = ''
6718     wps_run_cred_proto(dev, apdev, m8_cred)
6719
6720 def test_wps_ext_proto_m2_no_public_key(dev, apdev):
6721     """WPS and no Public Key in M2"""
6722     pin = "12345670"
6723     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6724     wps_ext_eap_identity_req(dev[0], hapd, bssid)
6725     wps_ext_eap_identity_resp(hapd, dev[0], addr)
6726     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6727
6728     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6729     uuid_r = 16*'\x33'
6730     r_nonce = 16*'\x44'
6731     own_private, e_pk = wsc_dh_init()
6732
6733     logger.debug("Receive M1 from STA")
6734     msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6735     eap_id = (msg['eap_identifier'] + 1) % 256
6736
6737     authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6738                                     mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6739                                     r_nonce)
6740     r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6741                                                 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6742
6743     logger.debug("Send M2 to STA")
6744     m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6745                                 m1_attrs[ATTR_ENROLLEE_NONCE],
6746                                 r_nonce, uuid_r, None)
6747     send_wsc_msg(dev[0], bssid, m2)
6748     eap_id = (eap_id + 1) % 256
6749
6750     # Verify STA NACK's the credential
6751     msg = get_wsc_msg(dev[0])
6752     if msg['wsc_opcode'] != WSC_NACK:
6753         raise Exception("Unexpected message - expected WSC_Nack")
6754     dev[0].request("WPS_CANCEL")
6755     send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6756     dev[0].wait_disconnected()
6757
6758 def test_wps_ext_proto_m2_invalid_public_key(dev, apdev):
6759     """WPS and invalid Public Key in M2"""
6760     pin = "12345670"
6761     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6762     wps_ext_eap_identity_req(dev[0], hapd, bssid)
6763     wps_ext_eap_identity_resp(hapd, dev[0], addr)
6764     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6765
6766     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6767     uuid_r = 16*'\x33'
6768     r_nonce = 16*'\x44'
6769     own_private, e_pk = wsc_dh_init()
6770
6771     logger.debug("Receive M1 from STA")
6772     msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6773     eap_id = (msg['eap_identifier'] + 1) % 256
6774
6775     authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6776                                     mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6777                                     r_nonce)
6778     r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6779                                                 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6780
6781     logger.debug("Send M2 to STA")
6782     m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6783                                 m1_attrs[ATTR_ENROLLEE_NONCE],
6784                                 r_nonce, uuid_r, 192*'\xff')
6785     send_wsc_msg(dev[0], bssid, m2)
6786     eap_id = (eap_id + 1) % 256
6787
6788     # Verify STA NACK's the credential
6789     msg = get_wsc_msg(dev[0])
6790     if msg['wsc_opcode'] != WSC_NACK:
6791         raise Exception("Unexpected message - expected WSC_Nack")
6792     dev[0].request("WPS_CANCEL")
6793     send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6794     dev[0].wait_disconnected()
6795
6796 def test_wps_ext_proto_m2_public_key_oom(dev, apdev):
6797     """WPS and Public Key OOM in M2"""
6798     pin = "12345670"
6799     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6800     wps_ext_eap_identity_req(dev[0], hapd, bssid)
6801     wps_ext_eap_identity_resp(hapd, dev[0], addr)
6802     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6803
6804     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6805     uuid_r = 16*'\x33'
6806     r_nonce = 16*'\x44'
6807     own_private, e_pk = wsc_dh_init()
6808
6809     logger.debug("Receive M1 from STA")
6810     msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6811     eap_id = (msg['eap_identifier'] + 1) % 256
6812
6813     authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6814                                     mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6815                                     r_nonce)
6816     r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6817                                                 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6818
6819     logger.debug("Send M2 to STA")
6820     m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6821                                 m1_attrs[ATTR_ENROLLEE_NONCE],
6822                                 r_nonce, uuid_r, e_pk)
6823     with alloc_fail(dev[0], 1, "wpabuf_alloc_copy;wps_process_pubkey"):
6824         send_wsc_msg(dev[0], bssid, m2)
6825         eap_id = (eap_id + 1) % 256
6826
6827         # Verify STA NACK's the credential
6828         msg = get_wsc_msg(dev[0])
6829         if msg['wsc_opcode'] != WSC_NACK:
6830             raise Exception("Unexpected message - expected WSC_Nack")
6831         dev[0].request("WPS_CANCEL")
6832         send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6833         dev[0].wait_disconnected()
6834
6835 def test_wps_ext_proto_nack_m3(dev, apdev):
6836     """WPS and NACK M3"""
6837     pin = "12345670"
6838     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6839     wps_ext_eap_identity_req(dev[0], hapd, bssid)
6840     wps_ext_eap_identity_resp(hapd, dev[0], addr)
6841     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6842
6843     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6844     uuid_r = 16*'\x33'
6845     r_nonce = 16*'\x44'
6846     own_private, e_pk = wsc_dh_init()
6847
6848     logger.debug("Receive M1 from STA")
6849     msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6850     eap_id = (msg['eap_identifier'] + 1) % 256
6851
6852     authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6853                                     mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6854                                     r_nonce)
6855     r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6856                                                 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6857
6858     logger.debug("Send M2 to STA")
6859     m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6860                                 m1_attrs[ATTR_ENROLLEE_NONCE],
6861                                 r_nonce, uuid_r, e_pk)
6862     send_wsc_msg(dev[0], bssid, m2)
6863     eap_id = (eap_id + 1) % 256
6864
6865     logger.debug("Receive M3 from STA")
6866     msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6867
6868     logger.debug("Send NACK to STA")
6869     msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
6870                             r_nonce, config_error='\x01\x23')
6871     send_wsc_msg(dev[0], bssid, msg)
6872     ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
6873     if ev is None:
6874         raise Exception("Failure not reported")
6875     if "msg=7 config_error=291" not in ev:
6876         raise Exception("Unexpected failure reason: " + ev)
6877
6878 def test_wps_ext_proto_nack_m5(dev, apdev):
6879     """WPS and NACK M5"""
6880     pin = "12345670"
6881     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6882     wps_ext_eap_identity_req(dev[0], hapd, bssid)
6883     wps_ext_eap_identity_resp(hapd, dev[0], addr)
6884     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6885
6886     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6887     uuid_r = 16*'\x33'
6888     r_nonce = 16*'\x44'
6889     own_private, e_pk = wsc_dh_init()
6890
6891     logger.debug("Receive M1 from STA")
6892     msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6893     eap_id = (msg['eap_identifier'] + 1) % 256
6894
6895     authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6896                                     mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6897                                     r_nonce)
6898     r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6899                                                 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6900
6901     logger.debug("Send M2 to STA")
6902     m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6903                                 m1_attrs[ATTR_ENROLLEE_NONCE],
6904                                 r_nonce, uuid_r, e_pk)
6905     send_wsc_msg(dev[0], bssid, m2)
6906     eap_id = (eap_id + 1) % 256
6907
6908     logger.debug("Receive M3 from STA")
6909     msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6910
6911     logger.debug("Send M4 to STA")
6912     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6913     attrs += build_attr_msg_type(WPS_M4)
6914     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6915     attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6916     attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6917     data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6918     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6919     attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6920     raw_m4_attrs = attrs
6921     m4 = build_eap_wsc(1, eap_id, attrs)
6922     send_wsc_msg(dev[0], bssid, m4)
6923     eap_id = (eap_id + 1) % 256
6924
6925     logger.debug("Receive M5 from STA")
6926     msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6927
6928     logger.debug("Send NACK to STA")
6929     msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
6930                             r_nonce, config_error='\x01\x24')
6931     send_wsc_msg(dev[0], bssid, msg)
6932     ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
6933     if ev is None:
6934         raise Exception("Failure not reported")
6935     if "msg=9 config_error=292" not in ev:
6936         raise Exception("Unexpected failure reason: " + ev)
6937
6938 def wps_nack_m3(dev, apdev):
6939     pin = "00000000"
6940     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
6941     wps_ext_eap_identity_req(dev[0], hapd, bssid)
6942     wps_ext_eap_identity_resp(hapd, dev[0], addr)
6943     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6944
6945     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6946     uuid_r = 16*'\x33'
6947     r_nonce = 16*'\x44'
6948     own_private, e_pk = wsc_dh_init()
6949
6950     logger.debug("Receive M1 from STA")
6951     msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6952     eap_id = (msg['eap_identifier'] + 1) % 256
6953
6954     authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6955                                     mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6956                                     r_nonce)
6957     r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6958                                                 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6959
6960     logger.debug("Send M2 to STA")
6961     m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6962                                 m1_attrs[ATTR_ENROLLEE_NONCE],
6963                                 r_nonce, uuid_r, e_pk, dev_pw_id='\x00\x04')
6964     send_wsc_msg(dev[0], bssid, m2)
6965     eap_id = (eap_id + 1) % 256
6966
6967     logger.debug("Receive M3 from STA")
6968     msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6969     return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid
6970
6971 def test_wps_ext_proto_nack_m3_no_config_error(dev, apdev):
6972     """WPS and NACK M3 missing Config Error"""
6973     eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
6974     logger.debug("Send NACK to STA")
6975     msg, attrs = build_nack(eap_id, e_nonce, r_nonce, config_error=None)
6976     send_wsc_msg(dev[0], bssid, msg)
6977     dev[0].request("WPS_CANCEL")
6978     dev[0].wait_disconnected()
6979     dev[0].flush_scan_cache()
6980
6981 def test_wps_ext_proto_nack_m3_no_e_nonce(dev, apdev):
6982     """WPS and NACK M3 missing E-Nonce"""
6983     eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
6984     logger.debug("Send NACK to STA")
6985     msg, attrs = build_nack(eap_id, None, r_nonce)
6986     send_wsc_msg(dev[0], bssid, msg)
6987     dev[0].request("WPS_CANCEL")
6988     dev[0].wait_disconnected()
6989     dev[0].flush_scan_cache()
6990
6991 def test_wps_ext_proto_nack_m3_e_nonce_mismatch(dev, apdev):
6992     """WPS and NACK M3 E-Nonce mismatch"""
6993     eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
6994     logger.debug("Send NACK to STA")
6995     msg, attrs = build_nack(eap_id, 16*'\x00', r_nonce)
6996     send_wsc_msg(dev[0], bssid, msg)
6997     dev[0].request("WPS_CANCEL")
6998     dev[0].wait_disconnected()
6999     dev[0].flush_scan_cache()
7000
7001 def test_wps_ext_proto_nack_m3_no_r_nonce(dev, apdev):
7002     """WPS and NACK M3 missing R-Nonce"""
7003     eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7004     logger.debug("Send NACK to STA")
7005     msg, attrs = build_nack(eap_id, e_nonce, None)
7006     send_wsc_msg(dev[0], bssid, msg)
7007     dev[0].request("WPS_CANCEL")
7008     dev[0].wait_disconnected()
7009     dev[0].flush_scan_cache()
7010
7011 def test_wps_ext_proto_nack_m3_r_nonce_mismatch(dev, apdev):
7012     """WPS and NACK M3 R-Nonce mismatch"""
7013     eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7014     logger.debug("Send NACK to STA")
7015     msg, attrs = build_nack(eap_id, e_nonce, 16*'\x00')
7016     send_wsc_msg(dev[0], bssid, msg)
7017     dev[0].request("WPS_CANCEL")
7018     dev[0].wait_disconnected()
7019     dev[0].flush_scan_cache()
7020
7021 def test_wps_ext_proto_nack_m3_no_msg_type(dev, apdev):
7022     """WPS and NACK M3 no Message Type"""
7023     eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7024     logger.debug("Send NACK to STA")
7025     msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=None)
7026     send_wsc_msg(dev[0], bssid, msg)
7027     dev[0].request("WPS_CANCEL")
7028     dev[0].wait_disconnected()
7029     dev[0].flush_scan_cache()
7030
7031 def test_wps_ext_proto_nack_m3_invalid_msg_type(dev, apdev):
7032     """WPS and NACK M3 invalid Message Type"""
7033     eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7034     logger.debug("Send NACK to STA")
7035     msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=123)
7036     send_wsc_msg(dev[0], bssid, msg)
7037     dev[0].request("WPS_CANCEL")
7038     dev[0].wait_disconnected()
7039     dev[0].flush_scan_cache()
7040
7041 def test_wps_ext_proto_nack_m3_invalid_attr(dev, apdev):
7042     """WPS and NACK M3 invalid attribute"""
7043     eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7044     logger.debug("Send NACK to STA")
7045     attrs = '\x10\x10\x00'
7046     msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_NACK)
7047     send_wsc_msg(dev[0], bssid, msg)
7048     dev[0].request("WPS_CANCEL")
7049     dev[0].wait_disconnected()
7050     dev[0].flush_scan_cache()
7051
7052 def test_wps_ext_proto_ack_m3_no_e_nonce(dev, apdev):
7053     """WPS and ACK M3 missing E-Nonce"""
7054     eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7055     logger.debug("Send NACK to STA")
7056     msg, attrs = build_ack(eap_id, None, r_nonce)
7057     send_wsc_msg(dev[0], bssid, msg)
7058     dev[0].request("WPS_CANCEL")
7059     dev[0].wait_disconnected()
7060     dev[0].flush_scan_cache()
7061
7062 def test_wps_ext_proto_ack_m3_e_nonce_mismatch(dev, apdev):
7063     """WPS and ACK M3 E-Nonce mismatch"""
7064     eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7065     logger.debug("Send NACK to STA")
7066     msg, attrs = build_ack(eap_id, 16*'\x00', r_nonce)
7067     send_wsc_msg(dev[0], bssid, msg)
7068     dev[0].request("WPS_CANCEL")
7069     dev[0].wait_disconnected()
7070     dev[0].flush_scan_cache()
7071
7072 def test_wps_ext_proto_ack_m3_no_r_nonce(dev, apdev):
7073     """WPS and ACK M3 missing R-Nonce"""
7074     eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7075     logger.debug("Send NACK to STA")
7076     msg, attrs = build_ack(eap_id, e_nonce, None)
7077     send_wsc_msg(dev[0], bssid, msg)
7078     dev[0].request("WPS_CANCEL")
7079     dev[0].wait_disconnected()
7080     dev[0].flush_scan_cache()
7081
7082 def test_wps_ext_proto_ack_m3_r_nonce_mismatch(dev, apdev):
7083     """WPS and ACK M3 R-Nonce mismatch"""
7084     eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7085     logger.debug("Send NACK to STA")
7086     msg, attrs = build_ack(eap_id, e_nonce, 16*'\x00')
7087     send_wsc_msg(dev[0], bssid, msg)
7088     dev[0].request("WPS_CANCEL")
7089     dev[0].wait_disconnected()
7090     dev[0].flush_scan_cache()
7091
7092 def test_wps_ext_proto_ack_m3_no_msg_type(dev, apdev):
7093     """WPS and ACK M3 no Message Type"""
7094     eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7095     logger.debug("Send NACK to STA")
7096     msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=None)
7097     send_wsc_msg(dev[0], bssid, msg)
7098     dev[0].request("WPS_CANCEL")
7099     dev[0].wait_disconnected()
7100     dev[0].flush_scan_cache()
7101
7102 def test_wps_ext_proto_ack_m3_invalid_msg_type(dev, apdev):
7103     """WPS and ACK M3 invalid Message Type"""
7104     eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7105     logger.debug("Send NACK to STA")
7106     msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=123)
7107     send_wsc_msg(dev[0], bssid, msg)
7108     dev[0].request("WPS_CANCEL")
7109     dev[0].wait_disconnected()
7110     dev[0].flush_scan_cache()
7111
7112 def test_wps_ext_proto_ack_m3_invalid_attr(dev, apdev):
7113     """WPS and ACK M3 invalid attribute"""
7114     eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7115     logger.debug("Send ACK to STA")
7116     attrs = '\x10\x10\x00'
7117     msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_ACK)
7118     send_wsc_msg(dev[0], bssid, msg)
7119     dev[0].request("WPS_CANCEL")
7120     dev[0].wait_disconnected()
7121     dev[0].flush_scan_cache()
7122
7123 def test_wps_ext_proto_ack_m3(dev, apdev):
7124     """WPS and ACK M3"""
7125     eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7126     logger.debug("Send ACK to STA")
7127     msg, attrs = build_ack(eap_id, e_nonce, r_nonce)
7128     send_wsc_msg(dev[0], bssid, msg)
7129     dev[0].request("WPS_CANCEL")
7130     dev[0].wait_disconnected()
7131     dev[0].flush_scan_cache()
7132
7133 def wps_to_m3_helper(dev, apdev):
7134     pin = "12345670"
7135     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7136     wps_ext_eap_identity_req(dev[0], hapd, bssid)
7137     wps_ext_eap_identity_resp(hapd, dev[0], addr)
7138     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7139
7140     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7141     uuid_r = 16*'\x33'
7142     r_nonce = 16*'\x44'
7143     own_private, e_pk = wsc_dh_init()
7144
7145     logger.debug("Receive M1 from STA")
7146     msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7147     eap_id = (msg['eap_identifier'] + 1) % 256
7148
7149     authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7150                                     mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7151                                     r_nonce)
7152     r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7153                                                 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
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     return eap_id, m1_attrs, r_nonce, bssid, r_hash1, r_hash2, r_s1, r_s2, raw_m3_attrs, authkey, keywrapkey
7165
7166 def wps_to_m3(dev, apdev):
7167     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)
7168     return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s1, raw_m3_attrs, authkey, keywrapkey
7169
7170 def wps_to_m5(dev, apdev):
7171     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)
7172
7173     logger.debug("Send M4 to STA")
7174     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7175     attrs += build_attr_msg_type(WPS_M4)
7176     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7177     attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7178     attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7179     data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7180     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7181     attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7182     raw_m4_attrs = attrs
7183     m4 = build_eap_wsc(1, eap_id, attrs)
7184     send_wsc_msg(dev[0], bssid, m4)
7185     eap_id = (eap_id + 1) % 256
7186
7187     logger.debug("Receive M5 from STA")
7188     msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7189
7190     return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s2, raw_m5_attrs, authkey, keywrapkey
7191
7192 def test_wps_ext_proto_m4_missing_r_hash1(dev, apdev):
7193     """WPS and no R-Hash1 in M4"""
7194     eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7195
7196     logger.debug("Send M4 to STA")
7197     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7198     attrs += build_attr_msg_type(WPS_M4)
7199     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7200     #attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7201     attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7202     data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7203     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7204     attrs += build_attr_authenticator(authkey, m3, attrs)
7205     m4 = build_eap_wsc(1, eap_id, attrs)
7206     send_wsc_msg(dev[0], bssid, m4)
7207     eap_id = (eap_id + 1) % 256
7208
7209     logger.debug("Receive M5 (NACK) from STA")
7210     msg = get_wsc_msg(dev[0])
7211     if msg['wsc_opcode'] != WSC_NACK:
7212         raise Exception("Unexpected message - expected WSC_Nack")
7213
7214     dev[0].request("WPS_CANCEL")
7215     send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7216     dev[0].wait_disconnected()
7217
7218 def test_wps_ext_proto_m4_missing_r_hash2(dev, apdev):
7219     """WPS and no R-Hash2 in M4"""
7220     eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7221
7222     logger.debug("Send M4 to STA")
7223     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7224     attrs += build_attr_msg_type(WPS_M4)
7225     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7226     attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7227     #attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7228     data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7229     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7230     attrs += build_attr_authenticator(authkey, m3, attrs)
7231     m4 = build_eap_wsc(1, eap_id, attrs)
7232     send_wsc_msg(dev[0], bssid, m4)
7233     eap_id = (eap_id + 1) % 256
7234
7235     logger.debug("Receive M5 (NACK) from STA")
7236     msg = get_wsc_msg(dev[0])
7237     if msg['wsc_opcode'] != WSC_NACK:
7238         raise Exception("Unexpected message - expected WSC_Nack")
7239
7240     dev[0].request("WPS_CANCEL")
7241     send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7242     dev[0].wait_disconnected()
7243
7244 def test_wps_ext_proto_m4_missing_r_snonce1(dev, apdev):
7245     """WPS and no R-SNonce1 in M4"""
7246     eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7247
7248     logger.debug("Send M4 to STA")
7249     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7250     attrs += build_attr_msg_type(WPS_M4)
7251     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7252     attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7253     attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7254     #data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7255     data = ''
7256     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7257     attrs += build_attr_authenticator(authkey, m3, attrs)
7258     m4 = build_eap_wsc(1, eap_id, attrs)
7259     send_wsc_msg(dev[0], bssid, m4)
7260     eap_id = (eap_id + 1) % 256
7261
7262     logger.debug("Receive M5 (NACK) from STA")
7263     msg = get_wsc_msg(dev[0])
7264     if msg['wsc_opcode'] != WSC_NACK:
7265         raise Exception("Unexpected message - expected WSC_Nack")
7266
7267     dev[0].request("WPS_CANCEL")
7268     send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7269     dev[0].wait_disconnected()
7270
7271 def test_wps_ext_proto_m4_invalid_pad_string(dev, apdev):
7272     """WPS and invalid pad string in M4"""
7273     eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7274
7275     logger.debug("Send M4 to STA")
7276     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7277     attrs += build_attr_msg_type(WPS_M4)
7278     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7279     attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7280     attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7281     data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7282
7283     m = hmac.new(authkey, data, hashlib.sha256)
7284     kwa = m.digest()[0:8]
7285     data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7286     iv = 16*'\x99'
7287     aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7288     pad_len = 16 - len(data) % 16
7289     ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', pad_len - 1)
7290     data += ps
7291     wrapped = aes.encrypt(data)
7292     attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7293
7294     attrs += build_attr_authenticator(authkey, m3, attrs)
7295     m4 = build_eap_wsc(1, eap_id, attrs)
7296     send_wsc_msg(dev[0], bssid, m4)
7297     eap_id = (eap_id + 1) % 256
7298
7299     logger.debug("Receive M5 (NACK) from STA")
7300     msg = get_wsc_msg(dev[0])
7301     if msg['wsc_opcode'] != WSC_NACK:
7302         raise Exception("Unexpected message - expected WSC_Nack")
7303
7304     dev[0].request("WPS_CANCEL")
7305     send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7306     dev[0].wait_disconnected()
7307
7308 def test_wps_ext_proto_m4_invalid_pad_value(dev, apdev):
7309     """WPS and invalid pad value in M4"""
7310     eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7311
7312     logger.debug("Send M4 to STA")
7313     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7314     attrs += build_attr_msg_type(WPS_M4)
7315     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7316     attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7317     attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7318     data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7319
7320     m = hmac.new(authkey, data, hashlib.sha256)
7321     kwa = m.digest()[0:8]
7322     data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7323     iv = 16*'\x99'
7324     aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7325     pad_len = 16 - len(data) % 16
7326     ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', 255)
7327     data += ps
7328     wrapped = aes.encrypt(data)
7329     attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7330
7331     attrs += build_attr_authenticator(authkey, m3, attrs)
7332     m4 = build_eap_wsc(1, eap_id, attrs)
7333     send_wsc_msg(dev[0], bssid, m4)
7334     eap_id = (eap_id + 1) % 256
7335
7336     logger.debug("Receive M5 (NACK) from STA")
7337     msg = get_wsc_msg(dev[0])
7338     if msg['wsc_opcode'] != WSC_NACK:
7339         raise Exception("Unexpected message - expected WSC_Nack")
7340
7341     dev[0].request("WPS_CANCEL")
7342     send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7343     dev[0].wait_disconnected()
7344
7345 def test_wps_ext_proto_m4_no_encr_settings(dev, apdev):
7346     """WPS and no Encr Settings in M4"""
7347     eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7348
7349     logger.debug("Send M4 to STA")
7350     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7351     attrs += build_attr_msg_type(WPS_M4)
7352     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7353     attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7354     attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7355     attrs += build_attr_authenticator(authkey, m3, attrs)
7356     m4 = build_eap_wsc(1, eap_id, attrs)
7357     send_wsc_msg(dev[0], bssid, m4)
7358     eap_id = (eap_id + 1) % 256
7359
7360     logger.debug("Receive M5 (NACK) from STA")
7361     msg = get_wsc_msg(dev[0])
7362     if msg['wsc_opcode'] != WSC_NACK:
7363         raise Exception("Unexpected message - expected WSC_Nack")
7364
7365     dev[0].request("WPS_CANCEL")
7366     send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7367     dev[0].wait_disconnected()
7368
7369 def test_wps_ext_proto_m6_missing_r_snonce2(dev, apdev):
7370     """WPS and no R-SNonce2 in M6"""
7371     eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7372
7373     logger.debug("Send M6 to STA")
7374     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7375     attrs += build_attr_msg_type(WPS_M6)
7376     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7377     #data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7378     data = ''
7379     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7380     attrs += build_attr_authenticator(authkey, m5, attrs)
7381     m6 = build_eap_wsc(1, eap_id, attrs)
7382     send_wsc_msg(dev[0], bssid, m6)
7383     eap_id = (eap_id + 1) % 256
7384
7385     logger.debug("Receive M7 (NACK) from STA")
7386     msg = get_wsc_msg(dev[0])
7387     if msg['wsc_opcode'] != WSC_NACK:
7388         raise Exception("Unexpected message - expected WSC_Nack")
7389
7390     dev[0].request("WPS_CANCEL")
7391     send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7392     dev[0].wait_disconnected()
7393
7394 def test_wps_ext_proto_m6_no_encr_settings(dev, apdev):
7395     """WPS and no Encr Settings in M6"""
7396     eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7397
7398     logger.debug("Send M6 to STA")
7399     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7400     attrs += build_attr_msg_type(WPS_M6)
7401     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7402     data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7403     #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7404     attrs += build_attr_authenticator(authkey, m5, attrs)
7405     m6 = build_eap_wsc(1, eap_id, attrs)
7406     send_wsc_msg(dev[0], bssid, m6)
7407     eap_id = (eap_id + 1) % 256
7408
7409     logger.debug("Receive M7 (NACK) from STA")
7410     msg = get_wsc_msg(dev[0])
7411     if msg['wsc_opcode'] != WSC_NACK:
7412         raise Exception("Unexpected message - expected WSC_Nack")
7413
7414     dev[0].request("WPS_CANCEL")
7415     send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7416     dev[0].wait_disconnected()
7417
7418 def test_wps_ext_proto_m8_no_encr_settings(dev, apdev):
7419     """WPS and no Encr Settings in M6"""
7420     eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7421
7422     logger.debug("Send M6 to STA")
7423     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7424     attrs += build_attr_msg_type(WPS_M6)
7425     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7426     data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7427     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7428     attrs += build_attr_authenticator(authkey, m5, attrs)
7429     raw_m6_attrs = attrs
7430     m6 = build_eap_wsc(1, eap_id, attrs)
7431     send_wsc_msg(dev[0], bssid, m6)
7432     eap_id = (eap_id + 1) % 256
7433
7434     logger.debug("Receive M7 from STA")
7435     msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
7436
7437     logger.debug("Send M8 to STA")
7438     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7439     attrs += build_attr_msg_type(WPS_M8)
7440     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7441     #attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
7442     attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7443     raw_m8_attrs = attrs
7444     m8 = build_eap_wsc(1, eap_id, attrs)
7445     send_wsc_msg(dev[0], bssid, m8)
7446
7447     logger.debug("Receive WSC_Done (NACK) from STA")
7448     msg = get_wsc_msg(dev[0])
7449     if msg['wsc_opcode'] != WSC_NACK:
7450         raise Exception("Unexpected message - expected WSC_Nack")
7451
7452     dev[0].request("WPS_CANCEL")
7453     send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7454     dev[0].wait_disconnected()
7455
7456 def wps_start_ext_reg(apdev, dev):
7457     addr = dev.own_addr()
7458     bssid = apdev['bssid']
7459     ssid = "test-wps-conf"
7460     appin = "12345670"
7461     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
7462                "wpa_passphrase": "12345678", "wpa": "2",
7463                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
7464                "ap_pin": appin }
7465     hapd = hostapd.add_ap(apdev['ifname'], params)
7466
7467     dev.scan_for_bss(bssid, freq="2412")
7468     hapd.request("SET ext_eapol_frame_io 1")
7469     dev.request("SET ext_eapol_frame_io 1")
7470
7471     dev.request("WPS_REG " + bssid + " " + appin)
7472
7473     return addr,bssid,hapd
7474
7475 def wps_run_ap_settings_proto(dev, apdev, ap_settings, success):
7476     addr,bssid,hapd = wps_start_ext_reg(apdev[0], dev[0])
7477     wps_ext_eap_identity_req(dev[0], hapd, bssid)
7478     wps_ext_eap_identity_resp(hapd, dev[0], addr)
7479
7480     logger.debug("Receive M1 from AP")
7481     msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7482     mac_addr = m1_attrs[ATTR_MAC_ADDR]
7483     e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7484     e_pk = m1_attrs[ATTR_PUBLIC_KEY]
7485
7486     appin = '12345670'
7487     uuid_r = 16*'\x33'
7488     r_nonce = 16*'\x44'
7489     own_private, r_pk = wsc_dh_init()
7490     authkey,keywrapkey = wsc_dh_kdf(e_pk, own_private, mac_addr, e_nonce,
7491                                     r_nonce)
7492     r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, appin, e_pk, r_pk)
7493
7494     logger.debug("Send M2 to AP")
7495     m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, msg['eap_identifier'],
7496                                 e_nonce, r_nonce, uuid_r, r_pk, eap_code=2)
7497     send_wsc_msg(hapd, addr, m2)
7498
7499     logger.debug("Receive M3 from AP")
7500     msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M3)
7501
7502     logger.debug("Send M4 to AP")
7503     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7504     attrs += build_attr_msg_type(WPS_M4)
7505     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7506     attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7507     attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7508     data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7509     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7510     attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7511     raw_m4_attrs = attrs
7512     m4 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7513     send_wsc_msg(hapd, addr, m4)
7514
7515     logger.debug("Receive M5 from AP")
7516     msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M5)
7517
7518     logger.debug("Send M6 to STA")
7519     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7520     attrs += build_attr_msg_type(WPS_M6)
7521     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7522     data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7523     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7524     attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
7525     raw_m6_attrs = attrs
7526     m6 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7527     send_wsc_msg(hapd, addr, m6)
7528
7529     logger.debug("Receive M7 from AP")
7530     msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M7)
7531
7532     logger.debug("Send M8 to STA")
7533     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7534     attrs += build_attr_msg_type(WPS_M8)
7535     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7536     if ap_settings:
7537         attrs += build_attr_encr_settings(authkey, keywrapkey, ap_settings)
7538     attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7539     raw_m8_attrs = attrs
7540     m8 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7541     send_wsc_msg(hapd, addr, m8)
7542
7543     if success:
7544         ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
7545         if ev is None:
7546             raise Exception("New AP settings not reported")
7547         logger.debug("Receive WSC_Done from AP")
7548         msg = get_wsc_msg(hapd)
7549         if msg['wsc_opcode'] != WSC_Done:
7550             raise Exception("Unexpected message - expected WSC_Done")
7551
7552         logger.debug("Send WSC_ACK to AP")
7553         ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
7554                               eap_code=2)
7555         send_wsc_msg(hapd, addr, ack)
7556         dev[0].wait_disconnected()
7557     else:
7558         ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
7559         if ev is None:
7560             raise Exception("WPS failure not reported")
7561         logger.debug("Receive WSC_NACK from AP")
7562         msg = get_wsc_msg(hapd)
7563         if msg['wsc_opcode'] != WSC_NACK:
7564             raise Exception("Unexpected message - expected WSC_NACK")
7565
7566         logger.debug("Send WSC_NACK to AP")
7567         nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7568                                 eap_code=2)
7569         send_wsc_msg(hapd, addr, nack)
7570         dev[0].wait_disconnected()
7571
7572 def test_wps_ext_ap_settings_success(dev, apdev):
7573     """WPS and AP Settings: success"""
7574     ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7575     ap_settings += build_wsc_attr(ATTR_SSID, "test")
7576     ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7577     ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7578     ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7579     ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7580     wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7581
7582 def test_wps_ext_ap_settings_missing(dev, apdev):
7583     """WPS and AP Settings: missing"""
7584     wps_run_ap_settings_proto(dev, apdev, None, False)
7585
7586 def test_wps_ext_ap_settings_mac_addr_mismatch(dev, apdev):
7587     """WPS and AP Settings: MAC Address mismatch"""
7588     ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7589     ap_settings += build_wsc_attr(ATTR_SSID, "test")
7590     ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7591     ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7592     ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7593     ap_settings += build_wsc_attr(ATTR_MAC_ADDR, '\x00\x00\x00\x00\x00\x00')
7594     wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7595
7596 def test_wps_ext_ap_settings_mac_addr_missing(dev, apdev):
7597     """WPS and AP Settings: missing MAC Address"""
7598     ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7599     ap_settings += build_wsc_attr(ATTR_SSID, "test")
7600     ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7601     ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7602     ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7603     wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7604
7605 def test_wps_ext_ap_settings_reject_encr_type(dev, apdev):
7606     """WPS and AP Settings: reject Encr Type"""
7607     ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7608     ap_settings += build_wsc_attr(ATTR_SSID, "test")
7609     ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7610     ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x00')
7611     ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7612     ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7613     wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7614
7615 def test_wps_ext_ap_settings_m2d(dev, apdev):
7616     """WPS and AP Settings: M2D"""
7617     addr,bssid,hapd = wps_start_ext_reg(apdev[0], dev[0])
7618     wps_ext_eap_identity_req(dev[0], hapd, bssid)
7619     wps_ext_eap_identity_resp(hapd, dev[0], addr)
7620
7621     logger.debug("Receive M1 from AP")
7622     msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7623     e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7624
7625     r_nonce = 16*'\x44'
7626     uuid_r = 16*'\x33'
7627
7628     logger.debug("Send M2D to AP")
7629     m2d, raw_m2d_attrs = build_m2d(raw_m1_attrs, msg['eap_identifier'],
7630                                    e_nonce, r_nonce, uuid_r,
7631                                    dev_pw_id='\x00\x00', eap_code=2)
7632     send_wsc_msg(hapd, addr, m2d)
7633
7634     ev = hapd.wait_event(["WPS-M2D"], timeout=5)
7635     if ev is None:
7636         raise Exception("M2D not reported")
7637
7638     wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7639
7640 def wps_wait_ap_nack(hapd, dev, e_nonce, r_nonce):
7641     logger.debug("Receive WSC_NACK from AP")
7642     msg = get_wsc_msg(hapd)
7643     if msg['wsc_opcode'] != WSC_NACK:
7644         raise Exception("Unexpected message - expected WSC_NACK")
7645
7646     logger.debug("Send WSC_NACK to AP")
7647     nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7648                             eap_code=2)
7649     send_wsc_msg(hapd, dev.own_addr(), nack)
7650     dev.wait_disconnected()
7651
7652 def test_wps_ext_m3_missing_e_hash1(dev, apdev):
7653     """WPS proto: M3 missing E-Hash1"""
7654     pin = "12345670"
7655     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7656     wps_ext_eap_identity_req(dev[0], hapd, bssid)
7657     wps_ext_eap_identity_resp(hapd, dev[0], addr)
7658
7659     logger.debug("Receive WSC/Start from AP")
7660     msg = get_wsc_msg(hapd)
7661     if msg['wsc_opcode'] != WSC_Start:
7662         raise Exception("Unexpected Op-Code for WSC/Start")
7663
7664     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7665     uuid_e = 16*'\x11'
7666     e_nonce = 16*'\x22'
7667     own_private, e_pk = wsc_dh_init()
7668
7669     logger.debug("Send M1 to AP")
7670     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7671                                 e_nonce, e_pk)
7672     send_wsc_msg(hapd, addr, m1)
7673
7674     logger.debug("Receive M2 from AP")
7675     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7676     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7677     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7678
7679     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7680                                     r_nonce)
7681     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7682
7683     logger.debug("Send M3 to AP")
7684     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7685     attrs += build_attr_msg_type(WPS_M3)
7686     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7687     #attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7688     attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7689     attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7690     raw_m3_attrs = attrs
7691     m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7692     send_wsc_msg(hapd, addr, m3)
7693
7694     wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7695
7696 def test_wps_ext_m3_missing_e_hash2(dev, apdev):
7697     """WPS proto: M3 missing E-Hash2"""
7698     pin = "12345670"
7699     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7700     wps_ext_eap_identity_req(dev[0], hapd, bssid)
7701     wps_ext_eap_identity_resp(hapd, dev[0], addr)
7702
7703     logger.debug("Receive WSC/Start from AP")
7704     msg = get_wsc_msg(hapd)
7705     if msg['wsc_opcode'] != WSC_Start:
7706         raise Exception("Unexpected Op-Code for WSC/Start")
7707
7708     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7709     uuid_e = 16*'\x11'
7710     e_nonce = 16*'\x22'
7711     own_private, e_pk = wsc_dh_init()
7712
7713     logger.debug("Send M1 to AP")
7714     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7715                                 e_nonce, e_pk)
7716     send_wsc_msg(hapd, addr, m1)
7717
7718     logger.debug("Receive M2 from AP")
7719     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7720     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7721     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7722
7723     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7724                                     r_nonce)
7725     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7726
7727     logger.debug("Send M3 to AP")
7728     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7729     attrs += build_attr_msg_type(WPS_M3)
7730     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7731     attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7732     #attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7733     attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7734     raw_m3_attrs = attrs
7735     m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7736     send_wsc_msg(hapd, addr, m3)
7737
7738     wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7739
7740 def test_wps_ext_m5_missing_e_snonce1(dev, apdev):
7741     """WPS proto: M5 missing E-SNonce1"""
7742     pin = "12345670"
7743     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7744     wps_ext_eap_identity_req(dev[0], hapd, bssid)
7745     wps_ext_eap_identity_resp(hapd, dev[0], addr)
7746
7747     logger.debug("Receive WSC/Start from AP")
7748     msg = get_wsc_msg(hapd)
7749     if msg['wsc_opcode'] != WSC_Start:
7750         raise Exception("Unexpected Op-Code for WSC/Start")
7751
7752     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7753     uuid_e = 16*'\x11'
7754     e_nonce = 16*'\x22'
7755     own_private, e_pk = wsc_dh_init()
7756
7757     logger.debug("Send M1 to AP")
7758     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7759                                 e_nonce, e_pk)
7760     send_wsc_msg(hapd, addr, m1)
7761
7762     logger.debug("Receive M2 from AP")
7763     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7764     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7765     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7766
7767     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7768                                     r_nonce)
7769     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7770
7771     logger.debug("Send M3 to AP")
7772     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7773     attrs += build_attr_msg_type(WPS_M3)
7774     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7775     attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7776     attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7777     attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7778     raw_m3_attrs = attrs
7779     m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7780     send_wsc_msg(hapd, addr, m3)
7781
7782     logger.debug("Receive M4 from AP")
7783     msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
7784
7785     logger.debug("Send M5 to AP")
7786     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7787     attrs += build_attr_msg_type(WPS_M5)
7788     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7789     #data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
7790     data = ''
7791     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7792     attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
7793     raw_m5_attrs = attrs
7794     m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7795     send_wsc_msg(hapd, addr, m5)
7796
7797     wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7798
7799 def test_wps_ext_m5_e_snonce1_mismatch(dev, apdev):
7800     """WPS proto: M5 E-SNonce1 mismatch"""
7801     pin = "12345670"
7802     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7803     wps_ext_eap_identity_req(dev[0], hapd, bssid)
7804     wps_ext_eap_identity_resp(hapd, dev[0], addr)
7805
7806     logger.debug("Receive WSC/Start from AP")
7807     msg = get_wsc_msg(hapd)
7808     if msg['wsc_opcode'] != WSC_Start:
7809         raise Exception("Unexpected Op-Code for WSC/Start")
7810
7811     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7812     uuid_e = 16*'\x11'
7813     e_nonce = 16*'\x22'
7814     own_private, e_pk = wsc_dh_init()
7815
7816     logger.debug("Send M1 to AP")
7817     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7818                                 e_nonce, e_pk)
7819     send_wsc_msg(hapd, addr, m1)
7820
7821     logger.debug("Receive M2 from AP")
7822     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7823     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7824     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7825
7826     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7827                                     r_nonce)
7828     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7829
7830     logger.debug("Send M3 to AP")
7831     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7832     attrs += build_attr_msg_type(WPS_M3)
7833     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7834     attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7835     attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7836     attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7837     raw_m3_attrs = attrs
7838     m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7839     send_wsc_msg(hapd, addr, m3)
7840
7841     logger.debug("Receive M4 from AP")
7842     msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
7843
7844     logger.debug("Send M5 to AP")
7845     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7846     attrs += build_attr_msg_type(WPS_M5)
7847     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7848     data = build_wsc_attr(ATTR_E_SNONCE1, 16*'\x00')
7849     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7850     attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
7851     raw_m5_attrs = attrs
7852     m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7853     send_wsc_msg(hapd, addr, m5)
7854
7855     wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7856
7857 def test_wps_ext_m7_missing_e_snonce2(dev, apdev):
7858     """WPS proto: M7 missing E-SNonce2"""
7859     pin = "12345670"
7860     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7861     wps_ext_eap_identity_req(dev[0], hapd, bssid)
7862     wps_ext_eap_identity_resp(hapd, dev[0], addr)
7863
7864     logger.debug("Receive WSC/Start from AP")
7865     msg = get_wsc_msg(hapd)
7866     if msg['wsc_opcode'] != WSC_Start:
7867         raise Exception("Unexpected Op-Code for WSC/Start")
7868
7869     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7870     uuid_e = 16*'\x11'
7871     e_nonce = 16*'\x22'
7872     own_private, e_pk = wsc_dh_init()
7873
7874     logger.debug("Send M1 to AP")
7875     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7876                                 e_nonce, e_pk)
7877     send_wsc_msg(hapd, addr, m1)
7878
7879     logger.debug("Receive M2 from AP")
7880     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7881     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7882     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7883
7884     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7885                                     r_nonce)
7886     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7887
7888     logger.debug("Send M3 to AP")
7889     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7890     attrs += build_attr_msg_type(WPS_M3)
7891     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7892     attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7893     attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7894     attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7895     raw_m3_attrs = attrs
7896     m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7897     send_wsc_msg(hapd, addr, m3)
7898
7899     logger.debug("Receive M4 from AP")
7900     msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
7901
7902     logger.debug("Send M5 to AP")
7903     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7904     attrs += build_attr_msg_type(WPS_M5)
7905     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7906     data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
7907     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7908     attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
7909     raw_m5_attrs = attrs
7910     m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7911     send_wsc_msg(hapd, addr, m5)
7912
7913     logger.debug("Receive M6 from AP")
7914     msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
7915
7916     logger.debug("Send M7 to AP")
7917     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7918     attrs += build_attr_msg_type(WPS_M7)
7919     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7920     #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
7921     data = ''
7922     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7923     attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
7924     m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7925     raw_m7_attrs = attrs
7926     send_wsc_msg(hapd, addr, m7)
7927
7928     wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7929
7930 def test_wps_ext_m7_e_snonce2_mismatch(dev, apdev):
7931     """WPS proto: M7 E-SNonce2 mismatch"""
7932     pin = "12345670"
7933     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7934     wps_ext_eap_identity_req(dev[0], hapd, bssid)
7935     wps_ext_eap_identity_resp(hapd, dev[0], addr)
7936
7937     logger.debug("Receive WSC/Start from AP")
7938     msg = get_wsc_msg(hapd)
7939     if msg['wsc_opcode'] != WSC_Start:
7940         raise Exception("Unexpected Op-Code for WSC/Start")
7941
7942     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7943     uuid_e = 16*'\x11'
7944     e_nonce = 16*'\x22'
7945     own_private, e_pk = wsc_dh_init()
7946
7947     logger.debug("Send M1 to AP")
7948     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7949                                 e_nonce, e_pk)
7950     send_wsc_msg(hapd, addr, m1)
7951
7952     logger.debug("Receive M2 from AP")
7953     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7954     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7955     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7956
7957     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7958                                     r_nonce)
7959     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7960
7961     logger.debug("Send M3 to AP")
7962     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7963     attrs += build_attr_msg_type(WPS_M3)
7964     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7965     attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7966     attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7967     attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7968     raw_m3_attrs = attrs
7969     m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7970     send_wsc_msg(hapd, addr, m3)
7971
7972     logger.debug("Receive M4 from AP")
7973     msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
7974
7975     logger.debug("Send M5 to AP")
7976     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7977     attrs += build_attr_msg_type(WPS_M5)
7978     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7979     data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
7980     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7981     attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
7982     raw_m5_attrs = attrs
7983     m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7984     send_wsc_msg(hapd, addr, m5)
7985
7986     logger.debug("Receive M6 from AP")
7987     msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
7988
7989     logger.debug("Send M7 to AP")
7990     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7991     attrs += build_attr_msg_type(WPS_M7)
7992     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7993     data = build_wsc_attr(ATTR_E_SNONCE2, 16*'\x00')
7994     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7995     attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
7996     m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7997     raw_m7_attrs = attrs
7998     send_wsc_msg(hapd, addr, m7)
7999
8000     wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8001
8002 def test_wps_ext_m1_pubkey_oom(dev, apdev):
8003     """WPS proto: M1 PubKey OOM"""
8004     pin = "12345670"
8005     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8006     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8007     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8008
8009     logger.debug("Receive WSC/Start from AP")
8010     msg = get_wsc_msg(hapd)
8011     if msg['wsc_opcode'] != WSC_Start:
8012         raise Exception("Unexpected Op-Code for WSC/Start")
8013
8014     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8015     uuid_e = 16*'\x11'
8016     e_nonce = 16*'\x22'
8017     own_private, e_pk = wsc_dh_init()
8018
8019     logger.debug("Send M1 to AP")
8020     with alloc_fail(hapd, 1, "wpabuf_alloc_copy;wps_process_pubkey"):
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         wps_wait_eap_failure(hapd, dev[0])
8025
8026 def wps_wait_eap_failure(hapd, dev):
8027     ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
8028     if ev is None:
8029         raise Exception("EAP-Failure not reported")
8030     dev.wait_disconnected()
8031
8032 def test_wps_ext_m3_m1(dev, apdev):
8033     """WPS proto: M3 replaced with M1"""
8034     pin = "12345670"
8035     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8036     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8037     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8038
8039     logger.debug("Receive WSC/Start from AP")
8040     msg = get_wsc_msg(hapd)
8041     if msg['wsc_opcode'] != WSC_Start:
8042         raise Exception("Unexpected Op-Code for WSC/Start")
8043
8044     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8045     uuid_e = 16*'\x11'
8046     e_nonce = 16*'\x22'
8047     own_private, e_pk = wsc_dh_init()
8048
8049     logger.debug("Send M1 to AP")
8050     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8051                                 e_nonce, e_pk)
8052     send_wsc_msg(hapd, addr, m1)
8053
8054     logger.debug("Receive M2 from AP")
8055     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8056     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8057     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8058
8059     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8060                                     r_nonce)
8061     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8062
8063     logger.debug("Send M3(M1) to AP")
8064     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8065     attrs += build_attr_msg_type(WPS_M1)
8066     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8067     attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8068     attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8069     attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8070     raw_m3_attrs = attrs
8071     m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8072     send_wsc_msg(hapd, addr, m3)
8073
8074     wps_wait_eap_failure(hapd, dev[0])
8075
8076 def test_wps_ext_m5_m3(dev, apdev):
8077     """WPS proto: M5 replaced with M3"""
8078     pin = "12345670"
8079     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8080     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8081     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8082
8083     logger.debug("Receive WSC/Start from AP")
8084     msg = get_wsc_msg(hapd)
8085     if msg['wsc_opcode'] != WSC_Start:
8086         raise Exception("Unexpected Op-Code for WSC/Start")
8087
8088     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8089     uuid_e = 16*'\x11'
8090     e_nonce = 16*'\x22'
8091     own_private, e_pk = wsc_dh_init()
8092
8093     logger.debug("Send M1 to AP")
8094     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8095                                 e_nonce, e_pk)
8096     send_wsc_msg(hapd, addr, m1)
8097
8098     logger.debug("Receive M2 from AP")
8099     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8100     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8101     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8102
8103     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8104                                     r_nonce)
8105     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8106
8107     logger.debug("Send M3 to AP")
8108     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8109     attrs += build_attr_msg_type(WPS_M3)
8110     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8111     attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8112     attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8113     attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8114     raw_m3_attrs = attrs
8115     m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8116     send_wsc_msg(hapd, addr, m3)
8117
8118     logger.debug("Receive M4 from AP")
8119     msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8120
8121     logger.debug("Send M5(M3) to AP")
8122     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8123     attrs += build_attr_msg_type(WPS_M3)
8124     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8125     data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8126     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8127     attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8128     raw_m5_attrs = attrs
8129     m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8130     send_wsc_msg(hapd, addr, m5)
8131
8132     wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8133
8134 def test_wps_ext_m3_m2(dev, apdev):
8135     """WPS proto: M3 replaced with M2"""
8136     pin = "12345670"
8137     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8138     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8139     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8140
8141     logger.debug("Receive WSC/Start from AP")
8142     msg = get_wsc_msg(hapd)
8143     if msg['wsc_opcode'] != WSC_Start:
8144         raise Exception("Unexpected Op-Code for WSC/Start")
8145
8146     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8147     uuid_e = 16*'\x11'
8148     e_nonce = 16*'\x22'
8149     own_private, e_pk = wsc_dh_init()
8150
8151     logger.debug("Send M1 to AP")
8152     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8153                                 e_nonce, e_pk)
8154     send_wsc_msg(hapd, addr, m1)
8155
8156     logger.debug("Receive M2 from AP")
8157     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8158     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8159     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8160
8161     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8162                                     r_nonce)
8163     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8164
8165     logger.debug("Send M3(M2) to AP")
8166     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8167     attrs += build_attr_msg_type(WPS_M2)
8168     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8169     attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8170     raw_m3_attrs = attrs
8171     m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8172     send_wsc_msg(hapd, addr, m3)
8173
8174     wps_wait_eap_failure(hapd, dev[0])
8175
8176 def test_wps_ext_m3_m5(dev, apdev):
8177     """WPS proto: M3 replaced with M5"""
8178     pin = "12345670"
8179     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8180     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8181     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8182
8183     logger.debug("Receive WSC/Start from AP")
8184     msg = get_wsc_msg(hapd)
8185     if msg['wsc_opcode'] != WSC_Start:
8186         raise Exception("Unexpected Op-Code for WSC/Start")
8187
8188     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8189     uuid_e = 16*'\x11'
8190     e_nonce = 16*'\x22'
8191     own_private, e_pk = wsc_dh_init()
8192
8193     logger.debug("Send M1 to AP")
8194     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8195                                 e_nonce, e_pk)
8196     send_wsc_msg(hapd, addr, m1)
8197
8198     logger.debug("Receive M2 from AP")
8199     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8200     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8201     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8202
8203     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8204                                     r_nonce)
8205     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8206
8207     logger.debug("Send M3(M5) to AP")
8208     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8209     attrs += build_attr_msg_type(WPS_M5)
8210     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8211     attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8212     attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8213     attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8214     raw_m3_attrs = attrs
8215     m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8216     send_wsc_msg(hapd, addr, m3)
8217
8218     wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8219
8220 def test_wps_ext_m3_m7(dev, apdev):
8221     """WPS proto: M3 replaced with M7"""
8222     pin = "12345670"
8223     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8224     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8225     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8226
8227     logger.debug("Receive WSC/Start from AP")
8228     msg = get_wsc_msg(hapd)
8229     if msg['wsc_opcode'] != WSC_Start:
8230         raise Exception("Unexpected Op-Code for WSC/Start")
8231
8232     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8233     uuid_e = 16*'\x11'
8234     e_nonce = 16*'\x22'
8235     own_private, e_pk = wsc_dh_init()
8236
8237     logger.debug("Send M1 to AP")
8238     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8239                                 e_nonce, e_pk)
8240     send_wsc_msg(hapd, addr, m1)
8241
8242     logger.debug("Receive M2 from AP")
8243     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8244     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8245     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8246
8247     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8248                                     r_nonce)
8249     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8250
8251     logger.debug("Send M3(M7) to AP")
8252     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8253     attrs += build_attr_msg_type(WPS_M7)
8254     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8255     attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8256     attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8257     attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8258     raw_m3_attrs = attrs
8259     m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8260     send_wsc_msg(hapd, addr, m3)
8261
8262     wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8263
8264 def test_wps_ext_m3_done(dev, apdev):
8265     """WPS proto: M3 replaced with WSC_Done"""
8266     pin = "12345670"
8267     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8268     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8269     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8270
8271     logger.debug("Receive WSC/Start from AP")
8272     msg = get_wsc_msg(hapd)
8273     if msg['wsc_opcode'] != WSC_Start:
8274         raise Exception("Unexpected Op-Code for WSC/Start")
8275
8276     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8277     uuid_e = 16*'\x11'
8278     e_nonce = 16*'\x22'
8279     own_private, e_pk = wsc_dh_init()
8280
8281     logger.debug("Send M1 to AP")
8282     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8283                                 e_nonce, e_pk)
8284     send_wsc_msg(hapd, addr, m1)
8285
8286     logger.debug("Receive M2 from AP")
8287     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8288     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8289     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8290
8291     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8292                                     r_nonce)
8293     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8294
8295     logger.debug("Send M3(WSC_Done) to AP")
8296     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8297     attrs += build_attr_msg_type(WPS_WSC_DONE)
8298     attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8299     raw_m3_attrs = attrs
8300     m3 = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8301     send_wsc_msg(hapd, addr, m3)
8302
8303     wps_wait_eap_failure(hapd, dev[0])
8304
8305 def test_wps_ext_m2_nack_invalid(dev, apdev):
8306     """WPS proto: M2 followed by invalid NACK"""
8307     pin = "12345670"
8308     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8309     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8310     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8311
8312     logger.debug("Receive WSC/Start from AP")
8313     msg = get_wsc_msg(hapd)
8314     if msg['wsc_opcode'] != WSC_Start:
8315         raise Exception("Unexpected Op-Code for WSC/Start")
8316
8317     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8318     uuid_e = 16*'\x11'
8319     e_nonce = 16*'\x22'
8320     own_private, e_pk = wsc_dh_init()
8321
8322     logger.debug("Send M1 to AP")
8323     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8324                                 e_nonce, e_pk)
8325     send_wsc_msg(hapd, addr, m1)
8326
8327     logger.debug("Receive M2 from AP")
8328     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8329     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8330     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8331
8332     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8333                                     r_nonce)
8334     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8335
8336     logger.debug("Send WSC_NACK to AP")
8337     attrs = '\x10\x00\x00'
8338     nack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_NACK)
8339     send_wsc_msg(hapd, addr, nack)
8340
8341     wps_wait_eap_failure(hapd, dev[0])
8342
8343 def test_wps_ext_m2_nack_no_msg_type(dev, apdev):
8344     """WPS proto: M2 followed by NACK without Msg Type"""
8345     pin = "12345670"
8346     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8347     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8348     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8349
8350     logger.debug("Receive WSC/Start from AP")
8351     msg = get_wsc_msg(hapd)
8352     if msg['wsc_opcode'] != WSC_Start:
8353         raise Exception("Unexpected Op-Code for WSC/Start")
8354
8355     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8356     uuid_e = 16*'\x11'
8357     e_nonce = 16*'\x22'
8358     own_private, e_pk = wsc_dh_init()
8359
8360     logger.debug("Send M1 to AP")
8361     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8362                                 e_nonce, e_pk)
8363     send_wsc_msg(hapd, addr, m1)
8364
8365     logger.debug("Receive M2 from AP")
8366     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8367     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8368     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8369
8370     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8371                                     r_nonce)
8372     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8373
8374     logger.debug("Send WSC_NACK to AP")
8375     nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8376                             msg_type=None, eap_code=2)
8377     send_wsc_msg(hapd, addr, nack)
8378
8379     wps_wait_eap_failure(hapd, dev[0])
8380
8381 def test_wps_ext_m2_nack_invalid_msg_type(dev, apdev):
8382     """WPS proto: M2 followed by NACK with invalid Msg Type"""
8383     pin = "12345670"
8384     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8385     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8386     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8387
8388     logger.debug("Receive WSC/Start from AP")
8389     msg = get_wsc_msg(hapd)
8390     if msg['wsc_opcode'] != WSC_Start:
8391         raise Exception("Unexpected Op-Code for WSC/Start")
8392
8393     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8394     uuid_e = 16*'\x11'
8395     e_nonce = 16*'\x22'
8396     own_private, e_pk = wsc_dh_init()
8397
8398     logger.debug("Send M1 to AP")
8399     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8400                                 e_nonce, e_pk)
8401     send_wsc_msg(hapd, addr, m1)
8402
8403     logger.debug("Receive M2 from AP")
8404     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8405     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8406     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8407
8408     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8409                                     r_nonce)
8410     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8411
8412     logger.debug("Send WSC_NACK to AP")
8413     nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8414                             msg_type=WPS_WSC_ACK, eap_code=2)
8415     send_wsc_msg(hapd, addr, nack)
8416
8417     wps_wait_eap_failure(hapd, dev[0])
8418
8419 def test_wps_ext_m2_nack_e_nonce_mismatch(dev, apdev):
8420     """WPS proto: M2 followed by NACK with e-nonce mismatch"""
8421     pin = "12345670"
8422     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8423     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8424     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8425
8426     logger.debug("Receive WSC/Start from AP")
8427     msg = get_wsc_msg(hapd)
8428     if msg['wsc_opcode'] != WSC_Start:
8429         raise Exception("Unexpected Op-Code for WSC/Start")
8430
8431     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8432     uuid_e = 16*'\x11'
8433     e_nonce = 16*'\x22'
8434     own_private, e_pk = wsc_dh_init()
8435
8436     logger.debug("Send M1 to AP")
8437     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8438                                 e_nonce, e_pk)
8439     send_wsc_msg(hapd, addr, m1)
8440
8441     logger.debug("Receive M2 from AP")
8442     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8443     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8444     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8445
8446     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8447                                     r_nonce)
8448     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8449
8450     logger.debug("Send WSC_NACK to AP")
8451     nack,attrs = build_nack(msg['eap_identifier'], 16*'\x00', r_nonce,
8452                             eap_code=2)
8453     send_wsc_msg(hapd, addr, nack)
8454
8455     wps_wait_eap_failure(hapd, dev[0])
8456
8457 def test_wps_ext_m2_nack_no_config_error(dev, apdev):
8458     """WPS proto: M2 followed by NACK without Config Error"""
8459     pin = "12345670"
8460     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8461     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8462     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8463
8464     logger.debug("Receive WSC/Start from AP")
8465     msg = get_wsc_msg(hapd)
8466     if msg['wsc_opcode'] != WSC_Start:
8467         raise Exception("Unexpected Op-Code for WSC/Start")
8468
8469     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8470     uuid_e = 16*'\x11'
8471     e_nonce = 16*'\x22'
8472     own_private, e_pk = wsc_dh_init()
8473
8474     logger.debug("Send M1 to AP")
8475     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8476                                 e_nonce, e_pk)
8477     send_wsc_msg(hapd, addr, m1)
8478
8479     logger.debug("Receive M2 from AP")
8480     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8481     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8482     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8483
8484     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8485                                     r_nonce)
8486     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8487
8488     logger.debug("Send WSC_NACK to AP")
8489     nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8490                             config_error=None, eap_code=2)
8491     send_wsc_msg(hapd, addr, nack)
8492
8493     wps_wait_eap_failure(hapd, dev[0])
8494
8495 def test_wps_ext_m2_ack_invalid(dev, apdev):
8496     """WPS proto: M2 followed by invalid ACK"""
8497     pin = "12345670"
8498     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8499     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8500     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8501
8502     logger.debug("Receive WSC/Start from AP")
8503     msg = get_wsc_msg(hapd)
8504     if msg['wsc_opcode'] != WSC_Start:
8505         raise Exception("Unexpected Op-Code for WSC/Start")
8506
8507     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8508     uuid_e = 16*'\x11'
8509     e_nonce = 16*'\x22'
8510     own_private, e_pk = wsc_dh_init()
8511
8512     logger.debug("Send M1 to AP")
8513     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8514                                 e_nonce, e_pk)
8515     send_wsc_msg(hapd, addr, m1)
8516
8517     logger.debug("Receive M2 from AP")
8518     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8519     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8520     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8521
8522     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8523                                     r_nonce)
8524     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8525
8526     logger.debug("Send WSC_ACK to AP")
8527     attrs = '\x10\x00\x00'
8528     ack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_ACK)
8529     send_wsc_msg(hapd, addr, ack)
8530
8531     wps_wait_eap_failure(hapd, dev[0])
8532
8533 def test_wps_ext_m2_ack(dev, apdev):
8534     """WPS proto: M2 followed by ACK"""
8535     pin = "12345670"
8536     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8537     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8538     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8539
8540     logger.debug("Receive WSC/Start from AP")
8541     msg = get_wsc_msg(hapd)
8542     if msg['wsc_opcode'] != WSC_Start:
8543         raise Exception("Unexpected Op-Code for WSC/Start")
8544
8545     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8546     uuid_e = 16*'\x11'
8547     e_nonce = 16*'\x22'
8548     own_private, e_pk = wsc_dh_init()
8549
8550     logger.debug("Send M1 to AP")
8551     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8552                                 e_nonce, e_pk)
8553     send_wsc_msg(hapd, addr, m1)
8554
8555     logger.debug("Receive M2 from AP")
8556     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8557     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8558     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8559
8560     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8561                                     r_nonce)
8562     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8563
8564     logger.debug("Send WSC_ACK to AP")
8565     ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce, eap_code=2)
8566     send_wsc_msg(hapd, addr, ack)
8567
8568     wps_wait_eap_failure(hapd, dev[0])
8569
8570 def test_wps_ext_m2_ack_no_msg_type(dev, apdev):
8571     """WPS proto: M2 followed by ACK missing Msg Type"""
8572     pin = "12345670"
8573     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8574     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8575     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8576
8577     logger.debug("Receive WSC/Start from AP")
8578     msg = get_wsc_msg(hapd)
8579     if msg['wsc_opcode'] != WSC_Start:
8580         raise Exception("Unexpected Op-Code for WSC/Start")
8581
8582     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8583     uuid_e = 16*'\x11'
8584     e_nonce = 16*'\x22'
8585     own_private, e_pk = wsc_dh_init()
8586
8587     logger.debug("Send M1 to AP")
8588     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8589                                 e_nonce, e_pk)
8590     send_wsc_msg(hapd, addr, m1)
8591
8592     logger.debug("Receive M2 from AP")
8593     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8594     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8595     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8596
8597     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8598                                     r_nonce)
8599     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8600
8601     logger.debug("Send WSC_ACK to AP")
8602     ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8603                           msg_type=None, eap_code=2)
8604     send_wsc_msg(hapd, addr, ack)
8605
8606     wps_wait_eap_failure(hapd, dev[0])
8607
8608 def test_wps_ext_m2_ack_invalid_msg_type(dev, apdev):
8609     """WPS proto: M2 followed by ACK with invalid Msg Type"""
8610     pin = "12345670"
8611     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8612     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8613     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8614
8615     logger.debug("Receive WSC/Start from AP")
8616     msg = get_wsc_msg(hapd)
8617     if msg['wsc_opcode'] != WSC_Start:
8618         raise Exception("Unexpected Op-Code for WSC/Start")
8619
8620     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8621     uuid_e = 16*'\x11'
8622     e_nonce = 16*'\x22'
8623     own_private, e_pk = wsc_dh_init()
8624
8625     logger.debug("Send M1 to AP")
8626     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8627                                 e_nonce, e_pk)
8628     send_wsc_msg(hapd, addr, m1)
8629
8630     logger.debug("Receive M2 from AP")
8631     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8632     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8633     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8634
8635     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8636                                     r_nonce)
8637     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8638
8639     logger.debug("Send WSC_ACK to AP")
8640     ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8641                           msg_type=WPS_WSC_NACK, eap_code=2)
8642     send_wsc_msg(hapd, addr, ack)
8643
8644     wps_wait_eap_failure(hapd, dev[0])
8645
8646 def test_wps_ext_m2_ack_e_nonce_mismatch(dev, apdev):
8647     """WPS proto: M2 followed by ACK with e-nonce mismatch"""
8648     pin = "12345670"
8649     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8650     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8651     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8652
8653     logger.debug("Receive WSC/Start from AP")
8654     msg = get_wsc_msg(hapd)
8655     if msg['wsc_opcode'] != WSC_Start:
8656         raise Exception("Unexpected Op-Code for WSC/Start")
8657
8658     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8659     uuid_e = 16*'\x11'
8660     e_nonce = 16*'\x22'
8661     own_private, e_pk = wsc_dh_init()
8662
8663     logger.debug("Send M1 to AP")
8664     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8665                                 e_nonce, e_pk)
8666     send_wsc_msg(hapd, addr, m1)
8667
8668     logger.debug("Receive M2 from AP")
8669     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8670     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8671     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8672
8673     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8674                                     r_nonce)
8675     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8676
8677     logger.debug("Send WSC_ACK to AP")
8678     ack,attrs = build_ack(msg['eap_identifier'], 16*'\x00', r_nonce,
8679                           eap_code=2)
8680     send_wsc_msg(hapd, addr, ack)
8681
8682     wps_wait_eap_failure(hapd, dev[0])
8683
8684 def test_wps_ext_m1_invalid(dev, apdev):
8685     """WPS proto: M1 failing parsing"""
8686     pin = "12345670"
8687     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8688     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8689     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8690
8691     logger.debug("Receive WSC/Start from AP")
8692     msg = get_wsc_msg(hapd)
8693     if msg['wsc_opcode'] != WSC_Start:
8694         raise Exception("Unexpected Op-Code for WSC/Start")
8695
8696     logger.debug("Send M1 to AP")
8697     attrs = '\x10\x00\x00'
8698     m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8699     send_wsc_msg(hapd, addr, m1)
8700
8701     wps_wait_eap_failure(hapd, dev[0])
8702
8703 def test_wps_ext_m1_missing_msg_type(dev, apdev):
8704     """WPS proto: M1 missing Msg Type"""
8705     pin = "12345670"
8706     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8707     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8708     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8709
8710     logger.debug("Receive WSC/Start from AP")
8711     msg = get_wsc_msg(hapd)
8712     if msg['wsc_opcode'] != WSC_Start:
8713         raise Exception("Unexpected Op-Code for WSC/Start")
8714
8715     logger.debug("Send M1 to AP")
8716     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8717     m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8718     send_wsc_msg(hapd, addr, m1)
8719
8720     wps_wait_ap_nack(hapd, dev[0], 16*'\x00', 16*'\x00')
8721
8722 def wps_ext_wsc_done(dev, apdev):
8723     pin = "12345670"
8724     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8725     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8726     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8727
8728     logger.debug("Receive WSC/Start from AP")
8729     msg = get_wsc_msg(hapd)
8730     if msg['wsc_opcode'] != WSC_Start:
8731         raise Exception("Unexpected Op-Code for WSC/Start")
8732
8733     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8734     uuid_e = 16*'\x11'
8735     e_nonce = 16*'\x22'
8736     own_private, e_pk = wsc_dh_init()
8737
8738     logger.debug("Send M1 to AP")
8739     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8740                                 e_nonce, e_pk)
8741     send_wsc_msg(hapd, addr, m1)
8742
8743     logger.debug("Receive M2 from AP")
8744     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8745     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8746     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8747
8748     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8749                                     r_nonce)
8750     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8751
8752     logger.debug("Send M3 to AP")
8753     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8754     attrs += build_attr_msg_type(WPS_M3)
8755     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8756     attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8757     attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8758     attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8759     raw_m3_attrs = attrs
8760     m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8761     send_wsc_msg(hapd, addr, m3)
8762
8763     logger.debug("Receive M4 from AP")
8764     msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8765
8766     logger.debug("Send M5 to AP")
8767     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8768     attrs += build_attr_msg_type(WPS_M5)
8769     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8770     data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8771     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8772     attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8773     raw_m5_attrs = attrs
8774     m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8775     send_wsc_msg(hapd, addr, m5)
8776
8777     logger.debug("Receive M6 from AP")
8778     msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8779
8780     logger.debug("Send M7 to AP")
8781     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8782     attrs += build_attr_msg_type(WPS_M7)
8783     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8784     data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
8785     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8786     attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8787     m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8788     raw_m7_attrs = attrs
8789     send_wsc_msg(hapd, addr, m7)
8790
8791     logger.debug("Receive M8 from AP")
8792     msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
8793     return hapd, msg, e_nonce, r_nonce
8794
8795 def test_wps_ext_wsc_done_invalid(dev, apdev):
8796     """WPS proto: invalid WSC_Done"""
8797     hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
8798
8799     logger.debug("Send WSC_Done to AP")
8800     attrs = '\x10\x00\x00'
8801     wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8802     send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
8803
8804     wps_wait_eap_failure(hapd, dev[0])
8805
8806 def test_wps_ext_wsc_done_no_msg_type(dev, apdev):
8807     """WPS proto: invalid WSC_Done"""
8808     hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
8809
8810     logger.debug("Send WSC_Done to AP")
8811     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8812     #attrs += build_attr_msg_type(WPS_WSC_DONE)
8813     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
8814     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8815     wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8816     send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
8817
8818     wps_wait_eap_failure(hapd, dev[0])
8819
8820 def test_wps_ext_wsc_done_wrong_msg_type(dev, apdev):
8821     """WPS proto: WSC_Done with wrong Msg Type"""
8822     hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
8823
8824     logger.debug("Send WSC_Done to AP")
8825     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8826     attrs += build_attr_msg_type(WPS_WSC_ACK)
8827     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
8828     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8829     wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8830     send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
8831
8832     wps_wait_eap_failure(hapd, dev[0])
8833
8834 def test_wps_ext_wsc_done_no_e_nonce(dev, apdev):
8835     """WPS proto: WSC_Done without e_nonce"""
8836     hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
8837
8838     logger.debug("Send WSC_Done to AP")
8839     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8840     attrs += build_attr_msg_type(WPS_WSC_DONE)
8841     #attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
8842     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8843     wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8844     send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
8845
8846     wps_wait_eap_failure(hapd, dev[0])
8847
8848 def test_wps_ext_wsc_done_no_r_nonce(dev, apdev):
8849     """WPS proto: WSC_Done without r_nonce"""
8850     hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
8851
8852     logger.debug("Send WSC_Done to AP")
8853     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8854     attrs += build_attr_msg_type(WPS_WSC_DONE)
8855     attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
8856     #attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8857     wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8858     send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
8859
8860     wps_wait_eap_failure(hapd, dev[0])
8861
8862 def test_wps_ext_m7_no_encr_settings(dev, apdev):
8863     """WPS proto: M7 without Encr Settings"""
8864     pin = "12345670"
8865     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8866     wps_ext_eap_identity_req(dev[0], hapd, bssid)
8867     wps_ext_eap_identity_resp(hapd, dev[0], addr)
8868
8869     logger.debug("Receive WSC/Start from AP")
8870     msg = get_wsc_msg(hapd)
8871     if msg['wsc_opcode'] != WSC_Start:
8872         raise Exception("Unexpected Op-Code for WSC/Start")
8873
8874     mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8875     uuid_e = 16*'\x11'
8876     e_nonce = 16*'\x22'
8877     own_private, e_pk = wsc_dh_init()
8878
8879     logger.debug("Send M1 to AP")
8880     m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8881                                 e_nonce, e_pk)
8882     send_wsc_msg(hapd, addr, m1)
8883
8884     logger.debug("Receive M2 from AP")
8885     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8886     r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8887     r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8888
8889     authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8890                                     r_nonce)
8891     e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8892
8893     logger.debug("Send M3 to AP")
8894     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8895     attrs += build_attr_msg_type(WPS_M3)
8896     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8897     attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8898     attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8899     attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8900     raw_m3_attrs = attrs
8901     m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8902     send_wsc_msg(hapd, addr, m3)
8903
8904     logger.debug("Receive M4 from AP")
8905     msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8906
8907     logger.debug("Send M5 to AP")
8908     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8909     attrs += build_attr_msg_type(WPS_M5)
8910     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8911     data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8912     attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8913     attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8914     raw_m5_attrs = attrs
8915     m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8916     send_wsc_msg(hapd, addr, m5)
8917
8918     logger.debug("Receive M6 from AP")
8919     msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8920
8921     logger.debug("Send M7 to AP")
8922     attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8923     attrs += build_attr_msg_type(WPS_M7)
8924     attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8925     #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
8926     #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8927     attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8928     m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8929     raw_m7_attrs = attrs
8930     send_wsc_msg(hapd, addr, m7)
8931
8932     wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8933
8934 def test_wps_ext_m1_workaround(dev, apdev):
8935     """WPS proto: M1 Manufacturer/Model workaround"""
8936     pin = "12345670"
8937     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
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(':', ''))
8947     uuid_e = 16*'\x11'
8948     e_nonce = 16*'\x22'
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, manufacturer='Apple TEST',
8954                                 model_name='AirPort', config_methods='\xff\xff')
8955     send_wsc_msg(hapd, addr, m1)
8956
8957     logger.debug("Receive M2 from AP")
8958     msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)