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