Updated to hostap_2_6
[mech_eap.git] / libeap / tests / hwsim / test_gas.py
1 # GAS tests
2 # Copyright (c) 2013, Qualcomm Atheros, Inc.
3 # Copyright (c) 2013-2015, Jouni Malinen <j@w1.fi>
4 #
5 # This software may be distributed under the terms of the BSD license.
6 # See README for more details.
7
8 from remotehost import remote_compatible
9 import time
10 import binascii
11 import logging
12 logger = logging.getLogger()
13 import os
14 import re
15 import struct
16
17 import hostapd
18 from wpasupplicant import WpaSupplicant
19 from tshark import run_tshark
20 from utils import alloc_fail, wait_fail_trigger, skip_with_fips
21 from hwsim import HWSimRadio
22
23 def hs20_ap_params():
24     params = hostapd.wpa2_params(ssid="test-gas")
25     params['wpa_key_mgmt'] = "WPA-EAP"
26     params['ieee80211w'] = "1"
27     params['ieee8021x'] = "1"
28     params['auth_server_addr'] = "127.0.0.1"
29     params['auth_server_port'] = "1812"
30     params['auth_server_shared_secret'] = "radius"
31     params['interworking'] = "1"
32     params['access_network_type'] = "14"
33     params['internet'] = "1"
34     params['asra'] = "0"
35     params['esr'] = "0"
36     params['uesa'] = "0"
37     params['venue_group'] = "7"
38     params['venue_type'] = "1"
39     params['venue_name'] = [ "eng:Example venue", "fin:Esimerkkipaikka" ]
40     params['roaming_consortium'] = [ "112233", "1020304050", "010203040506",
41                                      "fedcba" ]
42     params['domain_name'] = "example.com,another.example.com"
43     params['nai_realm'] = [ "0,example.com,13[5:6],21[2:4][5:7]",
44                             "0,another.example.com" ]
45     params['anqp_3gpp_cell_net'] = "244,91"
46     params['network_auth_type'] = "02http://www.example.com/redirect/me/here/"
47     params['ipaddr_type_availability'] = "14"
48     params['hs20'] = "1"
49     params['hs20_oper_friendly_name'] = [ "eng:Example operator", "fin:Esimerkkioperaattori" ]
50     params['hs20_wan_metrics'] = "01:8000:1000:80:240:3000"
51     params['hs20_conn_capab'] = [ "1:0:2", "6:22:1", "17:5060:0" ]
52     params['hs20_operating_class'] = "5173"
53     return params
54
55 def start_ap(ap):
56     params = hs20_ap_params()
57     params['hessid'] = ap['bssid']
58     return hostapd.add_ap(ap, params)
59
60 def get_gas_response(dev, bssid, info, allow_fetch_failure=False,
61                      extra_test=False):
62     exp = r'<.>(GAS-RESPONSE-INFO) addr=([0-9a-f:]*) dialog_token=([0-9]*) status_code=([0-9]*) resp_len=([\-0-9]*)'
63     res = re.split(exp, info)
64     if len(res) < 6:
65         raise Exception("Could not parse GAS-RESPONSE-INFO")
66     if res[2] != bssid:
67         raise Exception("Unexpected BSSID in response")
68     token = res[3]
69     status = res[4]
70     if status != "0":
71         raise Exception("GAS query failed")
72     resp_len = res[5]
73     if resp_len == "-1":
74         raise Exception("GAS query reported invalid response length")
75     if int(resp_len) > 2000:
76         raise Exception("Unexpected long GAS response")
77
78     if extra_test:
79         if "FAIL" not in dev.request("GAS_RESPONSE_GET " + bssid + " 123456"):
80             raise Exception("Invalid dialog token accepted")
81         if "FAIL-Invalid range" not in dev.request("GAS_RESPONSE_GET " + bssid + " " + token + " 10000,10001"):
82             raise Exception("Invalid range accepted")
83         if "FAIL-Invalid range" not in dev.request("GAS_RESPONSE_GET " + bssid + " " + token + " 0,10000"):
84             raise Exception("Invalid range accepted")
85         if "FAIL" not in dev.request("GAS_RESPONSE_GET " + bssid + " " + token + " 0"):
86             raise Exception("Invalid GAS_RESPONSE_GET accepted")
87
88         res1_2 = dev.request("GAS_RESPONSE_GET " + bssid + " " + token + " 1,2")
89         res5_3 = dev.request("GAS_RESPONSE_GET " + bssid + " " + token + " 5,3")
90
91     resp = dev.request("GAS_RESPONSE_GET " + bssid + " " + token)
92     if "FAIL" in resp:
93         if allow_fetch_failure:
94             logger.debug("GAS response was not available anymore")
95             return
96         raise Exception("Could not fetch GAS response")
97     if len(resp) != int(resp_len) * 2:
98         raise Exception("Unexpected GAS response length")
99     logger.debug("GAS response: " + resp)
100     if extra_test:
101         if resp[2:6] != res1_2:
102             raise Exception("Unexpected response substring res1_2: " + res1_2)
103         if resp[10:16] != res5_3:
104             raise Exception("Unexpected response substring res5_3: " + res5_3)
105
106 def test_gas_generic(dev, apdev):
107     """Generic GAS query"""
108     bssid = apdev[0]['bssid']
109     params = hs20_ap_params()
110     params['hessid'] = bssid
111     hostapd.add_ap(apdev[0], params)
112
113     cmds = [ "foo",
114              "00:11:22:33:44:55",
115              "00:11:22:33:44:55 ",
116              "00:11:22:33:44:55  ",
117              "00:11:22:33:44:55 1",
118              "00:11:22:33:44:55 1 1234",
119              "00:11:22:33:44:55 qq",
120              "00:11:22:33:44:55 qq 1234",
121              "00:11:22:33:44:55 00      1",
122              "00:11:22:33:44:55 00 123",
123              "00:11:22:33:44:55 00 ",
124              "00:11:22:33:44:55 00 qq" ]
125     for cmd in cmds:
126         if "FAIL" not in dev[0].request("GAS_REQUEST " + cmd):
127             raise Exception("Invalid GAS_REQUEST accepted: " + cmd)
128
129     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
130     req = dev[0].request("GAS_REQUEST " + bssid + " 00 000102000101")
131     if "FAIL" in req:
132         raise Exception("GAS query request rejected")
133     ev = dev[0].wait_event(["GAS-RESPONSE-INFO"], timeout=10)
134     if ev is None:
135         raise Exception("GAS query timed out")
136     get_gas_response(dev[0], bssid, ev, extra_test=True)
137
138     if "FAIL" not in dev[0].request("GAS_RESPONSE_GET ff"):
139         raise Exception("Invalid GAS_RESPONSE_GET accepted")
140
141 def test_gas_concurrent_scan(dev, apdev):
142     """Generic GAS queries with concurrent scan operation"""
143     bssid = apdev[0]['bssid']
144     params = hs20_ap_params()
145     params['hessid'] = bssid
146     hostapd.add_ap(apdev[0], params)
147
148     # get BSS entry available to allow GAS query
149     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
150
151     logger.info("Request concurrent operations")
152     req = dev[0].request("GAS_REQUEST " + bssid + " 00 000102000101")
153     if "FAIL" in req:
154         raise Exception("GAS query request rejected")
155     req = dev[0].request("GAS_REQUEST " + bssid + " 00 000102000801")
156     if "FAIL" in req:
157         raise Exception("GAS query request rejected")
158     dev[0].scan(no_wait=True)
159     req = dev[0].request("GAS_REQUEST " + bssid + " 00 000102000201")
160     if "FAIL" in req:
161         raise Exception("GAS query request rejected")
162     req = dev[0].request("GAS_REQUEST " + bssid + " 00 000102000501")
163     if "FAIL" in req:
164         raise Exception("GAS query request rejected")
165
166     responses = 0
167     for i in range(0, 5):
168         ev = dev[0].wait_event(["GAS-RESPONSE-INFO", "CTRL-EVENT-SCAN-RESULTS"],
169                                timeout=10)
170         if ev is None:
171             raise Exception("Operation timed out")
172         if "GAS-RESPONSE-INFO" in ev:
173             responses = responses + 1
174             get_gas_response(dev[0], bssid, ev, allow_fetch_failure=True)
175
176     if responses != 4:
177         raise Exception("Unexpected number of GAS responses")
178
179 def test_gas_concurrent_connect(dev, apdev):
180     """Generic GAS queries with concurrent connection operation"""
181     skip_with_fips(dev[0])
182     bssid = apdev[0]['bssid']
183     params = hs20_ap_params()
184     params['hessid'] = bssid
185     hostapd.add_ap(apdev[0], params)
186
187     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
188
189     logger.debug("Start concurrent connect and GAS request")
190     dev[0].connect("test-gas", key_mgmt="WPA-EAP", eap="TTLS",
191                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
192                    password="password", phase2="auth=MSCHAPV2",
193                    ca_cert="auth_serv/ca.pem", wait_connect=False,
194                    scan_freq="2412")
195     req = dev[0].request("GAS_REQUEST " + bssid + " 00 000102000101")
196     if "FAIL" in req:
197         raise Exception("GAS query request rejected")
198
199     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED", "GAS-RESPONSE-INFO"],
200                            timeout=20)
201     if ev is None:
202         raise Exception("Operation timed out")
203     if "CTRL-EVENT-CONNECTED" not in ev:
204         raise Exception("Unexpected operation order")
205
206     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED", "GAS-RESPONSE-INFO"],
207                            timeout=20)
208     if ev is None:
209         raise Exception("Operation timed out")
210     if "GAS-RESPONSE-INFO" not in ev:
211         raise Exception("Unexpected operation order")
212     get_gas_response(dev[0], bssid, ev)
213
214     dev[0].request("DISCONNECT")
215     dev[0].wait_disconnected(timeout=5)
216
217     logger.debug("Wait six seconds for expiration of connect-without-scan")
218     time.sleep(6)
219     dev[0].dump_monitor()
220
221     logger.debug("Start concurrent GAS request and connect")
222     req = dev[0].request("GAS_REQUEST " + bssid + " 00 000102000101")
223     if "FAIL" in req:
224         raise Exception("GAS query request rejected")
225     dev[0].request("RECONNECT")
226
227     ev = dev[0].wait_event(["GAS-RESPONSE-INFO"], timeout=10)
228     if ev is None:
229         raise Exception("Operation timed out")
230     get_gas_response(dev[0], bssid, ev)
231
232     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=20)
233     if ev is None:
234         raise Exception("No new scan results reported")
235
236     ev = dev[0].wait_connected(timeout=20, error="Operation tiemd out")
237     if "CTRL-EVENT-CONNECTED" not in ev:
238         raise Exception("Unexpected operation order")
239
240 def gas_fragment_and_comeback(dev, apdev, frag_limit=0, comeback_delay=0):
241     hapd = start_ap(apdev)
242     if frag_limit:
243         hapd.set("gas_frag_limit", str(frag_limit))
244     if comeback_delay:
245         hapd.set("gas_comeback_delay", str(comeback_delay))
246
247     dev.scan_for_bss(apdev['bssid'], freq="2412", force_scan=True)
248     dev.request("FETCH_ANQP")
249     ev = dev.wait_event(["GAS-QUERY-DONE"], timeout=5)
250     if ev is None:
251         raise Exception("No GAS-QUERY-DONE event")
252     if "result=SUCCESS" not in ev:
253         raise Exception("Unexpected GAS result: " + ev)
254     for i in range(0, 13):
255         ev = dev.wait_event(["RX-ANQP", "RX-HS20-ANQP"], timeout=5)
256         if ev is None:
257             raise Exception("Operation timed out")
258     ev = dev.wait_event(["ANQP-QUERY-DONE"], timeout=1)
259     if ev is None:
260         raise Exception("No ANQP-QUERY-DONE event")
261     if "result=SUCCESS" not in ev:
262         raise Exception("Unexpected ANQP result: " + ev)
263
264 def test_gas_fragment(dev, apdev):
265     """GAS fragmentation"""
266     gas_fragment_and_comeback(dev[0], apdev[0], frag_limit=50)
267
268 def test_gas_fragment_mcc(dev, apdev):
269     """GAS fragmentation with mac80211_hwsim MCC enabled"""
270     with HWSimRadio(n_channels=2) as (radio, iface):
271         wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
272         wpas.interface_add(iface)
273         gas_fragment_and_comeback(wpas, apdev[0], frag_limit=50)
274
275 def test_gas_fragment_with_comeback_delay(dev, apdev):
276     """GAS fragmentation and comeback delay"""
277     gas_fragment_and_comeback(dev[0], apdev[0], frag_limit=50,
278                               comeback_delay=500)
279
280 def test_gas_fragment_with_comeback_delay_mcc(dev, apdev):
281     """GAS fragmentation and comeback delay with mac80211_hwsim MCC enabled"""
282     with HWSimRadio(n_channels=2) as (radio, iface):
283         wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
284         wpas.interface_add(iface)
285         gas_fragment_and_comeback(wpas, apdev[0], frag_limit=50,
286                                   comeback_delay=500)
287
288 def test_gas_comeback_delay(dev, apdev):
289     """GAS comeback delay"""
290     hapd = start_ap(apdev[0])
291     hapd.set("gas_comeback_delay", "500")
292
293     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
294     dev[0].request("FETCH_ANQP")
295     if "FAIL-BUSY" not in dev[0].request("SCAN"):
296         raise Exception("SCAN accepted during FETCH_ANQP")
297     for i in range(0, 6):
298         ev = dev[0].wait_event(["RX-ANQP"], timeout=5)
299         if ev is None:
300             raise Exception("Operation timed out")
301
302 @remote_compatible
303 def test_gas_stop_fetch_anqp(dev, apdev):
304     """Stop FETCH_ANQP operation"""
305     hapd = start_ap(apdev[0])
306
307     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
308     hapd.set("ext_mgmt_frame_handling", "1")
309     dev[0].request("FETCH_ANQP")
310     dev[0].request("STOP_FETCH_ANQP")
311     hapd.set("ext_mgmt_frame_handling", "0")
312     ev = dev[0].wait_event(["RX-ANQP", "GAS-QUERY-DONE"], timeout=10)
313     if ev is None:
314         raise Exception("GAS-QUERY-DONE timed out")
315     if "RX-ANQP" in ev:
316         raise Exception("Unexpected ANQP response received")
317
318 def test_gas_anqp_get(dev, apdev):
319     """GAS/ANQP query for both IEEE 802.11 and Hotspot 2.0 elements"""
320     hapd = start_ap(apdev[0])
321     bssid = apdev[0]['bssid']
322
323     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
324     if "OK" not in dev[0].request("ANQP_GET " + bssid + " 258,268,hs20:3,hs20:4"):
325         raise Exception("ANQP_GET command failed")
326
327     ev = dev[0].wait_event(["GAS-QUERY-START"], timeout=5)
328     if ev is None:
329         raise Exception("GAS query start timed out")
330
331     ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=10)
332     if ev is None:
333         raise Exception("GAS query timed out")
334
335     ev = dev[0].wait_event(["RX-ANQP"], timeout=1)
336     if ev is None or "Venue Name" not in ev:
337         raise Exception("Did not receive Venue Name")
338
339     ev = dev[0].wait_event(["RX-ANQP"], timeout=1)
340     if ev is None or "Domain Name list" not in ev:
341         raise Exception("Did not receive Domain Name list")
342
343     ev = dev[0].wait_event(["RX-HS20-ANQP"], timeout=1)
344     if ev is None or "Operator Friendly Name" not in ev:
345         raise Exception("Did not receive Operator Friendly Name")
346
347     ev = dev[0].wait_event(["RX-HS20-ANQP"], timeout=1)
348     if ev is None or "WAN Metrics" not in ev:
349         raise Exception("Did not receive WAN Metrics")
350
351     ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=10)
352     if ev is None:
353         raise Exception("ANQP-QUERY-DONE event not seen")
354     if "result=SUCCESS" not in ev:
355         raise Exception("Unexpected result: " + ev)
356
357     if "OK" not in dev[0].request("HS20_ANQP_GET " + bssid + " 3,4"):
358         raise Exception("ANQP_GET command failed")
359
360     ev = dev[0].wait_event(["RX-HS20-ANQP"], timeout=1)
361     if ev is None or "Operator Friendly Name" not in ev:
362         raise Exception("Did not receive Operator Friendly Name")
363
364     ev = dev[0].wait_event(["RX-HS20-ANQP"], timeout=1)
365     if ev is None or "WAN Metrics" not in ev:
366         raise Exception("Did not receive WAN Metrics")
367
368     logger.info("Attempt an MBO request with an AP that does not support MBO")
369     if "OK" not in dev[0].request("ANQP_GET " + bssid + " 272,mbo:1"):
370         raise Exception("ANQP_GET command failed (2)")
371
372     ev = dev[0].wait_event(["GAS-QUERY-START"], timeout=5)
373     if ev is None:
374         raise Exception("GAS query start timed out (2)")
375
376     ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=10)
377     if ev is None:
378         raise Exception("GAS query timed out (2)")
379
380     cmds = [ "",
381              "foo",
382              "00:11:22:33:44:55 258,hs20:-1",
383              "00:11:22:33:44:55 258,hs20:0",
384              "00:11:22:33:44:55 258,hs20:32",
385              "00:11:22:33:44:55 hs20:-1",
386              "00:11:22:33:44:55 hs20:0",
387              "00:11:22:33:44:55 hs20:32",
388              "00:11:22:33:44:55 mbo:-1",
389              "00:11:22:33:44:55 mbo:0",
390              "00:11:22:33:44:55 mbo:999",
391              "00:11:22:33:44:55",
392              "00:11:22:33:44:55 ",
393              "00:11:22:33:44:55 0",
394              "00:11:22:33:44:55 1" ]
395     for cmd in cmds:
396         if "FAIL" not in dev[0].request("ANQP_GET " + cmd):
397             raise Exception("Invalid ANQP_GET accepted")
398
399     cmds = [ "",
400              "foo",
401              "00:11:22:33:44:55 -1",
402              "00:11:22:33:44:55 0",
403              "00:11:22:33:44:55 32",
404              "00:11:22:33:44:55",
405              "00:11:22:33:44:55 ",
406              "00:11:22:33:44:55 0",
407              "00:11:22:33:44:55 1" ]
408     for cmd in cmds:
409         if "FAIL" not in dev[0].request("HS20_ANQP_GET " + cmd):
410             raise Exception("Invalid HS20_ANQP_GET accepted")
411
412 def test_gas_anqp_get_oom(dev, apdev):
413     """GAS/ANQP query OOM"""
414     hapd = start_ap(apdev[0])
415     bssid = apdev[0]['bssid']
416
417     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
418     with alloc_fail(dev[0], 1, "wpabuf_alloc;anqp_send_req"):
419         if "FAIL" not in dev[0].request("ANQP_GET " + bssid + " 258,268,hs20:3,hs20:4"):
420             raise Exception("ANQP_GET command accepted during OOM")
421     with alloc_fail(dev[0], 1, "hs20_build_anqp_req;hs20_anqp_send_req"):
422         if "FAIL" not in dev[0].request("HS20_ANQP_GET " + bssid + " 1"):
423             raise Exception("HS20_ANQP_GET command accepted during OOM")
424     with alloc_fail(dev[0], 1, "gas_query_req;hs20_anqp_send_req"):
425         if "FAIL" not in dev[0].request("HS20_ANQP_GET " + bssid + " 1"):
426             raise Exception("HS20_ANQP_GET command accepted during OOM")
427     with alloc_fail(dev[0], 1, "=hs20_anqp_send_req"):
428         if "FAIL" not in dev[0].request("REQ_HS20_ICON " + bssid + " w1fi_logo"):
429             raise Exception("REQ_HS20_ICON command accepted during OOM")
430     with alloc_fail(dev[0], 2, "=hs20_anqp_send_req"):
431         if "FAIL" not in dev[0].request("REQ_HS20_ICON " + bssid + " w1fi_logo"):
432             raise Exception("REQ_HS20_ICON command accepted during OOM")
433
434 def test_gas_anqp_icon_binary_proto(dev, apdev):
435     """GAS/ANQP and icon binary protocol testing"""
436     hapd = start_ap(apdev[0])
437     bssid = apdev[0]['bssid']
438
439     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
440     hapd.set("ext_mgmt_frame_handling", "1")
441
442     tests = [ '010000', '01000000', '00000000', '00030000', '00020000',
443               '00000100', '0001ff0100ee', '0001ff0200ee' ]
444     for test in tests:
445         dev[0].request("HS20_ICON_REQUEST " + bssid + " w1fi_logo")
446         query = gas_rx(hapd)
447         gas = parse_gas(query['payload'])
448         resp = action_response(query)
449         data = binascii.unhexlify(test)
450         data = binascii.unhexlify('506f9a110b00') + data
451         data = struct.pack('<HHH', len(data) + 4, 0xdddd, len(data)) + data
452         resp['payload'] = anqp_initial_resp(gas['dialog_token'], 0) + data
453         send_gas_resp(hapd, resp)
454         expect_gas_result(dev[0], "SUCCESS")
455
456 def test_gas_anqp_hs20_proto(dev, apdev):
457     """GAS/ANQP and Hotspot 2.0 element protocol testing"""
458     hapd = start_ap(apdev[0])
459     bssid = apdev[0]['bssid']
460
461     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
462     hapd.set("ext_mgmt_frame_handling", "1")
463
464     tests = [ '00', '0100', '0201', '0300', '0400', '0500', '0600', '0700',
465               '0800', '0900', '0a00', '0b0000000000' ]
466     for test in tests:
467         dev[0].request("HS20_ANQP_GET " + bssid + " 3,4")
468         query = gas_rx(hapd)
469         gas = parse_gas(query['payload'])
470         resp = action_response(query)
471         data = binascii.unhexlify(test)
472         data = binascii.unhexlify('506f9a11') + data
473         data = struct.pack('<HHH', len(data) + 4, 0xdddd, len(data)) + data
474         resp['payload'] = anqp_initial_resp(gas['dialog_token'], 0) + data
475         send_gas_resp(hapd, resp)
476         expect_gas_result(dev[0], "SUCCESS")
477
478 def expect_gas_result(dev, result, status=None):
479     ev = dev.wait_event(["GAS-QUERY-DONE"], timeout=10)
480     if ev is None:
481         raise Exception("GAS query timed out")
482     if "result=" + result not in ev:
483         raise Exception("Unexpected GAS query result")
484     if status and "status_code=" + str(status) + ' ' not in ev:
485         raise Exception("Unexpected GAS status code")
486
487 def anqp_get(dev, bssid, id):
488     if "OK" not in dev.request("ANQP_GET " + bssid + " " + str(id)):
489         raise Exception("ANQP_GET command failed")
490     ev = dev.wait_event(["GAS-QUERY-START"], timeout=5)
491     if ev is None:
492         raise Exception("GAS query start timed out")
493
494 def test_gas_timeout(dev, apdev):
495     """GAS timeout"""
496     hapd = start_ap(apdev[0])
497     bssid = apdev[0]['bssid']
498
499     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
500     hapd.set("ext_mgmt_frame_handling", "1")
501
502     anqp_get(dev[0], bssid, 263)
503
504     ev = hapd.wait_event(["MGMT-RX"], timeout=5)
505     if ev is None:
506         raise Exception("MGMT RX wait timed out")
507
508     expect_gas_result(dev[0], "TIMEOUT")
509
510 MGMT_SUBTYPE_ACTION = 13
511 ACTION_CATEG_PUBLIC = 4
512
513 GAS_INITIAL_REQUEST = 10
514 GAS_INITIAL_RESPONSE = 11
515 GAS_COMEBACK_REQUEST = 12
516 GAS_COMEBACK_RESPONSE = 13
517 GAS_ACTIONS = [ GAS_INITIAL_REQUEST, GAS_INITIAL_RESPONSE,
518                 GAS_COMEBACK_REQUEST, GAS_COMEBACK_RESPONSE ]
519
520 def anqp_adv_proto():
521     return struct.pack('BBBB', 108, 2, 127, 0)
522
523 def anqp_initial_resp(dialog_token, status_code, comeback_delay=0):
524     return struct.pack('<BBBHH', ACTION_CATEG_PUBLIC, GAS_INITIAL_RESPONSE,
525                        dialog_token, status_code, comeback_delay) + anqp_adv_proto()
526
527 def anqp_comeback_resp(dialog_token, status_code=0, id=0, more=False, comeback_delay=0, bogus_adv_proto=False):
528     if more:
529         id |= 0x80
530     if bogus_adv_proto:
531         adv = struct.pack('BBBB', 108, 2, 127, 1)
532     else:
533         adv = anqp_adv_proto()
534     return struct.pack('<BBBHBH', ACTION_CATEG_PUBLIC, GAS_COMEBACK_RESPONSE,
535                        dialog_token, status_code, id, comeback_delay) + adv
536
537 def gas_rx(hapd):
538     count = 0
539     while count < 30:
540         count = count + 1
541         query = hapd.mgmt_rx()
542         if query is None:
543             raise Exception("Action frame not received")
544         if query['subtype'] != MGMT_SUBTYPE_ACTION:
545             continue
546         payload = query['payload']
547         if len(payload) < 2:
548             continue
549         (category, action) = struct.unpack('BB', payload[0:2])
550         if category != ACTION_CATEG_PUBLIC or action not in GAS_ACTIONS:
551             continue
552         return query
553     raise Exception("No Action frame received")
554
555 def parse_gas(payload):
556     pos = payload
557     (category, action, dialog_token) = struct.unpack('BBB', pos[0:3])
558     if category != ACTION_CATEG_PUBLIC:
559         return None
560     if action not in GAS_ACTIONS:
561         return None
562     gas = {}
563     gas['action'] = action
564     pos = pos[3:]
565
566     if len(pos) < 1 and action != GAS_COMEBACK_REQUEST:
567         return None
568
569     gas['dialog_token'] = dialog_token
570
571     if action == GAS_INITIAL_RESPONSE:
572         if len(pos) < 4:
573             return None
574         (status_code, comeback_delay) = struct.unpack('<HH', pos[0:4])
575         gas['status_code'] = status_code
576         gas['comeback_delay'] = comeback_delay
577
578     if action == GAS_COMEBACK_RESPONSE:
579         if len(pos) < 5:
580             return None
581         (status_code, frag, comeback_delay) = struct.unpack('<HBH', pos[0:5])
582         gas['status_code'] = status_code
583         gas['frag'] = frag
584         gas['comeback_delay'] = comeback_delay
585
586     return gas
587
588 def action_response(req):
589     resp = {}
590     resp['fc'] = req['fc']
591     resp['da'] = req['sa']
592     resp['sa'] = req['da']
593     resp['bssid'] = req['bssid']
594     return resp
595
596 def send_gas_resp(hapd, resp):
597     hapd.mgmt_tx(resp)
598     ev = hapd.wait_event(["MGMT-TX-STATUS"], timeout=5)
599     if ev is None:
600         raise Exception("Missing TX status for GAS response")
601     if "ok=1" not in ev:
602         raise Exception("GAS response not acknowledged")
603
604 def test_gas_invalid_response_type(dev, apdev):
605     """GAS invalid response type"""
606     hapd = start_ap(apdev[0])
607     bssid = apdev[0]['bssid']
608
609     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
610     hapd.set("ext_mgmt_frame_handling", "1")
611
612     anqp_get(dev[0], bssid, 263)
613
614     query = gas_rx(hapd)
615     gas = parse_gas(query['payload'])
616
617     resp = action_response(query)
618     # GAS Comeback Response instead of GAS Initial Response
619     resp['payload'] = anqp_comeback_resp(gas['dialog_token']) + struct.pack('<H', 0)
620     send_gas_resp(hapd, resp)
621
622     # station drops the invalid frame, so this needs to result in GAS timeout
623     expect_gas_result(dev[0], "TIMEOUT")
624
625 def test_gas_failure_status_code(dev, apdev):
626     """GAS failure status code"""
627     hapd = start_ap(apdev[0])
628     bssid = apdev[0]['bssid']
629
630     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
631     hapd.set("ext_mgmt_frame_handling", "1")
632
633     anqp_get(dev[0], bssid, 263)
634
635     query = gas_rx(hapd)
636     gas = parse_gas(query['payload'])
637
638     resp = action_response(query)
639     resp['payload'] = anqp_initial_resp(gas['dialog_token'], 61) + struct.pack('<H', 0)
640     send_gas_resp(hapd, resp)
641
642     expect_gas_result(dev[0], "FAILURE")
643
644 def test_gas_malformed(dev, apdev):
645     """GAS malformed response frames"""
646     hapd = start_ap(apdev[0])
647     bssid = apdev[0]['bssid']
648
649     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
650     hapd.set("ext_mgmt_frame_handling", "1")
651
652     anqp_get(dev[0], bssid, 263)
653
654     query = gas_rx(hapd)
655     gas = parse_gas(query['payload'])
656
657     resp = action_response(query)
658
659     resp['payload'] = struct.pack('<BBBH', ACTION_CATEG_PUBLIC,
660                                   GAS_COMEBACK_RESPONSE,
661                                   gas['dialog_token'], 0)
662     hapd.mgmt_tx(resp)
663
664     resp['payload'] = struct.pack('<BBBHB', ACTION_CATEG_PUBLIC,
665                                   GAS_COMEBACK_RESPONSE,
666                                   gas['dialog_token'], 0, 0)
667     hapd.mgmt_tx(resp)
668
669     hdr = struct.pack('<BBBHH', ACTION_CATEG_PUBLIC, GAS_INITIAL_RESPONSE,
670                       gas['dialog_token'], 0, 0)
671     resp['payload'] = hdr + struct.pack('B', 108)
672     hapd.mgmt_tx(resp)
673     resp['payload'] = hdr + struct.pack('BB', 108, 0)
674     hapd.mgmt_tx(resp)
675     resp['payload'] = hdr + struct.pack('BB', 108, 1)
676     hapd.mgmt_tx(resp)
677     resp['payload'] = hdr + struct.pack('BB', 108, 255)
678     hapd.mgmt_tx(resp)
679     resp['payload'] = hdr + struct.pack('BBB', 108, 1, 127)
680     hapd.mgmt_tx(resp)
681     resp['payload'] = hdr + struct.pack('BBB', 108, 2, 127)
682     hapd.mgmt_tx(resp)
683     resp['payload'] = hdr + struct.pack('BBBB', 0, 2, 127, 0)
684     hapd.mgmt_tx(resp)
685
686     resp['payload'] = anqp_initial_resp(gas['dialog_token'], 0) + struct.pack('<H', 1)
687     hapd.mgmt_tx(resp)
688
689     resp['payload'] = anqp_initial_resp(gas['dialog_token'], 0) + struct.pack('<HB', 2, 0)
690     hapd.mgmt_tx(resp)
691
692     resp['payload'] = anqp_initial_resp(gas['dialog_token'], 0) + struct.pack('<H', 65535)
693     hapd.mgmt_tx(resp)
694
695     resp['payload'] = anqp_initial_resp(gas['dialog_token'], 0) + struct.pack('<HBB', 1, 0, 0)
696     hapd.mgmt_tx(resp)
697
698     # Station drops invalid frames, but the last of the responses is valid from
699     # GAS view point even though it has an extra octet in the end and the ANQP
700     # part of the response is not valid. This is reported as successfully
701     # completed GAS exchange.
702     expect_gas_result(dev[0], "SUCCESS")
703
704     ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=5)
705     if ev is None:
706         raise Exception("ANQP-QUERY-DONE not reported")
707     if "result=INVALID_FRAME" not in ev:
708         raise Exception("Unexpected result: " + ev)
709
710 def init_gas(hapd, bssid, dev):
711     anqp_get(dev, bssid, 263)
712     query = gas_rx(hapd)
713     gas = parse_gas(query['payload'])
714     dialog_token = gas['dialog_token']
715
716     resp = action_response(query)
717     resp['payload'] = anqp_initial_resp(dialog_token, 0, comeback_delay=1) + struct.pack('<H', 0)
718     send_gas_resp(hapd, resp)
719
720     query = gas_rx(hapd)
721     gas = parse_gas(query['payload'])
722     if gas['action'] != GAS_COMEBACK_REQUEST:
723         raise Exception("Unexpected request action")
724     if gas['dialog_token'] != dialog_token:
725         raise Exception("Unexpected dialog token change")
726     return query, dialog_token
727
728 def allow_gas_initial_req(hapd, dialog_token):
729     msg = hapd.mgmt_rx(timeout=1)
730     if msg is not None:
731         gas = parse_gas(msg['payload'])
732         if gas['action'] != GAS_INITIAL_REQUEST or dialog_token == gas['dialog_token']:
733             raise Exception("Unexpected management frame")
734
735 def test_gas_malformed_comeback_resp(dev, apdev):
736     """GAS malformed comeback response frames"""
737     hapd = start_ap(apdev[0])
738     bssid = apdev[0]['bssid']
739
740     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
741     hapd.set("ext_mgmt_frame_handling", "1")
742
743     logger.debug("Non-zero status code in comeback response")
744     query, dialog_token = init_gas(hapd, bssid, dev[0])
745     resp = action_response(query)
746     resp['payload'] = anqp_comeback_resp(dialog_token, status_code=2) + struct.pack('<H', 0)
747     send_gas_resp(hapd, resp)
748     expect_gas_result(dev[0], "FAILURE", status=2)
749
750     logger.debug("Different advertisement protocol in comeback response")
751     query, dialog_token = init_gas(hapd, bssid, dev[0])
752     resp = action_response(query)
753     resp['payload'] = anqp_comeback_resp(dialog_token, bogus_adv_proto=True) + struct.pack('<H', 0)
754     send_gas_resp(hapd, resp)
755     expect_gas_result(dev[0], "PEER_ERROR")
756
757     logger.debug("Non-zero frag id and comeback delay in comeback response")
758     query, dialog_token = init_gas(hapd, bssid, dev[0])
759     resp = action_response(query)
760     resp['payload'] = anqp_comeback_resp(dialog_token, id=1, comeback_delay=1) + struct.pack('<H', 0)
761     send_gas_resp(hapd, resp)
762     expect_gas_result(dev[0], "PEER_ERROR")
763
764     logger.debug("Unexpected frag id in comeback response")
765     query, dialog_token = init_gas(hapd, bssid, dev[0])
766     resp = action_response(query)
767     resp['payload'] = anqp_comeback_resp(dialog_token, id=1) + struct.pack('<H', 0)
768     send_gas_resp(hapd, resp)
769     expect_gas_result(dev[0], "PEER_ERROR")
770
771     logger.debug("Empty fragment and replay in comeback response")
772     query, dialog_token = init_gas(hapd, bssid, dev[0])
773     resp = action_response(query)
774     resp['payload'] = anqp_comeback_resp(dialog_token, more=True) + struct.pack('<H', 0)
775     send_gas_resp(hapd, resp)
776     query = gas_rx(hapd)
777     gas = parse_gas(query['payload'])
778     if gas['action'] != GAS_COMEBACK_REQUEST:
779         raise Exception("Unexpected request action")
780     if gas['dialog_token'] != dialog_token:
781         raise Exception("Unexpected dialog token change")
782     resp = action_response(query)
783     resp['payload'] = anqp_comeback_resp(dialog_token) + struct.pack('<H', 0)
784     send_gas_resp(hapd, resp)
785     resp['payload'] = anqp_comeback_resp(dialog_token, id=1) + struct.pack('<H', 0)
786     send_gas_resp(hapd, resp)
787     expect_gas_result(dev[0], "SUCCESS")
788
789     logger.debug("Unexpected initial response when waiting for comeback response")
790     query, dialog_token = init_gas(hapd, bssid, dev[0])
791     resp = action_response(query)
792     resp['payload'] = anqp_initial_resp(dialog_token, 0) + struct.pack('<H', 0)
793     send_gas_resp(hapd, resp)
794     allow_gas_initial_req(hapd, dialog_token)
795     expect_gas_result(dev[0], "TIMEOUT")
796
797     logger.debug("Too short comeback response")
798     query, dialog_token = init_gas(hapd, bssid, dev[0])
799     resp = action_response(query)
800     resp['payload'] = struct.pack('<BBBH', ACTION_CATEG_PUBLIC,
801                                   GAS_COMEBACK_RESPONSE, dialog_token, 0)
802     send_gas_resp(hapd, resp)
803     allow_gas_initial_req(hapd, dialog_token)
804     expect_gas_result(dev[0], "TIMEOUT")
805
806     logger.debug("Too short comeback response(2)")
807     query, dialog_token = init_gas(hapd, bssid, dev[0])
808     resp = action_response(query)
809     resp['payload'] = struct.pack('<BBBHBB', ACTION_CATEG_PUBLIC,
810                                   GAS_COMEBACK_RESPONSE, dialog_token, 0, 0x80,
811                                   0)
812     send_gas_resp(hapd, resp)
813     allow_gas_initial_req(hapd, dialog_token)
814     expect_gas_result(dev[0], "TIMEOUT")
815
816     logger.debug("Maximum comeback response fragment claiming more fragments")
817     query, dialog_token = init_gas(hapd, bssid, dev[0])
818     resp = action_response(query)
819     resp['payload'] = anqp_comeback_resp(dialog_token, more=True) + struct.pack('<H', 0)
820     send_gas_resp(hapd, resp)
821     for i in range(1, 129):
822         query = gas_rx(hapd)
823         gas = parse_gas(query['payload'])
824         if gas['action'] != GAS_COMEBACK_REQUEST:
825             raise Exception("Unexpected request action")
826         if gas['dialog_token'] != dialog_token:
827             raise Exception("Unexpected dialog token change")
828         resp = action_response(query)
829         resp['payload'] = anqp_comeback_resp(dialog_token, id=i, more=True) + struct.pack('<H', 0)
830         send_gas_resp(hapd, resp)
831     expect_gas_result(dev[0], "PEER_ERROR")
832
833 def test_gas_comeback_resp_additional_delay(dev, apdev):
834     """GAS comeback response requesting additional delay"""
835     hapd = start_ap(apdev[0])
836     bssid = apdev[0]['bssid']
837
838     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
839     hapd.set("ext_mgmt_frame_handling", "1")
840
841     query, dialog_token = init_gas(hapd, bssid, dev[0])
842     for i in range(0, 2):
843         resp = action_response(query)
844         resp['payload'] = anqp_comeback_resp(dialog_token, status_code=95, comeback_delay=50) + struct.pack('<H', 0)
845         send_gas_resp(hapd, resp)
846         query = gas_rx(hapd)
847         gas = parse_gas(query['payload'])
848         if gas['action'] != GAS_COMEBACK_REQUEST:
849             raise Exception("Unexpected request action")
850         if gas['dialog_token'] != dialog_token:
851             raise Exception("Unexpected dialog token change")
852     resp = action_response(query)
853     resp['payload'] = anqp_comeback_resp(dialog_token, status_code=0) + struct.pack('<H', 0)
854     send_gas_resp(hapd, resp)
855     expect_gas_result(dev[0], "SUCCESS")
856
857 def test_gas_unknown_adv_proto(dev, apdev):
858     """Unknown advertisement protocol id"""
859     bssid = apdev[0]['bssid']
860     params = hs20_ap_params()
861     params['hessid'] = bssid
862     hostapd.add_ap(apdev[0], params)
863
864     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
865     req = dev[0].request("GAS_REQUEST " + bssid + " 42 000102000101")
866     if "FAIL" in req:
867         raise Exception("GAS query request rejected")
868     expect_gas_result(dev[0], "FAILURE", "59")
869     ev = dev[0].wait_event(["GAS-RESPONSE-INFO"], timeout=10)
870     if ev is None:
871         raise Exception("GAS query timed out")
872     exp = r'<.>(GAS-RESPONSE-INFO) addr=([0-9a-f:]*) dialog_token=([0-9]*) status_code=([0-9]*) resp_len=([\-0-9]*)'
873     res = re.split(exp, ev)
874     if len(res) < 6:
875         raise Exception("Could not parse GAS-RESPONSE-INFO")
876     if res[2] != bssid:
877         raise Exception("Unexpected BSSID in response")
878     status = res[4]
879     if status != "59":
880         raise Exception("Unexpected GAS-RESPONSE-INFO status")
881
882 def test_gas_request_oom(dev, apdev):
883     """GAS_REQUEST OOM"""
884     bssid = apdev[0]['bssid']
885     params = hs20_ap_params()
886     params['hessid'] = bssid
887     hostapd.add_ap(apdev[0], params)
888
889     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
890
891     with alloc_fail(dev[0], 1, "gas_build_req;gas_send_request"):
892         if "FAIL" not in dev[0].request("GAS_REQUEST " + bssid + " 42"):
893             raise Exception("GAS query request rejected")
894
895     with alloc_fail(dev[0], 1, "gas_query_req;gas_send_request"):
896         if "FAIL" not in dev[0].request("GAS_REQUEST " + bssid + " 42"):
897             raise Exception("GAS query request rejected")
898
899     with alloc_fail(dev[0], 1, "wpabuf_dup;gas_resp_cb"):
900         if "OK" not in dev[0].request("GAS_REQUEST " + bssid + " 00 000102000101"):
901             raise Exception("GAS query request rejected")
902         ev = dev[0].wait_event(["GAS-RESPONSE-INFO"], timeout=10)
903         if ev is None:
904             raise Exception("No GAS response")
905         if "status_code=0" not in ev:
906             raise Exception("GAS response indicated a failure")
907
908 def test_gas_max_pending(dev, apdev):
909     """GAS and maximum pending query limit"""
910     hapd = start_ap(apdev[0])
911     hapd.set("gas_frag_limit", "50")
912     bssid = apdev[0]['bssid']
913
914     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
915     wpas.interface_add("wlan5")
916     if "OK" not in wpas.request("P2P_SET listen_channel 1"):
917         raise Exception("Failed to set listen channel")
918     if "OK" not in wpas.p2p_listen():
919         raise Exception("Failed to start listen state")
920     if "FAIL" in wpas.request("SET ext_mgmt_frame_handling 1"):
921         raise Exception("Failed to enable external management frame handling")
922
923     anqp_query = struct.pack('<HHHHHHHHHH', 256, 16, 257, 258, 260, 261, 262, 263, 264, 268)
924     gas = struct.pack('<H', len(anqp_query)) + anqp_query
925
926     for dialog_token in range(1, 10):
927         msg = struct.pack('<BBB', ACTION_CATEG_PUBLIC, GAS_INITIAL_REQUEST,
928                           dialog_token) + anqp_adv_proto() + gas
929         req = "MGMT_TX {} {} freq=2412 wait_time=10 action={}".format(bssid, bssid, binascii.hexlify(msg))
930         if "OK" not in wpas.request(req):
931             raise Exception("Could not send management frame")
932         resp = wpas.mgmt_rx()
933         if resp is None:
934             raise Exception("MGMT-RX timeout")
935         if 'payload' not in resp:
936             raise Exception("Missing payload")
937         gresp = parse_gas(resp['payload'])
938         if gresp['dialog_token'] != dialog_token:
939             raise Exception("Dialog token mismatch")
940         status_code = gresp['status_code']
941         if dialog_token < 9 and status_code != 0:
942             raise Exception("Unexpected failure status code {} for dialog token {}".format(status_code, dialog_token))
943         if dialog_token > 8 and status_code == 0:
944             raise Exception("Unexpected success status code {} for dialog token {}".format(status_code, dialog_token))
945
946 def test_gas_no_pending(dev, apdev):
947     """GAS and no pending query for comeback request"""
948     hapd = start_ap(apdev[0])
949     bssid = apdev[0]['bssid']
950
951     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
952     wpas.interface_add("wlan5")
953     if "OK" not in wpas.request("P2P_SET listen_channel 1"):
954         raise Exception("Failed to set listen channel")
955     if "OK" not in wpas.p2p_listen():
956         raise Exception("Failed to start listen state")
957     if "FAIL" in wpas.request("SET ext_mgmt_frame_handling 1"):
958         raise Exception("Failed to enable external management frame handling")
959
960     msg = struct.pack('<BBB', ACTION_CATEG_PUBLIC, GAS_COMEBACK_REQUEST, 1)
961     req = "MGMT_TX {} {} freq=2412 wait_time=10 action={}".format(bssid, bssid, binascii.hexlify(msg))
962     if "OK" not in wpas.request(req):
963         raise Exception("Could not send management frame")
964     resp = wpas.mgmt_rx()
965     if resp is None:
966         raise Exception("MGMT-RX timeout")
967     if 'payload' not in resp:
968         raise Exception("Missing payload")
969     gresp = parse_gas(resp['payload'])
970     status_code = gresp['status_code']
971     if status_code != 60:
972         raise Exception("Unexpected status code {} (expected 60)".format(status_code))
973
974 def test_gas_delete_at_deinit(dev, apdev):
975     """GAS query deleted at deinit"""
976     hapd = start_ap(apdev[0])
977     hapd.set("gas_comeback_delay", "1000")
978     bssid = apdev[0]['bssid']
979
980     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
981     wpas.interface_add("wlan5")
982     wpas.scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
983     wpas.request("ANQP_GET " + bssid + " 258")
984
985     wpas.global_request("INTERFACE_REMOVE " + wpas.ifname)
986     ev = wpas.wait_event(["GAS-QUERY-DONE"], timeout=2)
987     del wpas
988     if ev is None:
989         raise Exception("GAS-QUERY-DONE not seen")
990     if "result=DELETED_AT_DEINIT" not in ev:
991         raise Exception("Unexpected result code: " + ev)
992
993 def test_gas_missing_payload(dev, apdev):
994     """No action code in the query frame"""
995     bssid = apdev[0]['bssid']
996     params = hs20_ap_params()
997     params['hessid'] = bssid
998     hostapd.add_ap(apdev[0], params)
999
1000     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
1001
1002     cmd = "MGMT_TX {} {} freq=2412 action=040A".format(bssid, bssid)
1003     if "FAIL" in dev[0].request(cmd):
1004         raise Exception("Could not send test Action frame")
1005     ev = dev[0].wait_event(["MGMT-TX-STATUS"], timeout=10)
1006     if ev is None:
1007         raise Exception("Timeout on MGMT-TX-STATUS")
1008     if "result=SUCCESS" not in ev:
1009         raise Exception("AP did not ack Action frame")
1010
1011     cmd = "MGMT_TX {} {} freq=2412 action=04".format(bssid, bssid)
1012     if "FAIL" in dev[0].request(cmd):
1013         raise Exception("Could not send test Action frame")
1014     ev = dev[0].wait_event(["MGMT-TX-STATUS"], timeout=10)
1015     if ev is None:
1016         raise Exception("Timeout on MGMT-TX-STATUS")
1017     if "result=SUCCESS" not in ev:
1018         raise Exception("AP did not ack Action frame")
1019
1020 def test_gas_query_deinit(dev, apdev):
1021     """Pending GAS/ANQP query during deinit"""
1022     hapd = start_ap(apdev[0])
1023     bssid = apdev[0]['bssid']
1024
1025     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
1026     wpas.interface_add("wlan5")
1027
1028     wpas.scan_for_bss(bssid, freq="2412", force_scan=True)
1029     id = wpas.request("RADIO_WORK add block-work")
1030     if "OK" not in wpas.request("ANQP_GET " + bssid + " 258"):
1031         raise Exception("ANQP_GET command failed")
1032
1033     ev = wpas.wait_event(["GAS-QUERY-START", "EXT-RADIO-WORK-START"], timeout=5)
1034     if ev is None:
1035         raise Exception("Timeout while waiting radio work to start")
1036     ev = wpas.wait_event(["GAS-QUERY-START", "EXT-RADIO-WORK-START"], timeout=5)
1037     if ev is None:
1038         raise Exception("Timeout while waiting radio work to start (2)")
1039
1040     # Remove the interface while the gas-query radio work is still pending and
1041     # GAS query has not yet been started.
1042     wpas.interface_remove("wlan5")
1043
1044 @remote_compatible
1045 def test_gas_anqp_oom_wpas(dev, apdev):
1046     """GAS/ANQP query and OOM in wpa_supplicant"""
1047     hapd = start_ap(apdev[0])
1048     bssid = apdev[0]['bssid']
1049
1050     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
1051
1052     with alloc_fail(dev[0], 1, "wpa_bss_anqp_alloc"):
1053         if "OK" not in dev[0].request("ANQP_GET " + bssid + " 258"):
1054             raise Exception("ANQP_GET command failed")
1055         ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=5)
1056         if ev is None:
1057             raise Exception("ANQP query did not complete")
1058
1059     with alloc_fail(dev[0], 1, "gas_build_req"):
1060         if "FAIL" not in dev[0].request("ANQP_GET " + bssid + " 258"):
1061             raise Exception("Unexpected ANQP_GET command success (OOM)")
1062
1063 def test_gas_anqp_oom_hapd(dev, apdev):
1064     """GAS/ANQP query and OOM in hostapd"""
1065     hapd = start_ap(apdev[0])
1066     bssid = apdev[0]['bssid']
1067
1068     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
1069
1070     with alloc_fail(hapd, 1, "gas_build_resp"):
1071         # This query will time out due to the AP not sending a response (OOM).
1072         if "OK" not in dev[0].request("ANQP_GET " + bssid + " 258"):
1073             raise Exception("ANQP_GET command failed")
1074
1075         ev = dev[0].wait_event(["GAS-QUERY-START"], timeout=5)
1076         if ev is None:
1077             raise Exception("GAS query start timed out")
1078
1079         ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=10)
1080         if ev is None:
1081             raise Exception("GAS query timed out")
1082         if "result=TIMEOUT" not in ev:
1083             raise Exception("Unexpected result: " + ev)
1084
1085         ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=10)
1086         if ev is None:
1087             raise Exception("ANQP-QUERY-DONE event not seen")
1088         if "result=FAILURE" not in ev:
1089             raise Exception("Unexpected result: " + ev)
1090
1091     with alloc_fail(hapd, 1, "gas_anqp_build_comeback_resp"):
1092         hapd.set("gas_frag_limit", "50")
1093
1094         # The first attempt of this query will time out due to the AP not
1095         # sending a response (OOM), but the retry succeeds.
1096         dev[0].request("FETCH_ANQP")
1097         ev = dev[0].wait_event(["GAS-QUERY-START"], timeout=5)
1098         if ev is None:
1099             raise Exception("GAS query start timed out")
1100
1101         ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=10)
1102         if ev is None:
1103             raise Exception("GAS query timed out")
1104         if "result=SUCCESS" not in ev:
1105             raise Exception("Unexpected result: " + ev)
1106
1107         ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=10)
1108         if ev is None:
1109             raise Exception("ANQP-QUERY-DONE event not seen")
1110         if "result=SUCCESS" not in ev:
1111             raise Exception("Unexpected result: " + ev)
1112
1113 def test_gas_anqp_extra_elements(dev, apdev):
1114     """GAS/ANQP and extra ANQP elements"""
1115     geo_loc = "001052834d12efd2b08b9b4bf1cc2c00004104050000000000060100"
1116     civic_loc = "0000f9555302f50102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5"
1117     held_uri = "https://held.example.com/location"
1118     held = struct.pack('BBB', 0, 1 + len(held_uri), 1) + held_uri
1119     supl_fqdn = "supl.example.com"
1120     supl = struct.pack('BBB', 0, 1 + len(supl_fqdn), 1) + supl_fqdn
1121     public_id = binascii.hexlify(held + supl)
1122     params = { "ssid": "gas/anqp",
1123                "interworking": "1",
1124                "anqp_elem": [ "265:" + geo_loc,
1125                               "266:" + civic_loc,
1126                               "262:1122334455",
1127                               "267:" + public_id,
1128                               "275:01020304",
1129                               "60000:01",
1130                               "299:0102" ] }
1131     hapd = hostapd.add_ap(apdev[0], params)
1132     bssid = apdev[0]['bssid']
1133
1134     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
1135     if "OK" not in dev[0].request("ANQP_GET " + bssid + " 265,266"):
1136         raise Exception("ANQP_GET command failed")
1137
1138     ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=10)
1139     if ev is None:
1140         raise Exception("GAS query timed out")
1141
1142     bss = dev[0].get_bss(bssid)
1143
1144     if 'anqp[265]' not in bss:
1145         raise Exception("AP Geospatial Location ANQP-element not seen")
1146     if bss['anqp[265]'] != geo_loc:
1147         raise Exception("Unexpected AP Geospatial Location ANQP-element value: " + bss['anqp[265]'])
1148
1149     if 'anqp[266]' not in bss:
1150         raise Exception("AP Civic Location ANQP-element not seen")
1151     if bss['anqp[266]'] != civic_loc:
1152         raise Exception("Unexpected AP Civic Location ANQP-element value: " + bss['anqp[266]'])
1153
1154     dev[1].scan_for_bss(bssid, freq="2412", force_scan=True)
1155     if "OK" not in dev[1].request("ANQP_GET " + bssid + " 257,258,259,260,261,262,263,264,265,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299"):
1156         raise Exception("ANQP_GET command failed")
1157
1158     ev = dev[1].wait_event(["GAS-QUERY-DONE"], timeout=10)
1159     if ev is None:
1160         raise Exception("GAS query timed out")
1161
1162     bss = dev[1].get_bss(bssid)
1163
1164     if 'anqp[265]' not in bss:
1165         raise Exception("AP Geospatial Location ANQP-element not seen")
1166     if bss['anqp[265]'] != geo_loc:
1167         raise Exception("Unexpected AP Geospatial Location ANQP-element value: " + bss['anqp[265]'])
1168
1169     if 'anqp[266]' in bss:
1170         raise Exception("AP Civic Location ANQP-element unexpectedly seen")
1171
1172     if 'anqp[267]' not in bss:
1173         raise Exception("AP Location Public Identifier ANQP-element not seen")
1174     if bss['anqp[267]'] != public_id:
1175         raise Exception("Unexpected AP Location Public Identifier ANQP-element value: " + bss['anqp[267]'])
1176
1177     if 'anqp[275]' not in bss:
1178         raise Exception("ANQP-element Info ID 275 not seen")
1179     if bss['anqp[275]'] != "01020304":
1180         raise Exception("Unexpected AP ANQP-element Info ID 299 value: " + bss['anqp[299]'])
1181
1182     if 'anqp[299]' not in bss:
1183         raise Exception("ANQP-element Info ID 299 not seen")
1184     if bss['anqp[299]'] != "0102":
1185         raise Exception("Unexpected AP ANQP-element Info ID 299 value: " + bss['anqp[299]'])
1186
1187     if 'anqp_ip_addr_type_availability' not in bss:
1188         raise Exception("ANQP-element Info ID 292 not seen")
1189     if bss['anqp_ip_addr_type_availability'] != "1122334455":
1190         raise Exception("Unexpected AP ANQP-element Info ID 262 value: " + bss['anqp_ip_addr_type_availability'])
1191
1192 def test_gas_anqp_address3_not_assoc(dev, apdev, params):
1193     """GAS/ANQP query using IEEE 802.11 compliant Address 3 value when not associated"""
1194     try:
1195         _test_gas_anqp_address3_not_assoc(dev, apdev, params)
1196     finally:
1197         dev[0].request("SET gas_address3 0")
1198
1199 def _test_gas_anqp_address3_not_assoc(dev, apdev, params):
1200     hapd = start_ap(apdev[0])
1201     bssid = apdev[0]['bssid']
1202
1203     if "OK" not in dev[0].request("SET gas_address3 1"):
1204         raise Exception("Failed to set gas_address3")
1205
1206     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
1207     if "OK" not in dev[0].request("ANQP_GET " + bssid + " 258"):
1208         raise Exception("ANQP_GET command failed")
1209
1210     ev = dev[0].wait_event(["GAS-QUERY-START"], timeout=5)
1211     if ev is None:
1212         raise Exception("GAS query start timed out")
1213
1214     ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=10)
1215     if ev is None:
1216         raise Exception("GAS query timed out")
1217
1218     ev = dev[0].wait_event(["RX-ANQP"], timeout=1)
1219     if ev is None or "Venue Name" not in ev:
1220         raise Exception("Did not receive Venue Name")
1221
1222     ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=10)
1223     if ev is None:
1224         raise Exception("ANQP-QUERY-DONE event not seen")
1225     if "result=SUCCESS" not in ev:
1226         raise Exception("Unexpected result: " + ev)
1227
1228     out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
1229                      "wlan_mgt.fixed.category_code == 4 && (wlan_mgt.fixed.publicact == 0x0a || wlan_mgt.fixed.publicact == 0x0b)",
1230                      display=["wlan.bssid"])
1231     res = out.splitlines()
1232     if len(res) != 2:
1233         raise Exception("Unexpected number of GAS frames")
1234     if res[0] != 'ff:ff:ff:ff:ff:ff':
1235         raise Exception("GAS request used unexpected Address3 field value: " + res[0])
1236     if res[1] != 'ff:ff:ff:ff:ff:ff':
1237         raise Exception("GAS response used unexpected Address3 field value: " + res[1])
1238
1239 def test_gas_anqp_address3_assoc(dev, apdev, params):
1240     """GAS/ANQP query using IEEE 802.11 compliant Address 3 value when associated"""
1241     try:
1242         _test_gas_anqp_address3_assoc(dev, apdev, params)
1243     finally:
1244         dev[0].request("SET gas_address3 0")
1245
1246 def _test_gas_anqp_address3_assoc(dev, apdev, params):
1247     hapd = start_ap(apdev[0])
1248     bssid = apdev[0]['bssid']
1249
1250     if "OK" not in dev[0].request("SET gas_address3 1"):
1251         raise Exception("Failed to set gas_address3")
1252
1253     dev[0].scan_for_bss(bssid, freq="2412")
1254     dev[0].connect("test-gas", key_mgmt="WPA-EAP", eap="TTLS",
1255                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1256                    password="password", phase2="auth=MSCHAPV2",
1257                    ca_cert="auth_serv/ca.pem", scan_freq="2412")
1258
1259     if "OK" not in dev[0].request("ANQP_GET " + bssid + " 258"):
1260         raise Exception("ANQP_GET command failed")
1261
1262     ev = dev[0].wait_event(["GAS-QUERY-START"], timeout=5)
1263     if ev is None:
1264         raise Exception("GAS query start timed out")
1265
1266     ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=10)
1267     if ev is None:
1268         raise Exception("GAS query timed out")
1269
1270     ev = dev[0].wait_event(["RX-ANQP"], timeout=1)
1271     if ev is None or "Venue Name" not in ev:
1272         raise Exception("Did not receive Venue Name")
1273
1274     ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=10)
1275     if ev is None:
1276         raise Exception("ANQP-QUERY-DONE event not seen")
1277     if "result=SUCCESS" not in ev:
1278         raise Exception("Unexpected result: " + ev)
1279
1280     out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
1281                      "wlan_mgt.fixed.category_code == 4 && (wlan_mgt.fixed.publicact == 0x0a || wlan_mgt.fixed.publicact == 0x0b)",
1282                      display=["wlan.bssid"])
1283     res = out.splitlines()
1284     if len(res) != 2:
1285         raise Exception("Unexpected number of GAS frames")
1286     if res[0] != bssid:
1287         raise Exception("GAS request used unexpected Address3 field value: " + res[0])
1288     if res[1] != bssid:
1289         raise Exception("GAS response used unexpected Address3 field value: " + res[1])
1290
1291 def test_gas_anqp_address3_ap_forced(dev, apdev, params):
1292     """GAS/ANQP query using IEEE 802.11 compliant Address 3 value on AP"""
1293     hapd = start_ap(apdev[0])
1294     bssid = apdev[0]['bssid']
1295     hapd.set("gas_address3", "1")
1296
1297     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
1298     if "OK" not in dev[0].request("ANQP_GET " + bssid + " 258"):
1299         raise Exception("ANQP_GET command failed")
1300
1301     ev = dev[0].wait_event(["GAS-QUERY-START"], timeout=5)
1302     if ev is None:
1303         raise Exception("GAS query start timed out")
1304
1305     ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=10)
1306     if ev is None:
1307         raise Exception("GAS query timed out")
1308
1309     ev = dev[0].wait_event(["RX-ANQP"], timeout=1)
1310     if ev is None or "Venue Name" not in ev:
1311         raise Exception("Did not receive Venue Name")
1312
1313     ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=10)
1314     if ev is None:
1315         raise Exception("ANQP-QUERY-DONE event not seen")
1316     if "result=SUCCESS" not in ev:
1317         raise Exception("Unexpected result: " + ev)
1318
1319     out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
1320                      "wlan_mgt.fixed.category_code == 4 && (wlan_mgt.fixed.publicact == 0x0a || wlan_mgt.fixed.publicact == 0x0b)",
1321                      display=["wlan.bssid"])
1322     res = out.splitlines()
1323     if len(res) != 2:
1324         raise Exception("Unexpected number of GAS frames")
1325     if res[0] != bssid:
1326         raise Exception("GAS request used unexpected Address3 field value: " + res[0])
1327     if res[1] != 'ff:ff:ff:ff:ff:ff':
1328         raise Exception("GAS response used unexpected Address3 field value: " + res[1])
1329
1330 def test_gas_anqp_address3_ap_non_compliant(dev, apdev, params):
1331     """GAS/ANQP query using IEEE 802.11 non-compliant Address 3 (AP)"""
1332     try:
1333         _test_gas_anqp_address3_ap_non_compliant(dev, apdev, params)
1334     finally:
1335         dev[0].request("SET gas_address3 0")
1336
1337 def _test_gas_anqp_address3_ap_non_compliant(dev, apdev, params):
1338     hapd = start_ap(apdev[0])
1339     bssid = apdev[0]['bssid']
1340     hapd.set("gas_address3", "2")
1341
1342     if "OK" not in dev[0].request("SET gas_address3 1"):
1343         raise Exception("Failed to set gas_address3")
1344
1345     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
1346     if "OK" not in dev[0].request("ANQP_GET " + bssid + " 258"):
1347         raise Exception("ANQP_GET command failed")
1348
1349     ev = dev[0].wait_event(["GAS-QUERY-START"], timeout=5)
1350     if ev is None:
1351         raise Exception("GAS query start timed out")
1352
1353     ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=10)
1354     if ev is None:
1355         raise Exception("GAS query timed out")
1356
1357     ev = dev[0].wait_event(["RX-ANQP"], timeout=1)
1358     if ev is None or "Venue Name" not in ev:
1359         raise Exception("Did not receive Venue Name")
1360
1361     ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=10)
1362     if ev is None:
1363         raise Exception("ANQP-QUERY-DONE event not seen")
1364     if "result=SUCCESS" not in ev:
1365         raise Exception("Unexpected result: " + ev)
1366
1367     out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
1368                      "wlan_mgt.fixed.category_code == 4 && (wlan_mgt.fixed.publicact == 0x0a || wlan_mgt.fixed.publicact == 0x0b)",
1369                      display=["wlan.bssid"])
1370     res = out.splitlines()
1371     if len(res) != 2:
1372         raise Exception("Unexpected number of GAS frames")
1373     if res[0] != 'ff:ff:ff:ff:ff:ff':
1374         raise Exception("GAS request used unexpected Address3 field value: " + res[0])
1375     if res[1] != bssid:
1376         raise Exception("GAS response used unexpected Address3 field value: " + res[1])
1377
1378 def test_gas_prot_vs_not_prot(dev, apdev, params):
1379     """GAS/ANQP query protected vs. not protected"""
1380     hapd = start_ap(apdev[0])
1381     bssid = apdev[0]['bssid']
1382
1383     dev[0].scan_for_bss(bssid, freq="2412")
1384     dev[0].connect("test-gas", key_mgmt="WPA-EAP", eap="TTLS",
1385                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1386                    password="password", phase2="auth=MSCHAPV2",
1387                    ca_cert="auth_serv/ca.pem", scan_freq="2412",
1388                    ieee80211w="2")
1389
1390     if "OK" not in dev[0].request("ANQP_GET " + bssid + " 258"):
1391         raise Exception("ANQP_GET command failed")
1392
1393     ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=5)
1394     if ev is None:
1395         raise Exception("No GAS-QUERY-DONE event")
1396     if "result=SUCCESS" not in ev:
1397         raise Exception("Unexpected GAS result: " + ev)
1398
1399     # GAS: Drop unexpected unprotected GAS frame when PMF is enabled
1400     dev[0].request("SET ext_mgmt_frame_handling 1")
1401     res = dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=d0003a010200000000000200000003000200000003001000040b00000005006c027f000000")
1402     dev[0].request("SET ext_mgmt_frame_handling 0")
1403     if "OK" not in res:
1404         raise Exception("MGMT_RX_PROCESS failed")
1405
1406     dev[0].request("DISCONNECT")
1407     dev[0].wait_disconnected()
1408
1409     # GAS: No pending query found for 02:00:00:00:03:00 dialog token 0
1410     dev[0].request("SET ext_mgmt_frame_handling 1")
1411     res = dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=d0003a010200000000000200000003000200000003001000040b00000005006c027f000000")
1412     dev[0].request("SET ext_mgmt_frame_handling 0")
1413     if "OK" not in res:
1414         raise Exception("MGMT_RX_PROCESS failed")
1415
1416     # GAS: Drop unexpected protected GAS frame when PMF is disabled
1417     dev[0].request("SET ext_mgmt_frame_handling 1")
1418     res = dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=d0003a010200000000000200000003000200000003001000090b00000005006c027f000000")
1419     dev[0].request("SET ext_mgmt_frame_handling 0")
1420     if "OK" not in res:
1421         raise Exception("MGMT_RX_PROCESS failed")
1422
1423 def test_gas_failures(dev, apdev):
1424     """GAS failure cases"""
1425     hapd = start_ap(apdev[0])
1426     hapd.set("gas_comeback_delay", "5")
1427     bssid = apdev[0]['bssid']
1428
1429     hapd2 = start_ap(apdev[1])
1430     bssid2 = apdev[1]['bssid']
1431
1432     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
1433     dev[0].scan_for_bss(bssid2, freq="2412")
1434
1435     tests = [ (bssid, "gas_build_req;gas_query_tx_comeback_req"),
1436               (bssid, "gas_query_tx;gas_query_tx_comeback_req"),
1437               (bssid, "gas_query_append;gas_query_rx_comeback"),
1438               (bssid2, "gas_query_append;gas_query_rx_initial"),
1439               (bssid2, "wpabuf_alloc_copy;gas_query_rx_initial"),
1440               (bssid, "gas_query_tx;gas_query_tx_initial_req") ]
1441     for addr,func in tests:
1442         with alloc_fail(dev[0], 1, func):
1443             dev[0].request("ANQP_GET " + addr + " 258")
1444             ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=5)
1445             if ev is None:
1446                 raise Exception("No GAS-QUERY-DONE seen")
1447             if "result=INTERNAL_ERROR" not in ev:
1448                 raise Exception("Unexpected result code: " + ev)
1449         dev[0].dump_monitor()
1450
1451     tests = [ "=gas_query_req", "radio_add_work;gas_query_req" ]
1452     for func in tests:
1453         with alloc_fail(dev[0], 1, func):
1454             if "FAIL" not in dev[0].request("ANQP_GET " + bssid + " 258"):
1455                 raise Exception("ANQP_GET succeeded unexpectedly during OOM")
1456         dev[0].dump_monitor()
1457
1458     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
1459     wpas.interface_add("wlan5")
1460     wpas.scan_for_bss(bssid2, freq="2412")
1461     wpas.request("SET preassoc_mac_addr 1111")
1462     wpas.request("ANQP_GET " + bssid2 + " 258")
1463     ev = wpas.wait_event(["Failed to assign random MAC address for GAS"],
1464                          timeout=5)
1465     wpas.request("SET preassoc_mac_addr 0")
1466     if ev is None:
1467         raise Exception("No random MAC address error seen")