tests: Truncated GAS query request
[mech_eap.git] / tests / hwsim / test_gas.py
1 # GAS tests
2 # Copyright (c) 2013, Qualcomm Atheros, Inc.
3 # Copyright (c) 2013-2014, 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 import time
9 import binascii
10 import logging
11 logger = logging.getLogger()
12 import re
13 import struct
14
15 import hostapd
16 from wpasupplicant import WpaSupplicant
17
18 def hs20_ap_params():
19     params = hostapd.wpa2_params(ssid="test-gas")
20     params['wpa_key_mgmt'] = "WPA-EAP"
21     params['ieee80211w'] = "1"
22     params['ieee8021x'] = "1"
23     params['auth_server_addr'] = "127.0.0.1"
24     params['auth_server_port'] = "1812"
25     params['auth_server_shared_secret'] = "radius"
26     params['interworking'] = "1"
27     params['access_network_type'] = "14"
28     params['internet'] = "1"
29     params['asra'] = "0"
30     params['esr'] = "0"
31     params['uesa'] = "0"
32     params['venue_group'] = "7"
33     params['venue_type'] = "1"
34     params['venue_name'] = [ "eng:Example venue", "fin:Esimerkkipaikka" ]
35     params['roaming_consortium'] = [ "112233", "1020304050", "010203040506",
36                                      "fedcba" ]
37     params['domain_name'] = "example.com,another.example.com"
38     params['nai_realm'] = [ "0,example.com,13[5:6],21[2:4][5:7]",
39                             "0,another.example.com" ]
40     params['anqp_3gpp_cell_net'] = "244,91"
41     params['network_auth_type'] = "02http://www.example.com/redirect/me/here/"
42     params['ipaddr_type_availability'] = "14"
43     params['hs20'] = "1"
44     params['hs20_oper_friendly_name'] = [ "eng:Example operator", "fin:Esimerkkioperaattori" ]
45     params['hs20_wan_metrics'] = "01:8000:1000:80:240:3000"
46     params['hs20_conn_capab'] = [ "1:0:2", "6:22:1", "17:5060:0" ]
47     params['hs20_operating_class'] = "5173"
48     return params
49
50 def start_ap(ap):
51     params = hs20_ap_params()
52     params['hessid'] = ap['bssid']
53     hostapd.add_ap(ap['ifname'], params)
54     return hostapd.Hostapd(ap['ifname'])
55
56 def get_gas_response(dev, bssid, info, allow_fetch_failure=False):
57     exp = r'<.>(GAS-RESPONSE-INFO) addr=([0-9a-f:]*) dialog_token=([0-9]*) status_code=([0-9]*) resp_len=([\-0-9]*)'
58     res = re.split(exp, info)
59     if len(res) < 6:
60         raise Exception("Could not parse GAS-RESPONSE-INFO")
61     if res[2] != bssid:
62         raise Exception("Unexpected BSSID in response")
63     token = res[3]
64     status = res[4]
65     if status != "0":
66         raise Exception("GAS query failed")
67     resp_len = res[5]
68     if resp_len == "-1":
69         raise Exception("GAS query reported invalid response length")
70     if int(resp_len) > 2000:
71         raise Exception("Unexpected long GAS response")
72
73     resp = dev.request("GAS_RESPONSE_GET " + bssid + " " + token)
74     if "FAIL" in resp:
75         if allow_fetch_failure:
76             logger.debug("GAS response was not available anymore")
77             return
78         raise Exception("Could not fetch GAS response")
79     if len(resp) != int(resp_len) * 2:
80         raise Exception("Unexpected GAS response length")
81     logger.debug("GAS response: " + resp)
82
83 def test_gas_generic(dev, apdev):
84     """Generic GAS query"""
85     bssid = apdev[0]['bssid']
86     params = hs20_ap_params()
87     params['hessid'] = bssid
88     hostapd.add_ap(apdev[0]['ifname'], params)
89
90     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
91     req = dev[0].request("GAS_REQUEST " + bssid + " 00 000102000101")
92     if "FAIL" in req:
93         raise Exception("GAS query request rejected")
94     ev = dev[0].wait_event(["GAS-RESPONSE-INFO"], timeout=10)
95     if ev is None:
96         raise Exception("GAS query timed out")
97     get_gas_response(dev[0], bssid, ev)
98
99 def test_gas_concurrent_scan(dev, apdev):
100     """Generic GAS queries with concurrent scan operation"""
101     bssid = apdev[0]['bssid']
102     params = hs20_ap_params()
103     params['hessid'] = bssid
104     hostapd.add_ap(apdev[0]['ifname'], params)
105
106     # get BSS entry available to allow GAS query
107     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
108
109     logger.info("Request concurrent operations")
110     req = dev[0].request("GAS_REQUEST " + bssid + " 00 000102000101")
111     if "FAIL" in req:
112         raise Exception("GAS query request rejected")
113     req = dev[0].request("GAS_REQUEST " + bssid + " 00 000102000801")
114     if "FAIL" in req:
115         raise Exception("GAS query request rejected")
116     dev[0].scan(no_wait=True)
117     req = dev[0].request("GAS_REQUEST " + bssid + " 00 000102000201")
118     if "FAIL" in req:
119         raise Exception("GAS query request rejected")
120     req = dev[0].request("GAS_REQUEST " + bssid + " 00 000102000501")
121     if "FAIL" in req:
122         raise Exception("GAS query request rejected")
123
124     responses = 0
125     for i in range(0, 5):
126         ev = dev[0].wait_event(["GAS-RESPONSE-INFO", "CTRL-EVENT-SCAN-RESULTS"],
127                                timeout=10)
128         if ev is None:
129             raise Exception("Operation timed out")
130         if "GAS-RESPONSE-INFO" in ev:
131             responses = responses + 1
132             get_gas_response(dev[0], bssid, ev, allow_fetch_failure=True)
133
134     if responses != 4:
135         raise Exception("Unexpected number of GAS responses")
136
137 def test_gas_concurrent_connect(dev, apdev):
138     """Generic GAS queries with concurrent connection operation"""
139     bssid = apdev[0]['bssid']
140     params = hs20_ap_params()
141     params['hessid'] = bssid
142     hostapd.add_ap(apdev[0]['ifname'], params)
143
144     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
145
146     logger.debug("Start concurrent connect and GAS request")
147     dev[0].connect("test-gas", key_mgmt="WPA-EAP", eap="TTLS",
148                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
149                    password="password", phase2="auth=MSCHAPV2",
150                    ca_cert="auth_serv/ca.pem", wait_connect=False,
151                    scan_freq="2412")
152     req = dev[0].request("GAS_REQUEST " + bssid + " 00 000102000101")
153     if "FAIL" in req:
154         raise Exception("GAS query request rejected")
155
156     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED", "GAS-RESPONSE-INFO"],
157                            timeout=20)
158     if ev is None:
159         raise Exception("Operation timed out")
160     if "CTRL-EVENT-CONNECTED" not in ev:
161         raise Exception("Unexpected operation order")
162
163     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED", "GAS-RESPONSE-INFO"],
164                            timeout=20)
165     if ev is None:
166         raise Exception("Operation timed out")
167     if "GAS-RESPONSE-INFO" not in ev:
168         raise Exception("Unexpected operation order")
169     get_gas_response(dev[0], bssid, ev)
170
171     dev[0].request("DISCONNECT")
172     ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=5)
173     if ev is None:
174         raise Exception("Disconnection timed out")
175
176     logger.debug("Wait six seconds for expiration of connect-without-scan")
177     time.sleep(6)
178     dev[0].dump_monitor()
179
180     logger.debug("Start concurrent GAS request and connect")
181     req = dev[0].request("GAS_REQUEST " + bssid + " 00 000102000101")
182     if "FAIL" in req:
183         raise Exception("GAS query request rejected")
184     dev[0].request("RECONNECT")
185
186     ev = dev[0].wait_event(["GAS-RESPONSE-INFO"], timeout=10)
187     if ev is None:
188         raise Exception("Operation timed out")
189     get_gas_response(dev[0], bssid, ev)
190
191     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=20)
192     if ev is None:
193         raise Exception("No new scan results reported")
194
195     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=20)
196     if ev is None:
197         raise Exception("Operation timed out")
198     if "CTRL-EVENT-CONNECTED" not in ev:
199         raise Exception("Unexpected operation order")
200
201 def test_gas_fragment(dev, apdev):
202     """GAS fragmentation"""
203     hapd = start_ap(apdev[0])
204     hapd.set("gas_frag_limit", "50")
205
206     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
207     dev[0].request("FETCH_ANQP")
208     for i in range(0, 13):
209         ev = dev[0].wait_event(["RX-ANQP", "RX-HS20-ANQP"], timeout=5)
210         if ev is None:
211             raise Exception("Operation timed out")
212
213 def test_gas_comeback_delay(dev, apdev):
214     """GAS fragmentation"""
215     hapd = start_ap(apdev[0])
216     hapd.set("gas_comeback_delay", "500")
217
218     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
219     dev[0].request("FETCH_ANQP")
220     for i in range(0, 6):
221         ev = dev[0].wait_event(["RX-ANQP"], timeout=5)
222         if ev is None:
223             raise Exception("Operation timed out")
224
225 def test_gas_anqp_get(dev, apdev):
226     """GAS/ANQP query for both IEEE 802.11 and Hotspot 2.0 elements"""
227     hapd = start_ap(apdev[0])
228     bssid = apdev[0]['bssid']
229
230     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
231     if "OK" not in dev[0].request("ANQP_GET " + bssid + " 258,268,hs20:3,hs20:4"):
232         raise Exception("ANQP_GET command failed")
233
234     ev = dev[0].wait_event(["GAS-QUERY-START"], timeout=5)
235     if ev is None:
236         raise Exception("GAS query start timed out")
237
238     ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=10)
239     if ev is None:
240         raise Exception("GAS query timed out")
241
242     ev = dev[0].wait_event(["RX-ANQP"], timeout=1)
243     if ev is None or "Venue Name" not in ev:
244         raise Exception("Did not receive Venue Name")
245
246     ev = dev[0].wait_event(["RX-ANQP"], timeout=1)
247     if ev is None or "Domain Name list" not in ev:
248         raise Exception("Did not receive Domain Name list")
249
250     ev = dev[0].wait_event(["RX-HS20-ANQP"], timeout=1)
251     if ev is None or "Operator Friendly Name" not in ev:
252         raise Exception("Did not receive Operator Friendly Name")
253
254     ev = dev[0].wait_event(["RX-HS20-ANQP"], timeout=1)
255     if ev is None or "WAN Metrics" not in ev:
256         raise Exception("Did not receive WAN Metrics")
257
258     if "OK" not in dev[0].request("HS20_ANQP_GET " + bssid + " 3,4"):
259         raise Exception("ANQP_GET command failed")
260
261     ev = dev[0].wait_event(["RX-HS20-ANQP"], timeout=1)
262     if ev is None or "Operator Friendly Name" not in ev:
263         raise Exception("Did not receive Operator Friendly Name")
264
265     ev = dev[0].wait_event(["RX-HS20-ANQP"], timeout=1)
266     if ev is None or "WAN Metrics" not in ev:
267         raise Exception("Did not receive WAN Metrics")
268
269 def expect_gas_result(dev, result, status=None):
270     ev = dev.wait_event(["GAS-QUERY-DONE"], timeout=10)
271     if ev is None:
272         raise Exception("GAS query timed out")
273     if "result=" + result not in ev:
274         raise Exception("Unexpected GAS query result")
275     if status and "status_code=" + str(status) + ' ' not in ev:
276         raise Exception("Unexpected GAS status code")
277
278 def anqp_get(dev, bssid, id):
279     if "OK" not in dev.request("ANQP_GET " + bssid + " " + str(id)):
280         raise Exception("ANQP_GET command failed")
281     ev = dev.wait_event(["GAS-QUERY-START"], timeout=5)
282     if ev is None:
283         raise Exception("GAS query start timed out")
284
285 def test_gas_timeout(dev, apdev):
286     """GAS timeout"""
287     hapd = start_ap(apdev[0])
288     bssid = apdev[0]['bssid']
289
290     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
291     hapd.set("ext_mgmt_frame_handling", "1")
292
293     anqp_get(dev[0], bssid, 263)
294
295     ev = hapd.wait_event(["MGMT-RX"], timeout=5)
296     if ev is None:
297         raise Exception("MGMT RX wait timed out")
298
299     expect_gas_result(dev[0], "TIMEOUT")
300
301 MGMT_SUBTYPE_ACTION = 13
302 ACTION_CATEG_PUBLIC = 4
303
304 GAS_INITIAL_REQUEST = 10
305 GAS_INITIAL_RESPONSE = 11
306 GAS_COMEBACK_REQUEST = 12
307 GAS_COMEBACK_RESPONSE = 13
308 GAS_ACTIONS = [ GAS_INITIAL_REQUEST, GAS_INITIAL_RESPONSE,
309                 GAS_COMEBACK_REQUEST, GAS_COMEBACK_RESPONSE ]
310
311 def anqp_adv_proto():
312     return struct.pack('BBBB', 108, 2, 127, 0)
313
314 def anqp_initial_resp(dialog_token, status_code, comeback_delay=0):
315     return struct.pack('<BBBHH', ACTION_CATEG_PUBLIC, GAS_INITIAL_RESPONSE,
316                        dialog_token, status_code, comeback_delay) + anqp_adv_proto()
317
318 def anqp_comeback_resp(dialog_token, status_code=0, id=0, more=False, comeback_delay=0, bogus_adv_proto=False):
319     if more:
320         id |= 0x80
321     if bogus_adv_proto:
322         adv = struct.pack('BBBB', 108, 2, 127, 1)
323     else:
324         adv = anqp_adv_proto()
325     return struct.pack('<BBBHBH', ACTION_CATEG_PUBLIC, GAS_COMEBACK_RESPONSE,
326                        dialog_token, status_code, id, comeback_delay) + adv
327
328 def gas_rx(hapd):
329     count = 0
330     while count < 30:
331         count = count + 1
332         query = hapd.mgmt_rx()
333         if query is None:
334             raise Exception("Action frame not received")
335         if query['subtype'] != MGMT_SUBTYPE_ACTION:
336             continue
337         payload = query['payload']
338         if len(payload) < 2:
339             continue
340         (category, action) = struct.unpack('BB', payload[0:2])
341         if category != ACTION_CATEG_PUBLIC or action not in GAS_ACTIONS:
342             continue
343         return query
344     raise Exception("No Action frame received")
345
346 def parse_gas(payload):
347     pos = payload
348     (category, action, dialog_token) = struct.unpack('BBB', pos[0:3])
349     if category != ACTION_CATEG_PUBLIC:
350         return None
351     if action not in GAS_ACTIONS:
352         return None
353     gas = {}
354     gas['action'] = action
355     pos = pos[3:]
356
357     if len(pos) < 1 and action != GAS_COMEBACK_REQUEST:
358         return None
359
360     gas['dialog_token'] = dialog_token
361
362     if action == GAS_INITIAL_RESPONSE:
363         if len(pos) < 4:
364             return None
365         (status_code, comeback_delay) = struct.unpack('<HH', pos[0:4])
366         gas['status_code'] = status_code
367         gas['comeback_delay'] = comeback_delay
368
369     if action == GAS_COMEBACK_RESPONSE:
370         if len(pos) < 5:
371             return None
372         (status_code, frag, comeback_delay) = struct.unpack('<HBH', pos[0:5])
373         gas['status_code'] = status_code
374         gas['frag'] = frag
375         gas['comeback_delay'] = comeback_delay
376
377     return gas
378
379 def action_response(req):
380     resp = {}
381     resp['fc'] = req['fc']
382     resp['da'] = req['sa']
383     resp['sa'] = req['da']
384     resp['bssid'] = req['bssid']
385     return resp
386
387 def send_gas_resp(hapd, resp):
388     hapd.mgmt_tx(resp)
389     ev = hapd.wait_event(["MGMT-TX-STATUS"], timeout=5)
390     if ev is None:
391         raise Exception("Missing TX status for GAS response")
392     if "ok=1" not in ev:
393         raise Exception("GAS response not acknowledged")
394
395 def test_gas_invalid_response_type(dev, apdev):
396     """GAS invalid response type"""
397     hapd = start_ap(apdev[0])
398     bssid = apdev[0]['bssid']
399
400     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
401     hapd.set("ext_mgmt_frame_handling", "1")
402
403     anqp_get(dev[0], bssid, 263)
404
405     query = gas_rx(hapd)
406     gas = parse_gas(query['payload'])
407
408     resp = action_response(query)
409     # GAS Comeback Response instead of GAS Initial Response
410     resp['payload'] = anqp_comeback_resp(gas['dialog_token']) + struct.pack('<H', 0)
411     send_gas_resp(hapd, resp)
412
413     # station drops the invalid frame, so this needs to result in GAS timeout
414     expect_gas_result(dev[0], "TIMEOUT")
415
416 def test_gas_failure_status_code(dev, apdev):
417     """GAS failure status code"""
418     hapd = start_ap(apdev[0])
419     bssid = apdev[0]['bssid']
420
421     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
422     hapd.set("ext_mgmt_frame_handling", "1")
423
424     anqp_get(dev[0], bssid, 263)
425
426     query = gas_rx(hapd)
427     gas = parse_gas(query['payload'])
428
429     resp = action_response(query)
430     resp['payload'] = anqp_initial_resp(gas['dialog_token'], 61) + struct.pack('<H', 0)
431     send_gas_resp(hapd, resp)
432
433     expect_gas_result(dev[0], "FAILURE")
434
435 def test_gas_malformed(dev, apdev):
436     """GAS malformed response frames"""
437     hapd = start_ap(apdev[0])
438     bssid = apdev[0]['bssid']
439
440     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
441     hapd.set("ext_mgmt_frame_handling", "1")
442
443     anqp_get(dev[0], bssid, 263)
444
445     query = gas_rx(hapd)
446     gas = parse_gas(query['payload'])
447
448     resp = action_response(query)
449
450     resp['payload'] = struct.pack('<BBBH', ACTION_CATEG_PUBLIC,
451                                   GAS_COMEBACK_RESPONSE,
452                                   gas['dialog_token'], 0)
453     hapd.mgmt_tx(resp)
454
455     resp['payload'] = struct.pack('<BBBHB', ACTION_CATEG_PUBLIC,
456                                   GAS_COMEBACK_RESPONSE,
457                                   gas['dialog_token'], 0, 0)
458     hapd.mgmt_tx(resp)
459
460     hdr = struct.pack('<BBBHH', ACTION_CATEG_PUBLIC, GAS_INITIAL_RESPONSE,
461                       gas['dialog_token'], 0, 0)
462     resp['payload'] = hdr + struct.pack('B', 108)
463     hapd.mgmt_tx(resp)
464     resp['payload'] = hdr + struct.pack('BB', 108, 0)
465     hapd.mgmt_tx(resp)
466     resp['payload'] = hdr + struct.pack('BB', 108, 1)
467     hapd.mgmt_tx(resp)
468     resp['payload'] = hdr + struct.pack('BB', 108, 255)
469     hapd.mgmt_tx(resp)
470     resp['payload'] = hdr + struct.pack('BBB', 108, 1, 127)
471     hapd.mgmt_tx(resp)
472     resp['payload'] = hdr + struct.pack('BBB', 108, 2, 127)
473     hapd.mgmt_tx(resp)
474     resp['payload'] = hdr + struct.pack('BBBB', 0, 2, 127, 0)
475     hapd.mgmt_tx(resp)
476
477     resp['payload'] = anqp_initial_resp(gas['dialog_token'], 0) + struct.pack('<H', 1)
478     hapd.mgmt_tx(resp)
479
480     resp['payload'] = anqp_initial_resp(gas['dialog_token'], 0) + struct.pack('<HB', 2, 0)
481     hapd.mgmt_tx(resp)
482
483     resp['payload'] = anqp_initial_resp(gas['dialog_token'], 0) + struct.pack('<H', 65535)
484     hapd.mgmt_tx(resp)
485
486     resp['payload'] = anqp_initial_resp(gas['dialog_token'], 0) + struct.pack('<HBB', 1, 0, 0)
487     hapd.mgmt_tx(resp)
488
489     # Station drops invalid frames, but the last of the responses is valid from
490     # GAS view point even though it has an extra octet in the end and the ANQP
491     # part of the response is not valid. This is reported as successfulyl
492     # completed GAS exchange.
493     expect_gas_result(dev[0], "SUCCESS")
494
495 def init_gas(hapd, bssid, dev):
496     anqp_get(dev, bssid, 263)
497     query = gas_rx(hapd)
498     gas = parse_gas(query['payload'])
499     dialog_token = gas['dialog_token']
500
501     resp = action_response(query)
502     resp['payload'] = anqp_initial_resp(dialog_token, 0, comeback_delay=1) + struct.pack('<H', 0)
503     send_gas_resp(hapd, resp)
504
505     query = gas_rx(hapd)
506     gas = parse_gas(query['payload'])
507     if gas['action'] != GAS_COMEBACK_REQUEST:
508         raise Exception("Unexpected request action")
509     if gas['dialog_token'] != dialog_token:
510         raise Exception("Unexpected dialog token change")
511     return query, dialog_token
512
513 def test_gas_malformed_comeback_resp(dev, apdev):
514     """GAS malformed comeback response frames"""
515     hapd = start_ap(apdev[0])
516     bssid = apdev[0]['bssid']
517
518     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
519     hapd.set("ext_mgmt_frame_handling", "1")
520
521     logger.debug("Non-zero status code in comeback response")
522     query, dialog_token = init_gas(hapd, bssid, dev[0])
523     resp = action_response(query)
524     resp['payload'] = anqp_comeback_resp(dialog_token, status_code=2) + struct.pack('<H', 0)
525     send_gas_resp(hapd, resp)
526     expect_gas_result(dev[0], "FAILURE", status=2)
527
528     logger.debug("Different advertisement protocol in comeback response")
529     query, dialog_token = init_gas(hapd, bssid, dev[0])
530     resp = action_response(query)
531     resp['payload'] = anqp_comeback_resp(dialog_token, bogus_adv_proto=True) + struct.pack('<H', 0)
532     send_gas_resp(hapd, resp)
533     expect_gas_result(dev[0], "PEER_ERROR")
534
535     logger.debug("Non-zero frag id and comeback delay in comeback response")
536     query, dialog_token = init_gas(hapd, bssid, dev[0])
537     resp = action_response(query)
538     resp['payload'] = anqp_comeback_resp(dialog_token, id=1, comeback_delay=1) + struct.pack('<H', 0)
539     send_gas_resp(hapd, resp)
540     expect_gas_result(dev[0], "PEER_ERROR")
541
542     logger.debug("Unexpected frag id in comeback response")
543     query, dialog_token = init_gas(hapd, bssid, dev[0])
544     resp = action_response(query)
545     resp['payload'] = anqp_comeback_resp(dialog_token, id=1) + struct.pack('<H', 0)
546     send_gas_resp(hapd, resp)
547     expect_gas_result(dev[0], "PEER_ERROR")
548
549     logger.debug("Empty fragment and replay in comeback response")
550     query, dialog_token = init_gas(hapd, bssid, dev[0])
551     resp = action_response(query)
552     resp['payload'] = anqp_comeback_resp(dialog_token, more=True) + struct.pack('<H', 0)
553     send_gas_resp(hapd, resp)
554     query = gas_rx(hapd)
555     gas = parse_gas(query['payload'])
556     if gas['action'] != GAS_COMEBACK_REQUEST:
557         raise Exception("Unexpected request action")
558     if gas['dialog_token'] != dialog_token:
559         raise Exception("Unexpected dialog token change")
560     resp = action_response(query)
561     resp['payload'] = anqp_comeback_resp(dialog_token) + struct.pack('<H', 0)
562     send_gas_resp(hapd, resp)
563     resp['payload'] = anqp_comeback_resp(dialog_token, id=1) + struct.pack('<H', 0)
564     send_gas_resp(hapd, resp)
565     expect_gas_result(dev[0], "SUCCESS")
566
567     logger.debug("Unexpected initial response when waiting for comeback response")
568     query, dialog_token = init_gas(hapd, bssid, dev[0])
569     resp = action_response(query)
570     resp['payload'] = anqp_initial_resp(dialog_token, 0) + struct.pack('<H', 0)
571     send_gas_resp(hapd, resp)
572     ev = hapd.wait_event(["MGMT-RX"], timeout=1)
573     if ev is not None:
574         raise Exception("Unexpected management frame")
575     expect_gas_result(dev[0], "TIMEOUT")
576
577     logger.debug("Too short comeback response")
578     query, dialog_token = init_gas(hapd, bssid, dev[0])
579     resp = action_response(query)
580     resp['payload'] = struct.pack('<BBBH', ACTION_CATEG_PUBLIC,
581                                   GAS_COMEBACK_RESPONSE, dialog_token, 0)
582     send_gas_resp(hapd, resp)
583     ev = hapd.wait_event(["MGMT-RX"], timeout=1)
584     if ev is not None:
585         raise Exception("Unexpected management frame")
586     expect_gas_result(dev[0], "TIMEOUT")
587
588     logger.debug("Too short comeback response(2)")
589     query, dialog_token = init_gas(hapd, bssid, dev[0])
590     resp = action_response(query)
591     resp['payload'] = struct.pack('<BBBHBB', ACTION_CATEG_PUBLIC,
592                                   GAS_COMEBACK_RESPONSE, dialog_token, 0, 0x80,
593                                   0)
594     send_gas_resp(hapd, resp)
595     ev = hapd.wait_event(["MGMT-RX"], timeout=1)
596     if ev is not None:
597         raise Exception("Unexpected management frame")
598     expect_gas_result(dev[0], "TIMEOUT")
599
600     logger.debug("Maximum comeback response fragment claiming more fragments")
601     query, dialog_token = init_gas(hapd, bssid, dev[0])
602     resp = action_response(query)
603     resp['payload'] = anqp_comeback_resp(dialog_token, more=True) + struct.pack('<H', 0)
604     send_gas_resp(hapd, resp)
605     for i in range(1, 129):
606         query = gas_rx(hapd)
607         gas = parse_gas(query['payload'])
608         if gas['action'] != GAS_COMEBACK_REQUEST:
609             raise Exception("Unexpected request action")
610         if gas['dialog_token'] != dialog_token:
611             raise Exception("Unexpected dialog token change")
612         resp = action_response(query)
613         resp['payload'] = anqp_comeback_resp(dialog_token, id=i, more=True) + struct.pack('<H', 0)
614         send_gas_resp(hapd, resp)
615     expect_gas_result(dev[0], "PEER_ERROR")
616
617 def test_gas_comeback_resp_additional_delay(dev, apdev):
618     """GAS comeback response requesting additional delay"""
619     hapd = start_ap(apdev[0])
620     bssid = apdev[0]['bssid']
621
622     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
623     hapd.set("ext_mgmt_frame_handling", "1")
624
625     query, dialog_token = init_gas(hapd, bssid, dev[0])
626     for i in range(0, 2):
627         resp = action_response(query)
628         resp['payload'] = anqp_comeback_resp(dialog_token, status_code=95, comeback_delay=50) + struct.pack('<H', 0)
629         send_gas_resp(hapd, resp)
630         query = gas_rx(hapd)
631         gas = parse_gas(query['payload'])
632         if gas['action'] != GAS_COMEBACK_REQUEST:
633             raise Exception("Unexpected request action")
634         if gas['dialog_token'] != dialog_token:
635             raise Exception("Unexpected dialog token change")
636     resp = action_response(query)
637     resp['payload'] = anqp_comeback_resp(dialog_token, status_code=0) + struct.pack('<H', 0)
638     send_gas_resp(hapd, resp)
639     expect_gas_result(dev[0], "SUCCESS")
640
641 def test_gas_unknown_adv_proto(dev, apdev):
642     """Unknown advertisement protocol id"""
643     bssid = apdev[0]['bssid']
644     params = hs20_ap_params()
645     params['hessid'] = bssid
646     hostapd.add_ap(apdev[0]['ifname'], params)
647
648     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
649     req = dev[0].request("GAS_REQUEST " + bssid + " 42 000102000101")
650     if "FAIL" in req:
651         raise Exception("GAS query request rejected")
652     expect_gas_result(dev[0], "FAILURE", "59")
653     ev = dev[0].wait_event(["GAS-RESPONSE-INFO"], timeout=10)
654     if ev is None:
655         raise Exception("GAS query timed out")
656     exp = r'<.>(GAS-RESPONSE-INFO) addr=([0-9a-f:]*) dialog_token=([0-9]*) status_code=([0-9]*) resp_len=([\-0-9]*)'
657     res = re.split(exp, ev)
658     if len(res) < 6:
659         raise Exception("Could not parse GAS-RESPONSE-INFO")
660     if res[2] != bssid:
661         raise Exception("Unexpected BSSID in response")
662     status = res[4]
663     if status != "59":
664         raise Exception("Unexpected GAS-RESPONSE-INFO status")
665
666 def test_gas_max_pending(dev, apdev):
667     """GAS and maximum pending query limit"""
668     hapd = start_ap(apdev[0])
669     hapd.set("gas_frag_limit", "50")
670     bssid = apdev[0]['bssid']
671
672     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
673     wpas.interface_add("wlan5")
674     if "OK" not in wpas.request("P2P_SET listen_channel 1"):
675         raise Exception("Failed to set listen channel")
676     if "OK" not in wpas.p2p_listen():
677         raise Exception("Failed to start listen state")
678     if "FAIL" in wpas.request("SET ext_mgmt_frame_handling 1"):
679         raise Exception("Failed to enable external management frame handling")
680
681     anqp_query = struct.pack('<HHHHHHHHHH', 256, 16, 257, 258, 260, 261, 262, 263, 264, 268)
682     gas = struct.pack('<H', len(anqp_query)) + anqp_query
683
684     for dialog_token in range(1, 10):
685         msg = struct.pack('<BBB', ACTION_CATEG_PUBLIC, GAS_INITIAL_REQUEST,
686                           dialog_token) + anqp_adv_proto() + gas
687         req = "MGMT_TX {} {} freq=2412 wait_time=10 action={}".format(bssid, bssid, binascii.hexlify(msg))
688         if "OK" not in wpas.request(req):
689             raise Exception("Could not send management frame")
690         resp = wpas.mgmt_rx()
691         if resp is None:
692             raise Exception("MGMT-RX timeout")
693         if 'payload' not in resp:
694             raise Exception("Missing payload")
695         gresp = parse_gas(resp['payload'])
696         if gresp['dialog_token'] != dialog_token:
697             raise Exception("Dialog token mismatch")
698         status_code = gresp['status_code']
699         if dialog_token < 9 and status_code != 0:
700             raise Exception("Unexpected failure status code {} for dialog token {}".format(status_code, dialog_token))
701         if dialog_token > 8 and status_code == 0:
702             raise Exception("Unexpected success status code {} for dialog token {}".format(status_code, dialog_token))
703
704 def test_gas_no_pending(dev, apdev):
705     """GAS and no pending query for comeback request"""
706     hapd = start_ap(apdev[0])
707     bssid = apdev[0]['bssid']
708
709     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
710     wpas.interface_add("wlan5")
711     if "OK" not in wpas.request("P2P_SET listen_channel 1"):
712         raise Exception("Failed to set listen channel")
713     if "OK" not in wpas.p2p_listen():
714         raise Exception("Failed to start listen state")
715     if "FAIL" in wpas.request("SET ext_mgmt_frame_handling 1"):
716         raise Exception("Failed to enable external management frame handling")
717
718     msg = struct.pack('<BBB', ACTION_CATEG_PUBLIC, GAS_COMEBACK_REQUEST, 1)
719     req = "MGMT_TX {} {} freq=2412 wait_time=10 action={}".format(bssid, bssid, binascii.hexlify(msg))
720     if "OK" not in wpas.request(req):
721         raise Exception("Could not send management frame")
722     resp = wpas.mgmt_rx()
723     if resp is None:
724         raise Exception("MGMT-RX timeout")
725     if 'payload' not in resp:
726         raise Exception("Missing payload")
727     gresp = parse_gas(resp['payload'])
728     status_code = gresp['status_code']
729     if status_code != 60:
730         raise Exception("Unexpected status code {} (expected 60)".format(status_code))
731
732 def test_gas_missing_payload(dev, apdev):
733     """No action code in the query frame"""
734     bssid = apdev[0]['bssid']
735     params = hs20_ap_params()
736     params['hessid'] = bssid
737     hostapd.add_ap(apdev[0]['ifname'], params)
738
739     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
740
741     cmd = "MGMT_TX {} {} freq=2412 action=040A".format(bssid, bssid)
742     if "FAIL" in dev[0].request(cmd):
743         raise Exception("Could not send test Action frame")
744     ev = dev[0].wait_event(["MGMT-TX-STATUS"], timeout=10)
745     if ev is None:
746         raise Exception("Timeout on MGMT-TX-STATUS")
747     if "result=SUCCESS" not in ev:
748         raise Exception("AP did not ack Action frame")
749
750     cmd = "MGMT_TX {} {} freq=2412 action=04".format(bssid, bssid)
751     if "FAIL" in dev[0].request(cmd):
752         raise Exception("Could not send test Action frame")
753     ev = dev[0].wait_event(["MGMT-TX-STATUS"], timeout=10)
754     if ev is None:
755         raise Exception("Timeout on MGMT-TX-STATUS")
756     if "result=SUCCESS" not in ev:
757         raise Exception("AP did not ack Action frame")