tests: Skip EAP-TTLS/CHAP, MSCHAP, MSCHAPV2 test cases in FIPS mode
[mech_eap.git] / 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 fragmentation"""
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     for i in range(0, 6):
267         ev = dev[0].wait_event(["RX-ANQP"], timeout=5)
268         if ev is None:
269             raise Exception("Operation timed out")
270
271 def test_gas_stop_fetch_anqp(dev, apdev):
272     """Stop FETCH_ANQP operation"""
273     hapd = start_ap(apdev[0])
274
275     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
276     hapd.set("ext_mgmt_frame_handling", "1")
277     dev[0].request("FETCH_ANQP")
278     dev[0].request("STOP_FETCH_ANQP")
279     hapd.set("ext_mgmt_frame_handling", "0")
280     ev = dev[0].wait_event(["RX-ANQP", "GAS-QUERY-DONE"], timeout=10)
281     if ev is None:
282         raise Exception("GAS-QUERY-DONE timed out")
283     if "RX-ANQP" in ev:
284         raise Exception("Unexpected ANQP response received")
285
286 def test_gas_anqp_get(dev, apdev):
287     """GAS/ANQP query for both IEEE 802.11 and Hotspot 2.0 elements"""
288     hapd = start_ap(apdev[0])
289     bssid = apdev[0]['bssid']
290
291     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
292     if "OK" not in dev[0].request("ANQP_GET " + bssid + " 258,268,hs20:3,hs20:4"):
293         raise Exception("ANQP_GET command failed")
294
295     ev = dev[0].wait_event(["GAS-QUERY-START"], timeout=5)
296     if ev is None:
297         raise Exception("GAS query start timed out")
298
299     ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=10)
300     if ev is None:
301         raise Exception("GAS query timed out")
302
303     ev = dev[0].wait_event(["RX-ANQP"], timeout=1)
304     if ev is None or "Venue Name" not in ev:
305         raise Exception("Did not receive Venue Name")
306
307     ev = dev[0].wait_event(["RX-ANQP"], timeout=1)
308     if ev is None or "Domain Name list" not in ev:
309         raise Exception("Did not receive Domain Name list")
310
311     ev = dev[0].wait_event(["RX-HS20-ANQP"], timeout=1)
312     if ev is None or "Operator Friendly Name" not in ev:
313         raise Exception("Did not receive Operator Friendly Name")
314
315     ev = dev[0].wait_event(["RX-HS20-ANQP"], timeout=1)
316     if ev is None or "WAN Metrics" not in ev:
317         raise Exception("Did not receive WAN Metrics")
318
319     ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=10)
320     if ev is None:
321         raise Exception("ANQP-QUERY-DONE event not seen")
322     if "result=SUCCESS" not in ev:
323         raise Exception("Unexpected result: " + ev)
324
325     if "OK" not in dev[0].request("HS20_ANQP_GET " + bssid + " 3,4"):
326         raise Exception("ANQP_GET command failed")
327
328     ev = dev[0].wait_event(["RX-HS20-ANQP"], timeout=1)
329     if ev is None or "Operator Friendly Name" not in ev:
330         raise Exception("Did not receive Operator Friendly Name")
331
332     ev = dev[0].wait_event(["RX-HS20-ANQP"], timeout=1)
333     if ev is None or "WAN Metrics" not in ev:
334         raise Exception("Did not receive WAN Metrics")
335
336     cmds = [ "",
337              "foo",
338              "00:11:22:33:44:55 258,hs20:-1",
339              "00:11:22:33:44:55 258,hs20:0",
340              "00:11:22:33:44:55 258,hs20:32",
341              "00:11:22:33:44:55 hs20:-1",
342              "00:11:22:33:44:55 hs20:0",
343              "00:11:22:33:44:55 hs20:32",
344              "00:11:22:33:44:55",
345              "00:11:22:33:44:55 ",
346              "00:11:22:33:44:55 0" ]
347     for cmd in cmds:
348         if "FAIL" not in dev[0].request("ANQP_GET " + cmd):
349             raise Exception("Invalid ANQP_GET accepted")
350
351     cmds = [ "",
352              "foo",
353              "00:11:22:33:44:55 -1",
354              "00:11:22:33:44:55 0",
355              "00:11:22:33:44:55 32",
356              "00:11:22:33:44:55",
357              "00:11:22:33:44:55 ",
358              "00:11:22:33:44:55 0" ]
359     for cmd in cmds:
360         if "FAIL" not in dev[0].request("HS20_ANQP_GET " + cmd):
361             raise Exception("Invalid HS20_ANQP_GET accepted")
362
363 def expect_gas_result(dev, result, status=None):
364     ev = dev.wait_event(["GAS-QUERY-DONE"], timeout=10)
365     if ev is None:
366         raise Exception("GAS query timed out")
367     if "result=" + result not in ev:
368         raise Exception("Unexpected GAS query result")
369     if status and "status_code=" + str(status) + ' ' not in ev:
370         raise Exception("Unexpected GAS status code")
371
372 def anqp_get(dev, bssid, id):
373     if "OK" not in dev.request("ANQP_GET " + bssid + " " + str(id)):
374         raise Exception("ANQP_GET command failed")
375     ev = dev.wait_event(["GAS-QUERY-START"], timeout=5)
376     if ev is None:
377         raise Exception("GAS query start timed out")
378
379 def test_gas_timeout(dev, apdev):
380     """GAS timeout"""
381     hapd = start_ap(apdev[0])
382     bssid = apdev[0]['bssid']
383
384     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
385     hapd.set("ext_mgmt_frame_handling", "1")
386
387     anqp_get(dev[0], bssid, 263)
388
389     ev = hapd.wait_event(["MGMT-RX"], timeout=5)
390     if ev is None:
391         raise Exception("MGMT RX wait timed out")
392
393     expect_gas_result(dev[0], "TIMEOUT")
394
395 MGMT_SUBTYPE_ACTION = 13
396 ACTION_CATEG_PUBLIC = 4
397
398 GAS_INITIAL_REQUEST = 10
399 GAS_INITIAL_RESPONSE = 11
400 GAS_COMEBACK_REQUEST = 12
401 GAS_COMEBACK_RESPONSE = 13
402 GAS_ACTIONS = [ GAS_INITIAL_REQUEST, GAS_INITIAL_RESPONSE,
403                 GAS_COMEBACK_REQUEST, GAS_COMEBACK_RESPONSE ]
404
405 def anqp_adv_proto():
406     return struct.pack('BBBB', 108, 2, 127, 0)
407
408 def anqp_initial_resp(dialog_token, status_code, comeback_delay=0):
409     return struct.pack('<BBBHH', ACTION_CATEG_PUBLIC, GAS_INITIAL_RESPONSE,
410                        dialog_token, status_code, comeback_delay) + anqp_adv_proto()
411
412 def anqp_comeback_resp(dialog_token, status_code=0, id=0, more=False, comeback_delay=0, bogus_adv_proto=False):
413     if more:
414         id |= 0x80
415     if bogus_adv_proto:
416         adv = struct.pack('BBBB', 108, 2, 127, 1)
417     else:
418         adv = anqp_adv_proto()
419     return struct.pack('<BBBHBH', ACTION_CATEG_PUBLIC, GAS_COMEBACK_RESPONSE,
420                        dialog_token, status_code, id, comeback_delay) + adv
421
422 def gas_rx(hapd):
423     count = 0
424     while count < 30:
425         count = count + 1
426         query = hapd.mgmt_rx()
427         if query is None:
428             raise Exception("Action frame not received")
429         if query['subtype'] != MGMT_SUBTYPE_ACTION:
430             continue
431         payload = query['payload']
432         if len(payload) < 2:
433             continue
434         (category, action) = struct.unpack('BB', payload[0:2])
435         if category != ACTION_CATEG_PUBLIC or action not in GAS_ACTIONS:
436             continue
437         return query
438     raise Exception("No Action frame received")
439
440 def parse_gas(payload):
441     pos = payload
442     (category, action, dialog_token) = struct.unpack('BBB', pos[0:3])
443     if category != ACTION_CATEG_PUBLIC:
444         return None
445     if action not in GAS_ACTIONS:
446         return None
447     gas = {}
448     gas['action'] = action
449     pos = pos[3:]
450
451     if len(pos) < 1 and action != GAS_COMEBACK_REQUEST:
452         return None
453
454     gas['dialog_token'] = dialog_token
455
456     if action == GAS_INITIAL_RESPONSE:
457         if len(pos) < 4:
458             return None
459         (status_code, comeback_delay) = struct.unpack('<HH', pos[0:4])
460         gas['status_code'] = status_code
461         gas['comeback_delay'] = comeback_delay
462
463     if action == GAS_COMEBACK_RESPONSE:
464         if len(pos) < 5:
465             return None
466         (status_code, frag, comeback_delay) = struct.unpack('<HBH', pos[0:5])
467         gas['status_code'] = status_code
468         gas['frag'] = frag
469         gas['comeback_delay'] = comeback_delay
470
471     return gas
472
473 def action_response(req):
474     resp = {}
475     resp['fc'] = req['fc']
476     resp['da'] = req['sa']
477     resp['sa'] = req['da']
478     resp['bssid'] = req['bssid']
479     return resp
480
481 def send_gas_resp(hapd, resp):
482     hapd.mgmt_tx(resp)
483     ev = hapd.wait_event(["MGMT-TX-STATUS"], timeout=5)
484     if ev is None:
485         raise Exception("Missing TX status for GAS response")
486     if "ok=1" not in ev:
487         raise Exception("GAS response not acknowledged")
488
489 def test_gas_invalid_response_type(dev, apdev):
490     """GAS invalid response type"""
491     hapd = start_ap(apdev[0])
492     bssid = apdev[0]['bssid']
493
494     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
495     hapd.set("ext_mgmt_frame_handling", "1")
496
497     anqp_get(dev[0], bssid, 263)
498
499     query = gas_rx(hapd)
500     gas = parse_gas(query['payload'])
501
502     resp = action_response(query)
503     # GAS Comeback Response instead of GAS Initial Response
504     resp['payload'] = anqp_comeback_resp(gas['dialog_token']) + struct.pack('<H', 0)
505     send_gas_resp(hapd, resp)
506
507     # station drops the invalid frame, so this needs to result in GAS timeout
508     expect_gas_result(dev[0], "TIMEOUT")
509
510 def test_gas_failure_status_code(dev, apdev):
511     """GAS failure status code"""
512     hapd = start_ap(apdev[0])
513     bssid = apdev[0]['bssid']
514
515     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
516     hapd.set("ext_mgmt_frame_handling", "1")
517
518     anqp_get(dev[0], bssid, 263)
519
520     query = gas_rx(hapd)
521     gas = parse_gas(query['payload'])
522
523     resp = action_response(query)
524     resp['payload'] = anqp_initial_resp(gas['dialog_token'], 61) + struct.pack('<H', 0)
525     send_gas_resp(hapd, resp)
526
527     expect_gas_result(dev[0], "FAILURE")
528
529 def test_gas_malformed(dev, apdev):
530     """GAS malformed response frames"""
531     hapd = start_ap(apdev[0])
532     bssid = apdev[0]['bssid']
533
534     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
535     hapd.set("ext_mgmt_frame_handling", "1")
536
537     anqp_get(dev[0], bssid, 263)
538
539     query = gas_rx(hapd)
540     gas = parse_gas(query['payload'])
541
542     resp = action_response(query)
543
544     resp['payload'] = struct.pack('<BBBH', ACTION_CATEG_PUBLIC,
545                                   GAS_COMEBACK_RESPONSE,
546                                   gas['dialog_token'], 0)
547     hapd.mgmt_tx(resp)
548
549     resp['payload'] = struct.pack('<BBBHB', ACTION_CATEG_PUBLIC,
550                                   GAS_COMEBACK_RESPONSE,
551                                   gas['dialog_token'], 0, 0)
552     hapd.mgmt_tx(resp)
553
554     hdr = struct.pack('<BBBHH', ACTION_CATEG_PUBLIC, GAS_INITIAL_RESPONSE,
555                       gas['dialog_token'], 0, 0)
556     resp['payload'] = hdr + struct.pack('B', 108)
557     hapd.mgmt_tx(resp)
558     resp['payload'] = hdr + struct.pack('BB', 108, 0)
559     hapd.mgmt_tx(resp)
560     resp['payload'] = hdr + struct.pack('BB', 108, 1)
561     hapd.mgmt_tx(resp)
562     resp['payload'] = hdr + struct.pack('BB', 108, 255)
563     hapd.mgmt_tx(resp)
564     resp['payload'] = hdr + struct.pack('BBB', 108, 1, 127)
565     hapd.mgmt_tx(resp)
566     resp['payload'] = hdr + struct.pack('BBB', 108, 2, 127)
567     hapd.mgmt_tx(resp)
568     resp['payload'] = hdr + struct.pack('BBBB', 0, 2, 127, 0)
569     hapd.mgmt_tx(resp)
570
571     resp['payload'] = anqp_initial_resp(gas['dialog_token'], 0) + struct.pack('<H', 1)
572     hapd.mgmt_tx(resp)
573
574     resp['payload'] = anqp_initial_resp(gas['dialog_token'], 0) + struct.pack('<HB', 2, 0)
575     hapd.mgmt_tx(resp)
576
577     resp['payload'] = anqp_initial_resp(gas['dialog_token'], 0) + struct.pack('<H', 65535)
578     hapd.mgmt_tx(resp)
579
580     resp['payload'] = anqp_initial_resp(gas['dialog_token'], 0) + struct.pack('<HBB', 1, 0, 0)
581     hapd.mgmt_tx(resp)
582
583     # Station drops invalid frames, but the last of the responses is valid from
584     # GAS view point even though it has an extra octet in the end and the ANQP
585     # part of the response is not valid. This is reported as successfully
586     # completed GAS exchange.
587     expect_gas_result(dev[0], "SUCCESS")
588
589     ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=5)
590     if ev is None:
591         raise Exception("ANQP-QUERY-DONE not reported")
592     if "result=INVALID_FRAME" not in ev:
593         raise Exception("Unexpected result: " + ev)
594
595 def init_gas(hapd, bssid, dev):
596     anqp_get(dev, bssid, 263)
597     query = gas_rx(hapd)
598     gas = parse_gas(query['payload'])
599     dialog_token = gas['dialog_token']
600
601     resp = action_response(query)
602     resp['payload'] = anqp_initial_resp(dialog_token, 0, comeback_delay=1) + struct.pack('<H', 0)
603     send_gas_resp(hapd, resp)
604
605     query = gas_rx(hapd)
606     gas = parse_gas(query['payload'])
607     if gas['action'] != GAS_COMEBACK_REQUEST:
608         raise Exception("Unexpected request action")
609     if gas['dialog_token'] != dialog_token:
610         raise Exception("Unexpected dialog token change")
611     return query, dialog_token
612
613 def test_gas_malformed_comeback_resp(dev, apdev):
614     """GAS malformed comeback response frames"""
615     hapd = start_ap(apdev[0])
616     bssid = apdev[0]['bssid']
617
618     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
619     hapd.set("ext_mgmt_frame_handling", "1")
620
621     logger.debug("Non-zero status code in comeback response")
622     query, dialog_token = init_gas(hapd, bssid, dev[0])
623     resp = action_response(query)
624     resp['payload'] = anqp_comeback_resp(dialog_token, status_code=2) + struct.pack('<H', 0)
625     send_gas_resp(hapd, resp)
626     expect_gas_result(dev[0], "FAILURE", status=2)
627
628     logger.debug("Different advertisement protocol in comeback response")
629     query, dialog_token = init_gas(hapd, bssid, dev[0])
630     resp = action_response(query)
631     resp['payload'] = anqp_comeback_resp(dialog_token, bogus_adv_proto=True) + struct.pack('<H', 0)
632     send_gas_resp(hapd, resp)
633     expect_gas_result(dev[0], "PEER_ERROR")
634
635     logger.debug("Non-zero frag id and comeback delay in comeback response")
636     query, dialog_token = init_gas(hapd, bssid, dev[0])
637     resp = action_response(query)
638     resp['payload'] = anqp_comeback_resp(dialog_token, id=1, comeback_delay=1) + struct.pack('<H', 0)
639     send_gas_resp(hapd, resp)
640     expect_gas_result(dev[0], "PEER_ERROR")
641
642     logger.debug("Unexpected frag id in comeback response")
643     query, dialog_token = init_gas(hapd, bssid, dev[0])
644     resp = action_response(query)
645     resp['payload'] = anqp_comeback_resp(dialog_token, id=1) + struct.pack('<H', 0)
646     send_gas_resp(hapd, resp)
647     expect_gas_result(dev[0], "PEER_ERROR")
648
649     logger.debug("Empty fragment and replay in comeback response")
650     query, dialog_token = init_gas(hapd, bssid, dev[0])
651     resp = action_response(query)
652     resp['payload'] = anqp_comeback_resp(dialog_token, more=True) + struct.pack('<H', 0)
653     send_gas_resp(hapd, resp)
654     query = gas_rx(hapd)
655     gas = parse_gas(query['payload'])
656     if gas['action'] != GAS_COMEBACK_REQUEST:
657         raise Exception("Unexpected request action")
658     if gas['dialog_token'] != dialog_token:
659         raise Exception("Unexpected dialog token change")
660     resp = action_response(query)
661     resp['payload'] = anqp_comeback_resp(dialog_token) + struct.pack('<H', 0)
662     send_gas_resp(hapd, resp)
663     resp['payload'] = anqp_comeback_resp(dialog_token, id=1) + struct.pack('<H', 0)
664     send_gas_resp(hapd, resp)
665     expect_gas_result(dev[0], "SUCCESS")
666
667     logger.debug("Unexpected initial response when waiting for comeback response")
668     query, dialog_token = init_gas(hapd, bssid, dev[0])
669     resp = action_response(query)
670     resp['payload'] = anqp_initial_resp(dialog_token, 0) + struct.pack('<H', 0)
671     send_gas_resp(hapd, resp)
672     ev = hapd.wait_event(["MGMT-RX"], timeout=1)
673     if ev is not None:
674         raise Exception("Unexpected management frame")
675     expect_gas_result(dev[0], "TIMEOUT")
676
677     logger.debug("Too short comeback response")
678     query, dialog_token = init_gas(hapd, bssid, dev[0])
679     resp = action_response(query)
680     resp['payload'] = struct.pack('<BBBH', ACTION_CATEG_PUBLIC,
681                                   GAS_COMEBACK_RESPONSE, dialog_token, 0)
682     send_gas_resp(hapd, resp)
683     ev = hapd.wait_event(["MGMT-RX"], timeout=1)
684     if ev is not None:
685         raise Exception("Unexpected management frame")
686     expect_gas_result(dev[0], "TIMEOUT")
687
688     logger.debug("Too short comeback response(2)")
689     query, dialog_token = init_gas(hapd, bssid, dev[0])
690     resp = action_response(query)
691     resp['payload'] = struct.pack('<BBBHBB', ACTION_CATEG_PUBLIC,
692                                   GAS_COMEBACK_RESPONSE, dialog_token, 0, 0x80,
693                                   0)
694     send_gas_resp(hapd, resp)
695     ev = hapd.wait_event(["MGMT-RX"], timeout=1)
696     if ev is not None:
697         raise Exception("Unexpected management frame")
698     expect_gas_result(dev[0], "TIMEOUT")
699
700     logger.debug("Maximum comeback response fragment claiming more fragments")
701     query, dialog_token = init_gas(hapd, bssid, dev[0])
702     resp = action_response(query)
703     resp['payload'] = anqp_comeback_resp(dialog_token, more=True) + struct.pack('<H', 0)
704     send_gas_resp(hapd, resp)
705     for i in range(1, 129):
706         query = gas_rx(hapd)
707         gas = parse_gas(query['payload'])
708         if gas['action'] != GAS_COMEBACK_REQUEST:
709             raise Exception("Unexpected request action")
710         if gas['dialog_token'] != dialog_token:
711             raise Exception("Unexpected dialog token change")
712         resp = action_response(query)
713         resp['payload'] = anqp_comeback_resp(dialog_token, id=i, more=True) + struct.pack('<H', 0)
714         send_gas_resp(hapd, resp)
715     expect_gas_result(dev[0], "PEER_ERROR")
716
717 def test_gas_comeback_resp_additional_delay(dev, apdev):
718     """GAS comeback response requesting additional delay"""
719     hapd = start_ap(apdev[0])
720     bssid = apdev[0]['bssid']
721
722     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
723     hapd.set("ext_mgmt_frame_handling", "1")
724
725     query, dialog_token = init_gas(hapd, bssid, dev[0])
726     for i in range(0, 2):
727         resp = action_response(query)
728         resp['payload'] = anqp_comeback_resp(dialog_token, status_code=95, comeback_delay=50) + struct.pack('<H', 0)
729         send_gas_resp(hapd, resp)
730         query = gas_rx(hapd)
731         gas = parse_gas(query['payload'])
732         if gas['action'] != GAS_COMEBACK_REQUEST:
733             raise Exception("Unexpected request action")
734         if gas['dialog_token'] != dialog_token:
735             raise Exception("Unexpected dialog token change")
736     resp = action_response(query)
737     resp['payload'] = anqp_comeback_resp(dialog_token, status_code=0) + struct.pack('<H', 0)
738     send_gas_resp(hapd, resp)
739     expect_gas_result(dev[0], "SUCCESS")
740
741 def test_gas_unknown_adv_proto(dev, apdev):
742     """Unknown advertisement protocol id"""
743     bssid = apdev[0]['bssid']
744     params = hs20_ap_params()
745     params['hessid'] = bssid
746     hostapd.add_ap(apdev[0]['ifname'], params)
747
748     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
749     req = dev[0].request("GAS_REQUEST " + bssid + " 42 000102000101")
750     if "FAIL" in req:
751         raise Exception("GAS query request rejected")
752     expect_gas_result(dev[0], "FAILURE", "59")
753     ev = dev[0].wait_event(["GAS-RESPONSE-INFO"], timeout=10)
754     if ev is None:
755         raise Exception("GAS query timed out")
756     exp = r'<.>(GAS-RESPONSE-INFO) addr=([0-9a-f:]*) dialog_token=([0-9]*) status_code=([0-9]*) resp_len=([\-0-9]*)'
757     res = re.split(exp, ev)
758     if len(res) < 6:
759         raise Exception("Could not parse GAS-RESPONSE-INFO")
760     if res[2] != bssid:
761         raise Exception("Unexpected BSSID in response")
762     status = res[4]
763     if status != "59":
764         raise Exception("Unexpected GAS-RESPONSE-INFO status")
765
766 def test_gas_max_pending(dev, apdev):
767     """GAS and maximum pending query limit"""
768     hapd = start_ap(apdev[0])
769     hapd.set("gas_frag_limit", "50")
770     bssid = apdev[0]['bssid']
771
772     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
773     wpas.interface_add("wlan5")
774     if "OK" not in wpas.request("P2P_SET listen_channel 1"):
775         raise Exception("Failed to set listen channel")
776     if "OK" not in wpas.p2p_listen():
777         raise Exception("Failed to start listen state")
778     if "FAIL" in wpas.request("SET ext_mgmt_frame_handling 1"):
779         raise Exception("Failed to enable external management frame handling")
780
781     anqp_query = struct.pack('<HHHHHHHHHH', 256, 16, 257, 258, 260, 261, 262, 263, 264, 268)
782     gas = struct.pack('<H', len(anqp_query)) + anqp_query
783
784     for dialog_token in range(1, 10):
785         msg = struct.pack('<BBB', ACTION_CATEG_PUBLIC, GAS_INITIAL_REQUEST,
786                           dialog_token) + anqp_adv_proto() + gas
787         req = "MGMT_TX {} {} freq=2412 wait_time=10 action={}".format(bssid, bssid, binascii.hexlify(msg))
788         if "OK" not in wpas.request(req):
789             raise Exception("Could not send management frame")
790         resp = wpas.mgmt_rx()
791         if resp is None:
792             raise Exception("MGMT-RX timeout")
793         if 'payload' not in resp:
794             raise Exception("Missing payload")
795         gresp = parse_gas(resp['payload'])
796         if gresp['dialog_token'] != dialog_token:
797             raise Exception("Dialog token mismatch")
798         status_code = gresp['status_code']
799         if dialog_token < 9 and status_code != 0:
800             raise Exception("Unexpected failure status code {} for dialog token {}".format(status_code, dialog_token))
801         if dialog_token > 8 and status_code == 0:
802             raise Exception("Unexpected success status code {} for dialog token {}".format(status_code, dialog_token))
803
804 def test_gas_no_pending(dev, apdev):
805     """GAS and no pending query for comeback request"""
806     hapd = start_ap(apdev[0])
807     bssid = apdev[0]['bssid']
808
809     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
810     wpas.interface_add("wlan5")
811     if "OK" not in wpas.request("P2P_SET listen_channel 1"):
812         raise Exception("Failed to set listen channel")
813     if "OK" not in wpas.p2p_listen():
814         raise Exception("Failed to start listen state")
815     if "FAIL" in wpas.request("SET ext_mgmt_frame_handling 1"):
816         raise Exception("Failed to enable external management frame handling")
817
818     msg = struct.pack('<BBB', ACTION_CATEG_PUBLIC, GAS_COMEBACK_REQUEST, 1)
819     req = "MGMT_TX {} {} freq=2412 wait_time=10 action={}".format(bssid, bssid, binascii.hexlify(msg))
820     if "OK" not in wpas.request(req):
821         raise Exception("Could not send management frame")
822     resp = wpas.mgmt_rx()
823     if resp is None:
824         raise Exception("MGMT-RX timeout")
825     if 'payload' not in resp:
826         raise Exception("Missing payload")
827     gresp = parse_gas(resp['payload'])
828     status_code = gresp['status_code']
829     if status_code != 60:
830         raise Exception("Unexpected status code {} (expected 60)".format(status_code))
831
832 def test_gas_missing_payload(dev, apdev):
833     """No action code in the query frame"""
834     bssid = apdev[0]['bssid']
835     params = hs20_ap_params()
836     params['hessid'] = bssid
837     hostapd.add_ap(apdev[0]['ifname'], params)
838
839     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
840
841     cmd = "MGMT_TX {} {} freq=2412 action=040A".format(bssid, bssid)
842     if "FAIL" in dev[0].request(cmd):
843         raise Exception("Could not send test Action frame")
844     ev = dev[0].wait_event(["MGMT-TX-STATUS"], timeout=10)
845     if ev is None:
846         raise Exception("Timeout on MGMT-TX-STATUS")
847     if "result=SUCCESS" not in ev:
848         raise Exception("AP did not ack Action frame")
849
850     cmd = "MGMT_TX {} {} freq=2412 action=04".format(bssid, bssid)
851     if "FAIL" in dev[0].request(cmd):
852         raise Exception("Could not send test Action frame")
853     ev = dev[0].wait_event(["MGMT-TX-STATUS"], timeout=10)
854     if ev is None:
855         raise Exception("Timeout on MGMT-TX-STATUS")
856     if "result=SUCCESS" not in ev:
857         raise Exception("AP did not ack Action frame")
858
859 def test_gas_query_deinit(dev, apdev):
860     """Pending GAS/ANQP query during deinit"""
861     hapd = start_ap(apdev[0])
862     bssid = apdev[0]['bssid']
863
864     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
865     wpas.interface_add("wlan5")
866
867     wpas.scan_for_bss(bssid, freq="2412", force_scan=True)
868     id = wpas.request("RADIO_WORK add block-work")
869     if "OK" not in wpas.request("ANQP_GET " + bssid + " 258"):
870         raise Exception("ANQP_GET command failed")
871
872     ev = wpas.wait_event(["GAS-QUERY-START", "EXT-RADIO-WORK-START"], timeout=5)
873     if ev is None:
874         raise Exception("Timeout while waiting radio work to start")
875     ev = wpas.wait_event(["GAS-QUERY-START", "EXT-RADIO-WORK-START"], timeout=5)
876     if ev is None:
877         raise Exception("Timeout while waiting radio work to start (2)")
878
879     # Remove the interface while the gas-query radio work is still pending and
880     # GAS query has not yet been started.
881     wpas.interface_remove("wlan5")
882
883 def test_gas_anqp_oom_wpas(dev, apdev):
884     """GAS/ANQP query and OOM in wpa_supplicant"""
885     hapd = start_ap(apdev[0])
886     bssid = apdev[0]['bssid']
887
888     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
889
890     with alloc_fail(dev[0], 1, "gas_build_req"):
891         if "FAIL" not in dev[0].request("ANQP_GET " + bssid + " 258"):
892             raise Exception("Unexpected ANQP_GET command success (OOM)")
893
894 def test_gas_anqp_oom_hapd(dev, apdev):
895     """GAS/ANQP query and OOM in hostapd"""
896     hapd = start_ap(apdev[0])
897     bssid = apdev[0]['bssid']
898
899     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
900
901     with alloc_fail(hapd, 1, "gas_build_resp"):
902         # This query will time out due to the AP not sending a response (OOM).
903         if "OK" not in dev[0].request("ANQP_GET " + bssid + " 258"):
904             raise Exception("ANQP_GET command failed")
905
906         ev = dev[0].wait_event(["GAS-QUERY-START"], timeout=5)
907         if ev is None:
908             raise Exception("GAS query start timed out")
909
910         ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=10)
911         if ev is None:
912             raise Exception("GAS query timed out")
913         if "result=TIMEOUT" not in ev:
914             raise Exception("Unexpected result: " + ev)
915
916         ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=10)
917         if ev is None:
918             raise Exception("ANQP-QUERY-DONE event not seen")
919         if "result=FAILURE" not in ev:
920             raise Exception("Unexpected result: " + ev)
921
922     with alloc_fail(hapd, 1, "gas_anqp_build_comeback_resp"):
923         hapd.set("gas_frag_limit", "50")
924
925         # This query will time out due to the AP not sending a response (OOM).
926         print dev[0].request("FETCH_ANQP")
927         ev = dev[0].wait_event(["GAS-QUERY-START"], timeout=5)
928         if ev is None:
929             raise Exception("GAS query start timed out")
930
931         ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=10)
932         if ev is None:
933             raise Exception("GAS query timed out")
934         if "result=TIMEOUT" not in ev:
935             raise Exception("Unexpected result: " + ev)
936
937         ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=10)
938         if ev is None:
939             raise Exception("ANQP-QUERY-DONE event not seen")
940         if "result=FAILURE" not in ev:
941             raise Exception("Unexpected result: " + ev)