tests: Hotspot 2.0 and connect attempt without matching cred
[mech_eap.git] / tests / hwsim / test_ap_hs20.py
1 # Hotspot 2.0 tests
2 # Copyright (c) 2013-2015, Jouni Malinen <j@w1.fi>
3 #
4 # This software may be distributed under the terms of the BSD license.
5 # See README for more details.
6
7 from remotehost import remote_compatible
8 import base64
9 import binascii
10 import struct
11 import time
12 import logging
13 logger = logging.getLogger()
14 import os
15 import os.path
16 import socket
17 import subprocess
18
19 import hostapd
20 from utils import HwsimSkip, skip_with_fips, alloc_fail, wait_fail_trigger
21 import hwsim_utils
22 from tshark import run_tshark
23 from wlantest import Wlantest
24 from wpasupplicant import WpaSupplicant
25 from test_ap_eap import check_eap_capa, check_domain_match_full
26 from test_gas import gas_rx, parse_gas, action_response, send_gas_resp, ACTION_CATEG_PUBLIC, GAS_INITIAL_RESPONSE
27
28 def hs20_ap_params(ssid="test-hs20"):
29     params = hostapd.wpa2_params(ssid=ssid)
30     params['wpa_key_mgmt'] = "WPA-EAP"
31     params['ieee80211w'] = "1"
32     params['ieee8021x'] = "1"
33     params['auth_server_addr'] = "127.0.0.1"
34     params['auth_server_port'] = "1812"
35     params['auth_server_shared_secret'] = "radius"
36     params['interworking'] = "1"
37     params['access_network_type'] = "14"
38     params['internet'] = "1"
39     params['asra'] = "0"
40     params['esr'] = "0"
41     params['uesa'] = "0"
42     params['venue_group'] = "7"
43     params['venue_type'] = "1"
44     params['venue_name'] = [ "eng:Example venue", "fin:Esimerkkipaikka" ]
45     params['roaming_consortium'] = [ "112233", "1020304050", "010203040506",
46                                      "fedcba" ]
47     params['domain_name'] = "example.com,another.example.com"
48     params['nai_realm'] = [ "0,example.com,13[5:6],21[2:4][5:7]",
49                             "0,another.example.com" ]
50     params['hs20'] = "1"
51     params['hs20_wan_metrics'] = "01:8000:1000:80:240:3000"
52     params['hs20_conn_capab'] = [ "1:0:2", "6:22:1", "17:5060:0" ]
53     params['hs20_operating_class'] = "5173"
54     params['anqp_3gpp_cell_net'] = "244,91"
55     return params
56
57 def check_auto_select(dev, bssid):
58     dev.scan_for_bss(bssid, freq="2412")
59     dev.request("INTERWORKING_SELECT auto freq=2412")
60     ev = dev.wait_connected(timeout=15)
61     if bssid not in ev:
62         raise Exception("Connected to incorrect network")
63     dev.request("REMOVE_NETWORK all")
64     dev.wait_disconnected()
65     dev.dump_monitor()
66
67 def interworking_select(dev, bssid, type=None, no_match=False, freq=None):
68     dev.dump_monitor()
69     if bssid and freq and not no_match:
70         dev.scan_for_bss(bssid, freq=freq)
71     freq_extra = " freq=" + str(freq) if freq else ""
72     dev.request("INTERWORKING_SELECT" + freq_extra)
73     ev = dev.wait_event(["INTERWORKING-AP", "INTERWORKING-NO-MATCH"],
74                         timeout=15)
75     if ev is None:
76         raise Exception("Network selection timed out")
77     if no_match:
78         if "INTERWORKING-NO-MATCH" not in ev:
79             raise Exception("Unexpected network match")
80         return
81     if "INTERWORKING-NO-MATCH" in ev:
82         logger.info("Matching network not found - try again")
83         dev.dump_monitor()
84         dev.request("INTERWORKING_SELECT" + freq_extra)
85         ev = dev.wait_event(["INTERWORKING-AP", "INTERWORKING-NO-MATCH"],
86                             timeout=15)
87         if ev is None:
88             raise Exception("Network selection timed out")
89         if "INTERWORKING-NO-MATCH" in ev:
90             raise Exception("Matching network not found")
91     if bssid and bssid not in ev:
92         raise Exception("Unexpected BSSID in match")
93     if type and "type=" + type not in ev:
94         raise Exception("Network type not recognized correctly")
95
96 def check_sp_type(dev, sp_type):
97     type = dev.get_status_field("sp_type")
98     if type is None:
99         raise Exception("sp_type not available")
100     if type != sp_type:
101         raise Exception("sp_type did not indicate home network")
102
103 def hlr_auc_gw_available():
104     if not os.path.exists("/tmp/hlr_auc_gw.sock"):
105         raise HwsimSkip("No hlr_auc_gw socket available")
106     if not os.path.exists("../../hostapd/hlr_auc_gw"):
107         raise HwsimSkip("No hlr_auc_gw available")
108
109 def interworking_ext_sim_connect(dev, bssid, method):
110     dev.request("INTERWORKING_CONNECT " + bssid)
111     interworking_ext_sim_auth(dev, method)
112
113 def interworking_ext_sim_auth(dev, method):
114     ev = dev.wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=15)
115     if ev is None:
116         raise Exception("Network connected timed out")
117     if "(" + method + ")" not in ev:
118         raise Exception("Unexpected EAP method selection")
119
120     ev = dev.wait_event(["CTRL-REQ-SIM"], timeout=15)
121     if ev is None:
122         raise Exception("Wait for external SIM processing request timed out")
123     p = ev.split(':', 2)
124     if p[1] != "GSM-AUTH":
125         raise Exception("Unexpected CTRL-REQ-SIM type")
126     id = p[0].split('-')[3]
127     rand = p[2].split(' ')[0]
128
129     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
130                                    "-m",
131                                    "auth_serv/hlr_auc_gw.milenage_db",
132                                    "GSM-AUTH-REQ 232010000000000 " + rand])
133     if "GSM-AUTH-RESP" not in res:
134         raise Exception("Unexpected hlr_auc_gw response")
135     resp = res.split(' ')[2].rstrip()
136
137     dev.request("CTRL-RSP-SIM-" + id + ":GSM-AUTH:" + resp)
138     dev.wait_connected(timeout=15)
139
140 def interworking_connect(dev, bssid, method):
141     dev.request("INTERWORKING_CONNECT " + bssid)
142     interworking_auth(dev, method)
143
144 def interworking_auth(dev, method):
145     ev = dev.wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=15)
146     if ev is None:
147         raise Exception("Network connected timed out")
148     if "(" + method + ")" not in ev:
149         raise Exception("Unexpected EAP method selection")
150
151     dev.wait_connected(timeout=15)
152
153 def check_probe_resp(wt, bssid_unexpected, bssid_expected):
154     if bssid_unexpected:
155         count = wt.get_bss_counter("probe_response", bssid_unexpected)
156         if count > 0:
157             raise Exception("Unexpected Probe Response frame from AP")
158
159     if bssid_expected:
160         count = wt.get_bss_counter("probe_response", bssid_expected)
161         if count == 0:
162             raise Exception("No Probe Response frame from AP")
163
164 def test_ap_anqp_sharing(dev, apdev):
165     """ANQP sharing within ESS and explicit unshare"""
166     check_eap_capa(dev[0], "MSCHAPV2")
167     dev[0].flush_scan_cache()
168
169     bssid = apdev[0]['bssid']
170     params = hs20_ap_params()
171     params['hessid'] = bssid
172     hostapd.add_ap(apdev[0], params)
173
174     bssid2 = apdev[1]['bssid']
175     params = hs20_ap_params()
176     params['hessid'] = bssid
177     params['nai_realm'] = [ "0,example.com,13[5:6],21[2:4][5:7]" ]
178     hostapd.add_ap(apdev[1], params)
179
180     dev[0].hs20_enable()
181     id = dev[0].add_cred_values({ 'realm': "example.com", 'username': "test",
182                                   'password': "secret",
183                                   'domain': "example.com" })
184     logger.info("Normal network selection with shared ANQP results")
185     dev[0].scan_for_bss(bssid, freq="2412")
186     dev[0].scan_for_bss(bssid2, freq="2412")
187     interworking_select(dev[0], None, "home", freq="2412")
188     dev[0].dump_monitor()
189
190     logger.debug("BSS entries:\n" + dev[0].request("BSS RANGE=ALL"))
191     res1 = dev[0].get_bss(bssid)
192     res2 = dev[0].get_bss(bssid2)
193     if 'anqp_nai_realm' not in res1:
194         raise Exception("anqp_nai_realm not found for AP1")
195     if 'anqp_nai_realm' not in res2:
196         raise Exception("anqp_nai_realm not found for AP2")
197     if res1['anqp_nai_realm'] != res2['anqp_nai_realm']:
198         raise Exception("ANQP results were not shared between BSSes")
199
200     logger.info("Explicit ANQP request to unshare ANQP results")
201     dev[0].request("ANQP_GET " + bssid + " 263")
202     ev = dev[0].wait_event(["RX-ANQP"], timeout=5)
203     if ev is None:
204         raise Exception("ANQP operation timed out")
205
206     dev[0].request("ANQP_GET " + bssid2 + " 263")
207     ev = dev[0].wait_event(["RX-ANQP"], timeout=5)
208     if ev is None:
209         raise Exception("ANQP operation timed out")
210
211     res1 = dev[0].get_bss(bssid)
212     res2 = dev[0].get_bss(bssid2)
213     if res1['anqp_nai_realm'] == res2['anqp_nai_realm']:
214         raise Exception("ANQP results were not unshared")
215
216 def test_ap_anqp_no_sharing_diff_ess(dev, apdev):
217     """ANQP no sharing between ESSs"""
218     check_eap_capa(dev[0], "MSCHAPV2")
219     dev[0].flush_scan_cache()
220
221     bssid = apdev[0]['bssid']
222     params = hs20_ap_params()
223     params['hessid'] = bssid
224     hostapd.add_ap(apdev[0], params)
225
226     bssid2 = apdev[1]['bssid']
227     params = hs20_ap_params(ssid="test-hs20-another")
228     params['hessid'] = bssid
229     params['nai_realm'] = [ "0,example.com,13[5:6],21[2:4][5:7]" ]
230     hostapd.add_ap(apdev[1], params)
231
232     dev[0].hs20_enable()
233     id = dev[0].add_cred_values({ 'realm': "example.com", 'username': "test",
234                                   'password': "secret",
235                                   'domain': "example.com" })
236     logger.info("Normal network selection with shared ANQP results")
237     dev[0].scan_for_bss(bssid, freq="2412")
238     dev[0].scan_for_bss(bssid2, freq="2412")
239     interworking_select(dev[0], None, "home", freq="2412")
240
241 def test_ap_anqp_no_sharing_missing_info(dev, apdev):
242     """ANQP no sharing due to missing information"""
243     check_eap_capa(dev[0], "MSCHAPV2")
244     dev[0].flush_scan_cache()
245
246     bssid = apdev[0]['bssid']
247     params = hs20_ap_params()
248     params['hessid'] = bssid
249     del params['roaming_consortium']
250     del params['domain_name']
251     del params['anqp_3gpp_cell_net']
252     del params['nai_realm']
253     hostapd.add_ap(apdev[0], params)
254
255     bssid2 = apdev[1]['bssid']
256     params = hs20_ap_params()
257     params['hessid'] = bssid
258     params['nai_realm'] = [ "0,example.com,13[5:6],21[2:4][5:7]" ]
259     hostapd.add_ap(apdev[1], params)
260
261     dev[0].hs20_enable()
262     id = dev[0].add_cred_values({ 'realm': "example.com", 'username': "test",
263                                   'password': "secret",
264                                   'domain': "example.com" })
265     logger.info("Normal network selection with shared ANQP results")
266     dev[0].scan_for_bss(bssid, freq="2412")
267     dev[0].scan_for_bss(bssid2, freq="2412")
268     interworking_select(dev[0], None, "home", freq="2412")
269
270 def test_ap_anqp_sharing_oom(dev, apdev):
271     """ANQP sharing within ESS and explicit unshare OOM"""
272     check_eap_capa(dev[0], "MSCHAPV2")
273     dev[0].flush_scan_cache()
274
275     bssid = apdev[0]['bssid']
276     params = hs20_ap_params()
277     params['hessid'] = bssid
278     hostapd.add_ap(apdev[0], params)
279
280     bssid2 = apdev[1]['bssid']
281     params = hs20_ap_params()
282     params['hessid'] = bssid
283     params['nai_realm'] = [ "0,example.com,13[5:6],21[2:4][5:7]" ]
284     hostapd.add_ap(apdev[1], params)
285
286     dev[0].hs20_enable()
287     id = dev[0].add_cred_values({ 'realm': "example.com", 'username': "test",
288                                   'password': "secret",
289                                   'domain': "example.com" })
290     dev[0].scan_for_bss(bssid, freq="2412")
291     dev[0].scan_for_bss(bssid2, freq="2412")
292     interworking_select(dev[0], None, "home", freq="2412")
293     dev[0].dump_monitor()
294
295     with alloc_fail(dev[0], 1, "wpa_bss_anqp_clone"):
296         dev[0].request("ANQP_GET " + bssid + " 263")
297         ev = dev[0].wait_event(["RX-ANQP"], timeout=5)
298         if ev is None:
299             raise Exception("ANQP operation timed out")
300
301 def test_ap_nai_home_realm_query(dev, apdev):
302     """NAI Home Realm Query"""
303     check_eap_capa(dev[0], "MSCHAPV2")
304     bssid = apdev[0]['bssid']
305     params = hs20_ap_params()
306     params['nai_realm'] = [ "0,example.com,13[5:6],21[2:4][5:7]",
307                             "0,another.example.org" ]
308     hostapd.add_ap(apdev[0], params)
309
310     dev[0].scan(freq="2412")
311     dev[0].request("HS20_GET_NAI_HOME_REALM_LIST " + bssid + " realm=example.com")
312     ev = dev[0].wait_event(["RX-ANQP"], timeout=5)
313     if ev is None:
314         raise Exception("ANQP operation timed out")
315     nai1 = dev[0].get_bss(bssid)['anqp_nai_realm']
316     dev[0].dump_monitor()
317
318     dev[0].request("ANQP_GET " + bssid + " 263")
319     ev = dev[0].wait_event(["RX-ANQP"], timeout=5)
320     if ev is None:
321         raise Exception("ANQP operation timed out")
322     nai2 = dev[0].get_bss(bssid)['anqp_nai_realm']
323
324     if len(nai1) >= len(nai2):
325         raise Exception("Unexpected NAI Realm list response lengths")
326     if "example.com".encode('hex') not in nai1:
327         raise Exception("Home realm not reported")
328     if "example.org".encode('hex') in nai1:
329         raise Exception("Non-home realm reported")
330     if "example.com".encode('hex') not in nai2:
331         raise Exception("Home realm not reported in wildcard query")
332     if "example.org".encode('hex') not in nai2:
333         raise Exception("Non-home realm not reported in wildcard query ")
334
335     cmds = [ "foo",
336              "00:11:22:33:44:55 123",
337              "00:11:22:33:44:55 qq" ]
338     for cmd in cmds:
339         if "FAIL" not in dev[0].request("HS20_GET_NAI_HOME_REALM_LIST " + cmd):
340             raise Exception("Invalid HS20_GET_NAI_HOME_REALM_LIST accepted: " + cmd)
341
342     dev[0].dump_monitor()
343     if "OK" not in dev[0].request("HS20_GET_NAI_HOME_REALM_LIST " + bssid):
344         raise Exception("HS20_GET_NAI_HOME_REALM_LIST failed")
345     ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=10)
346     if ev is None:
347         raise Exception("ANQP operation timed out")
348     ev = dev[0].wait_event(["RX-ANQP"], timeout=0.1)
349     if ev is not None:
350         raise Exception("Unexpected ANQP response: " + ev)
351
352     dev[0].dump_monitor()
353     if "OK" not in dev[0].request("HS20_GET_NAI_HOME_REALM_LIST " + bssid + " 01000b6578616d706c652e636f6d"):
354         raise Exception("HS20_GET_NAI_HOME_REALM_LIST failed")
355     ev = dev[0].wait_event(["RX-ANQP"], timeout=10)
356     if ev is None:
357         raise Exception("No ANQP response")
358     if "NAI Realm list" not in ev:
359         raise Exception("Missing NAI Realm list: " + ev)
360
361     dev[0].add_cred_values({ 'realm': "example.com", 'username': "test",
362                              'password': "secret",
363                              'domain': "example.com" })
364     dev[0].dump_monitor()
365     if "OK" not in dev[0].request("HS20_GET_NAI_HOME_REALM_LIST " + bssid):
366         raise Exception("HS20_GET_NAI_HOME_REALM_LIST failed")
367     ev = dev[0].wait_event(["RX-ANQP"], timeout=10)
368     if ev is None:
369         raise Exception("No ANQP response")
370     if "NAI Realm list" not in ev:
371         raise Exception("Missing NAI Realm list: " + ev)
372
373 @remote_compatible
374 def test_ap_interworking_scan_filtering(dev, apdev):
375     """Interworking scan filtering with HESSID and access network type"""
376     try:
377         _test_ap_interworking_scan_filtering(dev, apdev)
378     finally:
379         dev[0].request("SET hessid 00:00:00:00:00:00")
380         dev[0].request("SET access_network_type 15")
381
382 def _test_ap_interworking_scan_filtering(dev, apdev):
383     bssid = apdev[0]['bssid']
384     params = hs20_ap_params()
385     ssid = "test-hs20-ap1"
386     params['ssid'] = ssid
387     params['hessid'] = bssid
388     hapd0 = hostapd.add_ap(apdev[0], params)
389
390     bssid2 = apdev[1]['bssid']
391     params = hs20_ap_params()
392     ssid2 = "test-hs20-ap2"
393     params['ssid'] = ssid2
394     params['hessid'] = bssid2
395     params['access_network_type'] = "1"
396     del params['venue_group']
397     del params['venue_type']
398     hostapd.add_ap(apdev[1], params)
399
400     dev[0].hs20_enable()
401
402     Wlantest.setup(hapd0)
403     wt = Wlantest()
404     wt.flush()
405
406     logger.info("Check probe request filtering based on HESSID")
407
408     dev[0].request("SET hessid " + bssid2)
409     dev[0].scan(freq="2412")
410     time.sleep(0.03)
411     check_probe_resp(wt, bssid, bssid2)
412
413     logger.info("Check probe request filtering based on access network type")
414
415     wt.clear_bss_counters(bssid)
416     wt.clear_bss_counters(bssid2)
417     dev[0].request("SET hessid 00:00:00:00:00:00")
418     dev[0].request("SET access_network_type 14")
419     dev[0].scan(freq="2412")
420     time.sleep(0.03)
421     check_probe_resp(wt, bssid2, bssid)
422
423     wt.clear_bss_counters(bssid)
424     wt.clear_bss_counters(bssid2)
425     dev[0].request("SET hessid 00:00:00:00:00:00")
426     dev[0].request("SET access_network_type 1")
427     dev[0].scan(freq="2412")
428     time.sleep(0.03)
429     check_probe_resp(wt, bssid, bssid2)
430
431     logger.info("Check probe request filtering based on HESSID and ANT")
432
433     wt.clear_bss_counters(bssid)
434     wt.clear_bss_counters(bssid2)
435     dev[0].request("SET hessid " + bssid)
436     dev[0].request("SET access_network_type 14")
437     dev[0].scan(freq="2412")
438     time.sleep(0.03)
439     check_probe_resp(wt, bssid2, bssid)
440
441     wt.clear_bss_counters(bssid)
442     wt.clear_bss_counters(bssid2)
443     dev[0].request("SET hessid " + bssid2)
444     dev[0].request("SET access_network_type 14")
445     dev[0].scan(freq="2412")
446     time.sleep(0.03)
447     check_probe_resp(wt, bssid, None)
448     check_probe_resp(wt, bssid2, None)
449
450     wt.clear_bss_counters(bssid)
451     wt.clear_bss_counters(bssid2)
452     dev[0].request("SET hessid " + bssid)
453     dev[0].request("SET access_network_type 1")
454     dev[0].scan(freq="2412")
455     time.sleep(0.03)
456     check_probe_resp(wt, bssid, None)
457     check_probe_resp(wt, bssid2, None)
458
459 def test_ap_hs20_select(dev, apdev):
460     """Hotspot 2.0 network selection"""
461     bssid = apdev[0]['bssid']
462     params = hs20_ap_params()
463     params['hessid'] = bssid
464     hostapd.add_ap(apdev[0], params)
465
466     dev[0].hs20_enable()
467     id = dev[0].add_cred_values({ 'realm': "example.com", 'username': "test",
468                                   'password': "secret",
469                                   'domain': "example.com" })
470     interworking_select(dev[0], bssid, "home")
471
472     dev[0].remove_cred(id)
473     id = dev[0].add_cred_values({ 'realm': "example.com", 'username': "test",
474                                   'password': "secret",
475                                   'domain': "no.match.example.com" })
476     interworking_select(dev[0], bssid, "roaming", freq="2412")
477
478     dev[0].set_cred_quoted(id, "realm", "no.match.example.com")
479     interworking_select(dev[0], bssid, no_match=True, freq="2412")
480
481     res = dev[0].request("SCAN_RESULTS")
482     if "[HS20]" not in res:
483         raise Exception("HS20 flag missing from scan results: " + res)
484
485     bssid2 = apdev[1]['bssid']
486     params = hs20_ap_params()
487     params['nai_realm'] = [ "0,example.org,21" ]
488     params['hessid'] = bssid2
489     params['domain_name'] = "example.org"
490     hostapd.add_ap(apdev[1], params)
491     dev[0].remove_cred(id)
492     id = dev[0].add_cred_values({ 'realm': "example.org", 'username': "test",
493                                   'password': "secret",
494                                   'domain': "example.org" })
495     interworking_select(dev[0], bssid2, "home", freq="2412")
496
497 def hs20_simulated_sim(dev, ap, method):
498     bssid = ap['bssid']
499     params = hs20_ap_params()
500     params['hessid'] = bssid
501     params['anqp_3gpp_cell_net'] = "555,444"
502     params['domain_name'] = "wlan.mnc444.mcc555.3gppnetwork.org"
503     hostapd.add_ap(ap, params)
504
505     dev.hs20_enable()
506     dev.add_cred_values({ 'imsi': "555444-333222111", 'eap': method,
507                           'milenage': "5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123"})
508     interworking_select(dev, bssid, "home", freq="2412")
509     interworking_connect(dev, bssid, method)
510     check_sp_type(dev, "home")
511
512 def test_ap_hs20_sim(dev, apdev):
513     """Hotspot 2.0 with simulated SIM and EAP-SIM"""
514     hlr_auc_gw_available()
515     hs20_simulated_sim(dev[0], apdev[0], "SIM")
516     dev[0].request("INTERWORKING_SELECT auto freq=2412")
517     ev = dev[0].wait_event(["INTERWORKING-ALREADY-CONNECTED"], timeout=15)
518     if ev is None:
519         raise Exception("Timeout on already-connected event")
520
521 def test_ap_hs20_sim_invalid(dev, apdev):
522     """Hotspot 2.0 with simulated SIM and EAP-SIM - invalid IMSI"""
523     hlr_auc_gw_available()
524     bssid = apdev[0]['bssid']
525     params = hs20_ap_params()
526     params['hessid'] = bssid
527     params['anqp_3gpp_cell_net'] = "555,444"
528     params['domain_name'] = "wlan.mnc444.mcc555.3gppnetwork.org"
529     hostapd.add_ap(apdev[0], params)
530
531     dev[0].hs20_enable()
532     dev[0].add_cred_values({ 'imsi': "555444-3332221110", 'eap': "SIM",
533                           'milenage': "5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123"})
534     # This hits "No valid IMSI available" in build_root_nai()
535     interworking_select(dev[0], bssid, freq="2412")
536
537 def test_ap_hs20_sim_oom(dev, apdev):
538     """Hotspot 2.0 with simulated SIM and EAP-SIM - OOM"""
539     hlr_auc_gw_available()
540     bssid = apdev[0]['bssid']
541     params = hs20_ap_params()
542     params['hessid'] = bssid
543     params['anqp_3gpp_cell_net'] = "555,444"
544     params['domain_name'] = "wlan.mnc444.mcc555.3gppnetwork.org"
545     hostapd.add_ap(apdev[0], params)
546
547     dev[0].hs20_enable()
548     dev[0].add_cred_values({ 'imsi': "555444-333222111", 'eap': "SIM",
549                           'milenage': "5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123"})
550     dev[0].scan_for_bss(bssid, freq=2412)
551     interworking_select(dev[0], bssid, freq="2412")
552
553     with alloc_fail(dev[0], 1, "wpa_config_add_network;interworking_connect_3gpp"):
554         dev[0].request("INTERWORKING_CONNECT " + bssid)
555         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
556
557     with alloc_fail(dev[0], 1, "=interworking_connect_3gpp"):
558         dev[0].request("INTERWORKING_CONNECT " + bssid)
559         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
560
561 def test_ap_hs20_aka(dev, apdev):
562     """Hotspot 2.0 with simulated USIM and EAP-AKA"""
563     hlr_auc_gw_available()
564     hs20_simulated_sim(dev[0], apdev[0], "AKA")
565
566 def test_ap_hs20_aka_prime(dev, apdev):
567     """Hotspot 2.0 with simulated USIM and EAP-AKA'"""
568     hlr_auc_gw_available()
569     hs20_simulated_sim(dev[0], apdev[0], "AKA'")
570
571 def test_ap_hs20_ext_sim(dev, apdev):
572     """Hotspot 2.0 with external SIM processing"""
573     hlr_auc_gw_available()
574     bssid = apdev[0]['bssid']
575     params = hs20_ap_params()
576     params['hessid'] = bssid
577     params['anqp_3gpp_cell_net'] = "232,01"
578     params['domain_name'] = "wlan.mnc001.mcc232.3gppnetwork.org"
579     hostapd.add_ap(apdev[0], params)
580
581     dev[0].hs20_enable()
582     try:
583         dev[0].request("SET external_sim 1")
584         dev[0].add_cred_values({ 'imsi': "23201-0000000000", 'eap': "SIM" })
585         interworking_select(dev[0], bssid, "home", freq="2412")
586         interworking_ext_sim_connect(dev[0], bssid, "SIM")
587         check_sp_type(dev[0], "home")
588     finally:
589         dev[0].request("SET external_sim 0")
590
591 def test_ap_hs20_ext_sim_roaming(dev, apdev):
592     """Hotspot 2.0 with external SIM processing in roaming network"""
593     hlr_auc_gw_available()
594     bssid = apdev[0]['bssid']
595     params = hs20_ap_params()
596     params['hessid'] = bssid
597     params['anqp_3gpp_cell_net'] = "244,91;310,026;232,01;234,56"
598     params['domain_name'] = "wlan.mnc091.mcc244.3gppnetwork.org"
599     hostapd.add_ap(apdev[0], params)
600
601     dev[0].hs20_enable()
602     try:
603         dev[0].request("SET external_sim 1")
604         dev[0].add_cred_values({ 'imsi': "23201-0000000000", 'eap': "SIM" })
605         interworking_select(dev[0], bssid, "roaming", freq="2412")
606         interworking_ext_sim_connect(dev[0], bssid, "SIM")
607         check_sp_type(dev[0], "roaming")
608     finally:
609         dev[0].request("SET external_sim 0")
610
611 def test_ap_hs20_username(dev, apdev):
612     """Hotspot 2.0 connection in username/password credential"""
613     check_eap_capa(dev[0], "MSCHAPV2")
614     bssid = apdev[0]['bssid']
615     params = hs20_ap_params()
616     params['hessid'] = bssid
617     params['disable_dgaf'] = '1'
618     hostapd.add_ap(apdev[0], params)
619
620     dev[0].hs20_enable()
621     id = dev[0].add_cred_values({ 'realm': "example.com",
622                                   'username': "hs20-test",
623                                   'password': "password",
624                                   'ca_cert': "auth_serv/ca.pem",
625                                   'domain': "example.com",
626                                   'update_identifier': "1234" })
627     interworking_select(dev[0], bssid, "home", freq="2412")
628     interworking_connect(dev[0], bssid, "TTLS")
629     check_sp_type(dev[0], "home")
630     status = dev[0].get_status()
631     if status['pairwise_cipher'] != "CCMP":
632         raise Exception("Unexpected pairwise cipher")
633     if status['hs20'] != "2":
634         raise Exception("Unexpected HS 2.0 support indication")
635
636     dev[1].connect("test-hs20", key_mgmt="WPA-EAP", eap="TTLS",
637                    identity="hs20-test", password="password",
638                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
639                    scan_freq="2412")
640
641 def test_ap_hs20_connect_api(dev, apdev):
642     """Hotspot 2.0 connection with connect API"""
643     check_eap_capa(dev[0], "MSCHAPV2")
644     bssid = apdev[0]['bssid']
645     params = hs20_ap_params()
646     params['hessid'] = bssid
647     params['disable_dgaf'] = '1'
648     hostapd.add_ap(apdev[0], params)
649
650     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
651     wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
652     wpas.hs20_enable()
653     wpas.flush_scan_cache()
654     id = wpas.add_cred_values({ 'realm': "example.com",
655                                   'username': "hs20-test",
656                                   'password': "password",
657                                   'ca_cert': "auth_serv/ca.pem",
658                                   'domain': "example.com",
659                                   'update_identifier': "1234" })
660     interworking_select(wpas, bssid, "home", freq="2412")
661     interworking_connect(wpas, bssid, "TTLS")
662     check_sp_type(wpas, "home")
663     status = wpas.get_status()
664     if status['pairwise_cipher'] != "CCMP":
665         raise Exception("Unexpected pairwise cipher")
666     if status['hs20'] != "2":
667         raise Exception("Unexpected HS 2.0 support indication")
668
669 def test_ap_hs20_auto_interworking(dev, apdev):
670     """Hotspot 2.0 connection with auto_interworking=1"""
671     check_eap_capa(dev[0], "MSCHAPV2")
672     bssid = apdev[0]['bssid']
673     params = hs20_ap_params()
674     params['hessid'] = bssid
675     params['disable_dgaf'] = '1'
676     hostapd.add_ap(apdev[0], params)
677
678     dev[0].hs20_enable(auto_interworking=True)
679     id = dev[0].add_cred_values({ 'realm': "example.com",
680                                   'username': "hs20-test",
681                                   'password': "password",
682                                   'ca_cert': "auth_serv/ca.pem",
683                                   'domain': "example.com",
684                                   'update_identifier': "1234" })
685     dev[0].request("REASSOCIATE")
686     dev[0].wait_connected(timeout=15)
687     check_sp_type(dev[0], "home")
688     status = dev[0].get_status()
689     if status['pairwise_cipher'] != "CCMP":
690         raise Exception("Unexpected pairwise cipher")
691     if status['hs20'] != "2":
692         raise Exception("Unexpected HS 2.0 support indication")
693
694 @remote_compatible
695 def test_ap_hs20_auto_interworking_no_match(dev, apdev):
696     """Hotspot 2.0 connection with auto_interworking=1 and no matching network"""
697     hapd = hostapd.add_ap(apdev[0], { "ssid": "mismatch" })
698
699     dev[0].hs20_enable(auto_interworking=True)
700     id = dev[0].connect("mismatch", psk="12345678", scan_freq="2412",
701                         only_add_network=True)
702     dev[0].request("ENABLE_NETWORK " + str(id) + " no-connect")
703
704     id = dev[0].add_cred_values({ 'realm': "example.com",
705                                   'username': "hs20-test",
706                                   'password': "password",
707                                   'ca_cert': "auth_serv/ca.pem",
708                                   'domain': "example.com",
709                                   'update_identifier': "1234" })
710     dev[0].request("INTERWORKING_SELECT auto freq=2412")
711     time.sleep(0.1)
712     dev[0].dump_monitor()
713     for i in range(5):
714         logger.info("start ping")
715         if "PONG" not in dev[0].ctrl.request("PING", timeout=2):
716             raise Exception("PING failed")
717         logger.info("ping done")
718         fetch = 0
719         scan = 0
720         for j in range(15):
721             ev = dev[0].wait_event([ "ANQP fetch completed",
722                                      "CTRL-EVENT-SCAN-RESULTS" ], timeout=0.05)
723             if ev is None:
724                 break
725             if "ANQP fetch completed" in ev:
726                 fetch += 1
727             else:
728                 scan += 1
729         if fetch > 2 * scan + 3:
730             raise Exception("Too many ANQP fetch iterations")
731         dev[0].dump_monitor()
732     dev[0].request("DISCONNECT")
733
734 @remote_compatible
735 def test_ap_hs20_auto_interworking_no_cred_match(dev, apdev):
736     """Hotspot 2.0 connection with auto_interworking=1 but no cred match"""
737     bssid = apdev[0]['bssid']
738     params = { "ssid": "test" }
739     hostapd.add_ap(apdev[0], params)
740
741     dev[0].hs20_enable(auto_interworking=True)
742     dev[0].add_cred_values({ 'realm': "example.com",
743                              'username': "hs20-test",
744                              'password': "password",
745                              'ca_cert': "auth_serv/ca.pem",
746                              'domain': "example.com" })
747
748     id = dev[0].connect("test", psk="12345678", only_add_network=True)
749     dev[0].request("ENABLE_NETWORK %s" % id)
750     logger.info("Verify that scanning continues when there is partial network block match")
751     for i in range(0, 2):
752         ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 10)
753         if ev is None:
754             raise Exception("Scan timed out")
755         logger.info("Scan completed")
756
757 def eap_test(dev, ap, eap_params, method, user):
758     bssid = ap['bssid']
759     params = hs20_ap_params()
760     params['nai_realm'] = [ "0,example.com," + eap_params ]
761     hostapd.add_ap(ap, params)
762
763     dev.hs20_enable()
764     dev.add_cred_values({ 'realm': "example.com",
765                           'ca_cert': "auth_serv/ca.pem",
766                           'username': user,
767                           'password': "password" })
768     interworking_select(dev, bssid, freq="2412")
769     interworking_connect(dev, bssid, method)
770
771 @remote_compatible
772 def test_ap_hs20_eap_unknown(dev, apdev):
773     """Hotspot 2.0 connection with unknown EAP method"""
774     bssid = apdev[0]['bssid']
775     params = hs20_ap_params()
776     params['nai_realm'] = "0,example.com,99"
777     hostapd.add_ap(apdev[0], params)
778
779     dev[0].hs20_enable()
780     dev[0].add_cred_values(default_cred())
781     interworking_select(dev[0], None, no_match=True, freq="2412")
782
783 def test_ap_hs20_eap_peap_mschapv2(dev, apdev):
784     """Hotspot 2.0 connection with PEAP/MSCHAPV2"""
785     check_eap_capa(dev[0], "MSCHAPV2")
786     eap_test(dev[0], apdev[0], "25[3:26]", "PEAP", "user")
787
788 def test_ap_hs20_eap_peap_default(dev, apdev):
789     """Hotspot 2.0 connection with PEAP/MSCHAPV2 (as default)"""
790     check_eap_capa(dev[0], "MSCHAPV2")
791     eap_test(dev[0], apdev[0], "25", "PEAP", "user")
792
793 def test_ap_hs20_eap_peap_gtc(dev, apdev):
794     """Hotspot 2.0 connection with PEAP/GTC"""
795     eap_test(dev[0], apdev[0], "25[3:6]", "PEAP", "user")
796
797 @remote_compatible
798 def test_ap_hs20_eap_peap_unknown(dev, apdev):
799     """Hotspot 2.0 connection with PEAP/unknown"""
800     bssid = apdev[0]['bssid']
801     params = hs20_ap_params()
802     params['nai_realm'] = "0,example.com,25[3:99]"
803     hostapd.add_ap(apdev[0], params)
804
805     dev[0].hs20_enable()
806     dev[0].add_cred_values(default_cred())
807     interworking_select(dev[0], None, no_match=True, freq="2412")
808
809 def test_ap_hs20_eap_ttls_chap(dev, apdev):
810     """Hotspot 2.0 connection with TTLS/CHAP"""
811     skip_with_fips(dev[0])
812     eap_test(dev[0], apdev[0], "21[2:2]", "TTLS", "chap user")
813
814 def test_ap_hs20_eap_ttls_mschap(dev, apdev):
815     """Hotspot 2.0 connection with TTLS/MSCHAP"""
816     skip_with_fips(dev[0])
817     eap_test(dev[0], apdev[0], "21[2:3]", "TTLS", "mschap user")
818
819 def test_ap_hs20_eap_ttls_default(dev, apdev):
820     """Hotspot 2.0 connection with TTLS/default"""
821     skip_with_fips(dev[0])
822     eap_test(dev[0], apdev[0], "21", "TTLS", "hs20-test")
823
824 def test_ap_hs20_eap_ttls_eap_mschapv2(dev, apdev):
825     """Hotspot 2.0 connection with TTLS/EAP-MSCHAPv2"""
826     check_eap_capa(dev[0], "MSCHAPV2")
827     eap_test(dev[0], apdev[0], "21[3:26][6:7][99:99]", "TTLS", "user")
828
829 @remote_compatible
830 def test_ap_hs20_eap_ttls_eap_unknown(dev, apdev):
831     """Hotspot 2.0 connection with TTLS/EAP-unknown"""
832     bssid = apdev[0]['bssid']
833     params = hs20_ap_params()
834     params['nai_realm'] = "0,example.com,21[3:99]"
835     hostapd.add_ap(apdev[0], params)
836
837     dev[0].hs20_enable()
838     dev[0].add_cred_values(default_cred())
839     interworking_select(dev[0], None, no_match=True, freq="2412")
840
841 @remote_compatible
842 def test_ap_hs20_eap_ttls_eap_unsupported(dev, apdev):
843     """Hotspot 2.0 connection with TTLS/EAP-OTP(unsupported)"""
844     bssid = apdev[0]['bssid']
845     params = hs20_ap_params()
846     params['nai_realm'] = "0,example.com,21[3:5]"
847     hostapd.add_ap(apdev[0], params)
848
849     dev[0].hs20_enable()
850     dev[0].add_cred_values(default_cred())
851     interworking_select(dev[0], None, no_match=True, freq="2412")
852
853 @remote_compatible
854 def test_ap_hs20_eap_ttls_unknown(dev, apdev):
855     """Hotspot 2.0 connection with TTLS/unknown"""
856     bssid = apdev[0]['bssid']
857     params = hs20_ap_params()
858     params['nai_realm'] = "0,example.com,21[2:5]"
859     hostapd.add_ap(apdev[0], params)
860
861     dev[0].hs20_enable()
862     dev[0].add_cred_values(default_cred())
863     interworking_select(dev[0], None, no_match=True, freq="2412")
864
865 def test_ap_hs20_eap_fast_mschapv2(dev, apdev):
866     """Hotspot 2.0 connection with FAST/EAP-MSCHAPV2"""
867     check_eap_capa(dev[0], "FAST")
868     eap_test(dev[0], apdev[0], "43[3:26]", "FAST", "user")
869
870 def test_ap_hs20_eap_fast_gtc(dev, apdev):
871     """Hotspot 2.0 connection with FAST/EAP-GTC"""
872     check_eap_capa(dev[0], "FAST")
873     eap_test(dev[0], apdev[0], "43[3:6]", "FAST", "user")
874
875 def test_ap_hs20_eap_tls(dev, apdev):
876     """Hotspot 2.0 connection with EAP-TLS"""
877     bssid = apdev[0]['bssid']
878     params = hs20_ap_params()
879     params['nai_realm'] = [ "0,example.com,13[5:6]" ]
880     hostapd.add_ap(apdev[0], params)
881
882     dev[0].hs20_enable()
883     dev[0].add_cred_values({ 'realm': "example.com",
884                              'username': "certificate-user",
885                              'ca_cert': "auth_serv/ca.pem",
886                              'client_cert': "auth_serv/user.pem",
887                              'private_key': "auth_serv/user.key"})
888     interworking_select(dev[0], bssid, freq="2412")
889     interworking_connect(dev[0], bssid, "TLS")
890
891 @remote_compatible
892 def test_ap_hs20_eap_cert_unknown(dev, apdev):
893     """Hotspot 2.0 connection with certificate, but unknown EAP method"""
894     bssid = apdev[0]['bssid']
895     params = hs20_ap_params()
896     params['nai_realm'] = [ "0,example.com,99[5:6]" ]
897     hostapd.add_ap(apdev[0], params)
898
899     dev[0].hs20_enable()
900     dev[0].add_cred_values({ 'realm': "example.com",
901                              'username': "certificate-user",
902                              'ca_cert': "auth_serv/ca.pem",
903                              'client_cert': "auth_serv/user.pem",
904                              'private_key': "auth_serv/user.key"})
905     interworking_select(dev[0], None, no_match=True, freq="2412")
906
907 @remote_compatible
908 def test_ap_hs20_eap_cert_unsupported(dev, apdev):
909     """Hotspot 2.0 connection with certificate, but unsupported TTLS"""
910     bssid = apdev[0]['bssid']
911     params = hs20_ap_params()
912     params['nai_realm'] = [ "0,example.com,21[5:6]" ]
913     hostapd.add_ap(apdev[0], params)
914
915     dev[0].hs20_enable()
916     dev[0].add_cred_values({ 'realm': "example.com",
917                              'username': "certificate-user",
918                              'ca_cert': "auth_serv/ca.pem",
919                              'client_cert': "auth_serv/user.pem",
920                              'private_key': "auth_serv/user.key"})
921     interworking_select(dev[0], None, no_match=True, freq="2412")
922
923 @remote_compatible
924 def test_ap_hs20_eap_invalid_cred(dev, apdev):
925     """Hotspot 2.0 connection with invalid cred configuration"""
926     bssid = apdev[0]['bssid']
927     params = hs20_ap_params()
928     hostapd.add_ap(apdev[0], params)
929
930     dev[0].hs20_enable()
931     dev[0].add_cred_values({ 'realm': "example.com",
932                              'username': "certificate-user",
933                              'client_cert': "auth_serv/user.pem" })
934     interworking_select(dev[0], None, no_match=True, freq="2412")
935
936 def test_ap_hs20_nai_realms(dev, apdev):
937     """Hotspot 2.0 connection and multiple NAI realms and TTLS/PAP"""
938     bssid = apdev[0]['bssid']
939     params = hs20_ap_params()
940     params['hessid'] = bssid
941     params['nai_realm'] = [ "0,no.match.here;example.com;no.match.here.either,21[2:1][5:7]" ]
942     hostapd.add_ap(apdev[0], params)
943
944     dev[0].hs20_enable()
945     id = dev[0].add_cred_values({ 'realm': "example.com",
946                                   'ca_cert': "auth_serv/ca.pem",
947                                   'username': "pap user",
948                                   'password': "password",
949                                   'domain': "example.com" })
950     interworking_select(dev[0], bssid, "home", freq="2412")
951     interworking_connect(dev[0], bssid, "TTLS")
952     check_sp_type(dev[0], "home")
953
954 def test_ap_hs20_roaming_consortium(dev, apdev):
955     """Hotspot 2.0 connection based on roaming consortium match"""
956     bssid = apdev[0]['bssid']
957     params = hs20_ap_params()
958     params['hessid'] = bssid
959     hostapd.add_ap(apdev[0], params)
960
961     dev[0].hs20_enable()
962     for consortium in [ "112233", "1020304050", "010203040506", "fedcba" ]:
963         id = dev[0].add_cred_values({ 'username': "user",
964                                       'password': "password",
965                                       'domain': "example.com",
966                                       'ca_cert': "auth_serv/ca.pem",
967                                       'roaming_consortium': consortium,
968                                       'eap': "PEAP" })
969         interworking_select(dev[0], bssid, "home", freq="2412")
970         interworking_connect(dev[0], bssid, "PEAP")
971         check_sp_type(dev[0], "home")
972         dev[0].request("INTERWORKING_SELECT auto freq=2412")
973         ev = dev[0].wait_event(["INTERWORKING-ALREADY-CONNECTED"], timeout=15)
974         if ev is None:
975             raise Exception("Timeout on already-connected event")
976         dev[0].remove_cred(id)
977
978 def test_ap_hs20_roaming_consortium_invalid(dev, apdev):
979     """Hotspot 2.0 connection and invalid roaming consortium ANQP-element"""
980     bssid = apdev[0]['bssid']
981     params = hs20_ap_params()
982     params['hessid'] = bssid
983     # Override Roaming Consortium ANQP-element with an incorrectly encoded
984     # value.
985     params['anqp_elem'] = "261:04fedcba"
986     hostapd.add_ap(apdev[0], params)
987
988     dev[0].hs20_enable()
989     id = dev[0].add_cred_values({ 'username': "user",
990                                   'password': "password",
991                                   'domain': "example.com",
992                                   'ca_cert': "auth_serv/ca.pem",
993                                   'roaming_consortium': "fedcba",
994                                   'eap': "PEAP" })
995     interworking_select(dev[0], bssid, "home", freq="2412", no_match=True)
996
997 def test_ap_hs20_roaming_consortium_element(dev, apdev):
998     """Hotspot 2.0 connection and invalid roaming consortium element"""
999     bssid = apdev[0]['bssid']
1000     params = hs20_ap_params()
1001     params['hessid'] = bssid
1002     del params['roaming_consortium']
1003     params['vendor_elements'] = '6f00'
1004     hapd = hostapd.add_ap(apdev[0], params)
1005
1006     dev[0].hs20_enable()
1007     dev[0].scan_for_bss(bssid, freq="2412")
1008     id = dev[0].add_cred_values({ 'username': "user",
1009                                   'password': "password",
1010                                   'domain': "example.com",
1011                                   'ca_cert': "auth_serv/ca.pem",
1012                                   'roaming_consortium': "112233",
1013                                   'eap': "PEAP" })
1014     interworking_select(dev[0], bssid, freq="2412", no_match=True)
1015
1016     hapd.set('vendor_elements', '6f020001')
1017     if "OK" not in hapd.request("UPDATE_BEACON"):
1018         raise Exception("UPDATE_BEACON failed")
1019     dev[0].request("BSS_FLUSH 0")
1020     dev[0].scan_for_bss(bssid, freq="2412", force_scan=True)
1021     interworking_select(dev[0], bssid, freq="2412", no_match=True)
1022
1023 def test_ap_hs20_roaming_consortium_constraints(dev, apdev):
1024     """Hotspot 2.0 connection and roaming consortium constraints"""
1025     bssid = apdev[0]['bssid']
1026     params = hs20_ap_params()
1027     params['hessid'] = bssid
1028     params['bss_load_test'] = "12:200:20000"
1029     hostapd.add_ap(apdev[0], params)
1030
1031     dev[0].hs20_enable()
1032
1033     vals = { 'username': "user",
1034              'password': "password",
1035              'domain': "example.com",
1036              'ca_cert': "auth_serv/ca.pem",
1037              'roaming_consortium': "fedcba",
1038              'eap': "TTLS" }
1039     vals2 = vals.copy()
1040     vals2['required_roaming_consortium'] = "223344"
1041     id = dev[0].add_cred_values(vals2)
1042     interworking_select(dev[0], bssid, "home", freq="2412", no_match=True)
1043     dev[0].remove_cred(id)
1044
1045     vals2 = vals.copy()
1046     vals2['min_dl_bandwidth_home'] = "65500"
1047     id = dev[0].add_cred_values(vals2)
1048     dev[0].request("INTERWORKING_SELECT freq=2412")
1049     ev = dev[0].wait_event(["INTERWORKING-AP"], timeout=15)
1050     if ev is None:
1051         raise Exception("No AP found")
1052     if "below_min_backhaul=1" not in ev:
1053         raise Exception("below_min_backhaul not reported")
1054     dev[0].remove_cred(id)
1055
1056     vals2 = vals.copy()
1057     vals2['max_bss_load'] = "100"
1058     id = dev[0].add_cred_values(vals2)
1059     dev[0].request("INTERWORKING_SELECT freq=2412")
1060     ev = dev[0].wait_event(["INTERWORKING-AP"], timeout=15)
1061     if ev is None:
1062         raise Exception("No AP found")
1063     if "over_max_bss_load=1" not in ev:
1064         raise Exception("over_max_bss_load not reported")
1065     dev[0].remove_cred(id)
1066
1067     vals2 = vals.copy()
1068     vals2['req_conn_capab'] = "6:1234"
1069     vals2['domain'] = 'example.org'
1070     id = dev[0].add_cred_values(vals2)
1071
1072     dev[0].request("INTERWORKING_SELECT freq=2412")
1073     ev = dev[0].wait_event(["INTERWORKING-AP"], timeout=15)
1074     if ev is None:
1075         raise Exception("No AP found")
1076     if "conn_capab_missing=1" not in ev:
1077         raise Exception("conn_capab_missing not reported")
1078     dev[0].remove_cred(id)
1079
1080     values = default_cred()
1081     values['roaming_consortium'] = "fedcba"
1082     id3 = dev[0].add_cred_values(values)
1083
1084     vals2 = vals.copy()
1085     vals2['roaming_consortium'] = "fedcba"
1086     vals2['priority'] = "2"
1087     id = dev[0].add_cred_values(vals2)
1088
1089     values = default_cred()
1090     values['roaming_consortium'] = "fedcba"
1091     id2 = dev[0].add_cred_values(values)
1092
1093     dev[0].request("INTERWORKING_SELECT freq=2412")
1094     ev = dev[0].wait_event(["INTERWORKING-AP"], timeout=15)
1095     if ev is None:
1096         raise Exception("No AP found")
1097     dev[0].remove_cred(id)
1098     dev[0].remove_cred(id2)
1099     dev[0].remove_cred(id3)
1100
1101 def test_ap_hs20_3gpp_constraints(dev, apdev):
1102     """Hotspot 2.0 connection and 3GPP credential constraints"""
1103     bssid = apdev[0]['bssid']
1104     params = hs20_ap_params()
1105     params['hessid'] = bssid
1106     params['anqp_3gpp_cell_net'] = "555,444"
1107     params['domain_name'] = "wlan.mnc444.mcc555.3gppnetwork.org"
1108     params['bss_load_test'] = "12:200:20000"
1109     hapd = hostapd.add_ap(apdev[0], params)
1110
1111     dev[0].hs20_enable()
1112
1113     vals = { 'imsi': "555444-333222111",
1114              'eap': "SIM",
1115              'milenage': "5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123" }
1116     vals2 = vals.copy()
1117     vals2['required_roaming_consortium'] = "223344"
1118     id = dev[0].add_cred_values(vals2)
1119     interworking_select(dev[0], bssid, "home", freq="2412", no_match=True)
1120     dev[0].remove_cred(id)
1121
1122     vals2 = vals.copy()
1123     vals2['min_dl_bandwidth_home'] = "65500"
1124     id = dev[0].add_cred_values(vals2)
1125     dev[0].request("INTERWORKING_SELECT freq=2412")
1126     ev = dev[0].wait_event(["INTERWORKING-AP"], timeout=15)
1127     if ev is None:
1128         raise Exception("No AP found")
1129     if "below_min_backhaul=1" not in ev:
1130         raise Exception("below_min_backhaul not reported")
1131     dev[0].remove_cred(id)
1132
1133     vals2 = vals.copy()
1134     vals2['max_bss_load'] = "100"
1135     id = dev[0].add_cred_values(vals2)
1136     dev[0].request("INTERWORKING_SELECT freq=2412")
1137     ev = dev[0].wait_event(["INTERWORKING-AP"], timeout=15)
1138     if ev is None:
1139         raise Exception("No AP found")
1140     if "over_max_bss_load=1" not in ev:
1141         raise Exception("over_max_bss_load not reported")
1142     dev[0].remove_cred(id)
1143
1144     values = default_cred()
1145     values['roaming_consortium'] = "fedcba"
1146     id3 = dev[0].add_cred_values(values)
1147
1148     vals2 = vals.copy()
1149     vals2['roaming_consortium'] = "fedcba"
1150     vals2['priority'] = "2"
1151     id = dev[0].add_cred_values(vals2)
1152
1153     values = default_cred()
1154     values['roaming_consortium'] = "fedcba"
1155     id2 = dev[0].add_cred_values(values)
1156
1157     dev[0].request("INTERWORKING_SELECT freq=2412")
1158     ev = dev[0].wait_event(["INTERWORKING-AP"], timeout=15)
1159     if ev is None:
1160         raise Exception("No AP found")
1161     dev[0].remove_cred(id)
1162     dev[0].remove_cred(id2)
1163     dev[0].remove_cred(id3)
1164
1165     hapd.disable()
1166     params = hs20_ap_params()
1167     params['hessid'] = bssid
1168     params['anqp_3gpp_cell_net'] = "555,444"
1169     params['bss_load_test'] = "12:200:20000"
1170     hapd = hostapd.add_ap(apdev[0], params)
1171     vals2 = vals.copy()
1172     vals2['req_conn_capab'] = "6:1234"
1173     id = dev[0].add_cred_values(vals2)
1174     dev[0].request("INTERWORKING_SELECT freq=2412")
1175     ev = dev[0].wait_event(["INTERWORKING-AP"], timeout=15)
1176     if ev is None:
1177         raise Exception("No AP found")
1178     if "conn_capab_missing=1" not in ev:
1179         raise Exception("conn_capab_missing not reported")
1180     dev[0].remove_cred(id)
1181
1182 def test_ap_hs20_connect_no_full_match(dev, apdev):
1183     """Hotspot 2.0 connection and no full match"""
1184     bssid = apdev[0]['bssid']
1185     params = hs20_ap_params()
1186     params['hessid'] = bssid
1187     params['anqp_3gpp_cell_net'] = "555,444"
1188     hostapd.add_ap(apdev[0], params)
1189
1190     dev[0].hs20_enable()
1191
1192     vals = { 'username': "user",
1193              'password': "password",
1194              'domain': "example.com",
1195              'ca_cert': "auth_serv/ca.pem",
1196              'roaming_consortium': "fedcba",
1197              'eap': "TTLS",
1198              'min_dl_bandwidth_home': "65500" }
1199     id = dev[0].add_cred_values(vals)
1200     dev[0].request("INTERWORKING_SELECT freq=2412")
1201     ev = dev[0].wait_event(["INTERWORKING-AP"], timeout=15)
1202     if ev is None:
1203         raise Exception("No AP found")
1204     if "below_min_backhaul=1" not in ev:
1205         raise Exception("below_min_backhaul not reported")
1206     interworking_connect(dev[0], bssid, "TTLS")
1207     dev[0].remove_cred(id)
1208     dev[0].wait_disconnected()
1209
1210     vals = { 'imsi': "555444-333222111", 'eap': "SIM",
1211              'milenage': "5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123",
1212              'min_dl_bandwidth_roaming': "65500" }
1213     id = dev[0].add_cred_values(vals)
1214     dev[0].request("INTERWORKING_SELECT freq=2412")
1215     ev = dev[0].wait_event(["INTERWORKING-AP"], timeout=15)
1216     if ev is None:
1217         raise Exception("No AP found")
1218     if "below_min_backhaul=1" not in ev:
1219         raise Exception("below_min_backhaul not reported")
1220     interworking_connect(dev[0], bssid, "SIM")
1221     dev[0].remove_cred(id)
1222     dev[0].wait_disconnected()
1223
1224 def test_ap_hs20_username_roaming(dev, apdev):
1225     """Hotspot 2.0 connection in username/password credential (roaming)"""
1226     check_eap_capa(dev[0], "MSCHAPV2")
1227     bssid = apdev[0]['bssid']
1228     params = hs20_ap_params()
1229     params['nai_realm'] = [ "0,example.com,13[5:6],21[2:4][5:7]",
1230                             "0,roaming.example.com,21[2:4][5:7]",
1231                             "0,another.example.com" ]
1232     params['domain_name'] = "another.example.com"
1233     params['hessid'] = bssid
1234     hostapd.add_ap(apdev[0], params)
1235
1236     dev[0].hs20_enable()
1237     id = dev[0].add_cred_values({ 'realm': "roaming.example.com",
1238                                   'username': "hs20-test",
1239                                   'password': "password",
1240                                   'ca_cert': "auth_serv/ca.pem",
1241                                   'domain': "example.com" })
1242     interworking_select(dev[0], bssid, "roaming", freq="2412")
1243     interworking_connect(dev[0], bssid, "TTLS")
1244     check_sp_type(dev[0], "roaming")
1245
1246 def test_ap_hs20_username_unknown(dev, apdev):
1247     """Hotspot 2.0 connection in username/password credential (no domain in cred)"""
1248     check_eap_capa(dev[0], "MSCHAPV2")
1249     bssid = apdev[0]['bssid']
1250     params = hs20_ap_params()
1251     params['hessid'] = bssid
1252     hostapd.add_ap(apdev[0], params)
1253
1254     dev[0].hs20_enable()
1255     id = dev[0].add_cred_values({ 'realm': "example.com",
1256                                   'ca_cert': "auth_serv/ca.pem",
1257                                   'username': "hs20-test",
1258                                   'password': "password" })
1259     interworking_select(dev[0], bssid, "unknown", freq="2412")
1260     interworking_connect(dev[0], bssid, "TTLS")
1261     check_sp_type(dev[0], "unknown")
1262
1263 def test_ap_hs20_username_unknown2(dev, apdev):
1264     """Hotspot 2.0 connection in username/password credential (no domain advertized)"""
1265     check_eap_capa(dev[0], "MSCHAPV2")
1266     bssid = apdev[0]['bssid']
1267     params = hs20_ap_params()
1268     params['hessid'] = bssid
1269     del params['domain_name']
1270     hostapd.add_ap(apdev[0], params)
1271
1272     dev[0].hs20_enable()
1273     id = dev[0].add_cred_values({ 'realm': "example.com",
1274                                   'ca_cert': "auth_serv/ca.pem",
1275                                   'username': "hs20-test",
1276                                   'password': "password",
1277                                   'domain': "example.com" })
1278     interworking_select(dev[0], bssid, "unknown", freq="2412")
1279     interworking_connect(dev[0], bssid, "TTLS")
1280     check_sp_type(dev[0], "unknown")
1281
1282 def test_ap_hs20_gas_while_associated(dev, apdev):
1283     """Hotspot 2.0 connection with GAS query while associated"""
1284     check_eap_capa(dev[0], "MSCHAPV2")
1285     bssid = apdev[0]['bssid']
1286     params = hs20_ap_params()
1287     params['hessid'] = bssid
1288     hostapd.add_ap(apdev[0], params)
1289
1290     dev[0].hs20_enable()
1291     id = dev[0].add_cred_values({ 'realm': "example.com",
1292                                   'ca_cert': "auth_serv/ca.pem",
1293                                   'username': "hs20-test",
1294                                   'password': "password",
1295                                   'domain': "example.com" })
1296     interworking_select(dev[0], bssid, "home", freq="2412")
1297     interworking_connect(dev[0], bssid, "TTLS")
1298
1299     logger.info("Verifying GAS query while associated")
1300     dev[0].request("FETCH_ANQP")
1301     for i in range(0, 6):
1302         ev = dev[0].wait_event(["RX-ANQP"], timeout=5)
1303         if ev is None:
1304             raise Exception("Operation timed out")
1305
1306 def test_ap_hs20_gas_with_another_ap_while_associated(dev, apdev):
1307     """GAS query with another AP while associated"""
1308     check_eap_capa(dev[0], "MSCHAPV2")
1309     bssid = apdev[0]['bssid']
1310     params = hs20_ap_params()
1311     params['hessid'] = bssid
1312     hostapd.add_ap(apdev[0], params)
1313
1314     bssid2 = apdev[1]['bssid']
1315     params = hs20_ap_params()
1316     params['hessid'] = bssid2
1317     params['nai_realm'] = [ "0,no-match.example.org,13[5:6],21[2:4][5:7]" ]
1318     hostapd.add_ap(apdev[1], params)
1319
1320     dev[0].hs20_enable()
1321     id = dev[0].add_cred_values({ 'realm': "example.com",
1322                                   'ca_cert': "auth_serv/ca.pem",
1323                                   'username': "hs20-test",
1324                                   'password': "password",
1325                                   'domain': "example.com" })
1326     interworking_select(dev[0], bssid, "home", freq="2412")
1327     interworking_connect(dev[0], bssid, "TTLS")
1328     dev[0].dump_monitor()
1329
1330     logger.info("Verifying GAS query with same AP while associated")
1331     dev[0].request("ANQP_GET " + bssid + " 263")
1332     ev = dev[0].wait_event(["RX-ANQP"], timeout=5)
1333     if ev is None:
1334         raise Exception("ANQP operation timed out")
1335     dev[0].dump_monitor()
1336
1337     logger.info("Verifying GAS query with another AP while associated")
1338     dev[0].scan_for_bss(bssid2, 2412)
1339     dev[0].request("ANQP_GET " + bssid2 + " 263")
1340     ev = dev[0].wait_event(["RX-ANQP"], timeout=5)
1341     if ev is None:
1342         raise Exception("ANQP operation timed out")
1343
1344 def test_ap_hs20_gas_while_associated_with_pmf(dev, apdev):
1345     """Hotspot 2.0 connection with GAS query while associated and using PMF"""
1346     check_eap_capa(dev[0], "MSCHAPV2")
1347     try:
1348         _test_ap_hs20_gas_while_associated_with_pmf(dev, apdev)
1349     finally:
1350         dev[0].request("SET pmf 0")
1351
1352 def _test_ap_hs20_gas_while_associated_with_pmf(dev, apdev):
1353     bssid = apdev[0]['bssid']
1354     params = hs20_ap_params()
1355     params['hessid'] = bssid
1356     hostapd.add_ap(apdev[0], params)
1357
1358     bssid2 = apdev[1]['bssid']
1359     params = hs20_ap_params()
1360     params['hessid'] = bssid2
1361     params['nai_realm'] = [ "0,no-match.example.org,13[5:6],21[2:4][5:7]" ]
1362     hostapd.add_ap(apdev[1], params)
1363
1364     dev[0].hs20_enable()
1365     dev[0].request("SET pmf 2")
1366     id = dev[0].add_cred_values({ 'realm': "example.com",
1367                                   'ca_cert': "auth_serv/ca.pem",
1368                                   'username': "hs20-test",
1369                                   'password': "password",
1370                                   'domain': "example.com" })
1371     interworking_select(dev[0], bssid, "home", freq="2412")
1372     interworking_connect(dev[0], bssid, "TTLS")
1373
1374     logger.info("Verifying GAS query while associated")
1375     dev[0].request("FETCH_ANQP")
1376     for i in range(0, 2 * 6):
1377         ev = dev[0].wait_event(["RX-ANQP"], timeout=5)
1378         if ev is None:
1379             raise Exception("Operation timed out")
1380
1381 def test_ap_hs20_gas_with_another_ap_while_using_pmf(dev, apdev):
1382     """GAS query with another AP while associated and using PMF"""
1383     check_eap_capa(dev[0], "MSCHAPV2")
1384     try:
1385         _test_ap_hs20_gas_with_another_ap_while_using_pmf(dev, apdev)
1386     finally:
1387         dev[0].request("SET pmf 0")
1388
1389 def _test_ap_hs20_gas_with_another_ap_while_using_pmf(dev, apdev):
1390     bssid = apdev[0]['bssid']
1391     params = hs20_ap_params()
1392     params['hessid'] = bssid
1393     hostapd.add_ap(apdev[0], params)
1394
1395     bssid2 = apdev[1]['bssid']
1396     params = hs20_ap_params()
1397     params['hessid'] = bssid2
1398     params['nai_realm'] = [ "0,no-match.example.org,13[5:6],21[2:4][5:7]" ]
1399     hostapd.add_ap(apdev[1], params)
1400
1401     dev[0].hs20_enable()
1402     dev[0].request("SET pmf 2")
1403     id = dev[0].add_cred_values({ 'realm': "example.com",
1404                                   'ca_cert': "auth_serv/ca.pem",
1405                                   'username': "hs20-test",
1406                                   'password': "password",
1407                                   'domain': "example.com" })
1408     interworking_select(dev[0], bssid, "home", freq="2412")
1409     interworking_connect(dev[0], bssid, "TTLS")
1410     dev[0].dump_monitor()
1411
1412     logger.info("Verifying GAS query with same AP while associated")
1413     dev[0].request("ANQP_GET " + bssid + " 263")
1414     ev = dev[0].wait_event(["RX-ANQP"], timeout=5)
1415     if ev is None:
1416         raise Exception("ANQP operation timed out")
1417     dev[0].dump_monitor()
1418
1419     logger.info("Verifying GAS query with another AP while associated")
1420     dev[0].scan_for_bss(bssid2, 2412)
1421     dev[0].request("ANQP_GET " + bssid2 + " 263")
1422     ev = dev[0].wait_event(["RX-ANQP"], timeout=5)
1423     if ev is None:
1424         raise Exception("ANQP operation timed out")
1425
1426 def test_ap_hs20_gas_frag_while_associated(dev, apdev):
1427     """Hotspot 2.0 connection with fragmented GAS query while associated"""
1428     check_eap_capa(dev[0], "MSCHAPV2")
1429     bssid = apdev[0]['bssid']
1430     params = hs20_ap_params()
1431     params['hessid'] = bssid
1432     hapd = hostapd.add_ap(apdev[0], params)
1433     hapd.set("gas_frag_limit", "50")
1434
1435     dev[0].hs20_enable()
1436     id = dev[0].add_cred_values({ 'realm': "example.com",
1437                                   'ca_cert': "auth_serv/ca.pem",
1438                                   'username': "hs20-test",
1439                                   'password': "password",
1440                                   'domain': "example.com" })
1441     interworking_select(dev[0], bssid, "home", freq="2412")
1442     interworking_connect(dev[0], bssid, "TTLS")
1443
1444     logger.info("Verifying GAS query while associated")
1445     dev[0].request("FETCH_ANQP")
1446     for i in range(0, 6):
1447         ev = dev[0].wait_event(["RX-ANQP"], timeout=5)
1448         if ev is None:
1449             raise Exception("Operation timed out")
1450
1451 def test_ap_hs20_multiple_connects(dev, apdev):
1452     """Hotspot 2.0 connection through multiple network selections"""
1453     check_eap_capa(dev[0], "MSCHAPV2")
1454     bssid = apdev[0]['bssid']
1455     params = hs20_ap_params()
1456     params['hessid'] = bssid
1457     hostapd.add_ap(apdev[0], params)
1458
1459     dev[0].hs20_enable()
1460     values = { 'realm': "example.com",
1461                'ca_cert': "auth_serv/ca.pem",
1462                'username': "hs20-test",
1463                'password': "password",
1464                'domain': "example.com" }
1465     id = dev[0].add_cred_values(values)
1466
1467     dev[0].scan_for_bss(bssid, freq="2412")
1468
1469     for i in range(0, 3):
1470         logger.info("Starting Interworking network selection")
1471         dev[0].request("INTERWORKING_SELECT auto freq=2412")
1472         while True:
1473             ev = dev[0].wait_event(["INTERWORKING-NO-MATCH",
1474                                     "INTERWORKING-ALREADY-CONNECTED",
1475                                     "CTRL-EVENT-CONNECTED"], timeout=15)
1476             if ev is None:
1477                 raise Exception("Connection timed out")
1478             if "INTERWORKING-NO-MATCH" in ev:
1479                 raise Exception("Matching AP not found")
1480             if "CTRL-EVENT-CONNECTED" in ev:
1481                 break
1482             if i == 2 and "INTERWORKING-ALREADY-CONNECTED" in ev:
1483                 break
1484         if i == 0:
1485             dev[0].request("DISCONNECT")
1486         dev[0].dump_monitor()
1487
1488     networks = dev[0].list_networks()
1489     if len(networks) > 1:
1490         raise Exception("Duplicated network block detected")
1491
1492 def test_ap_hs20_disallow_aps(dev, apdev):
1493     """Hotspot 2.0 connection and disallow_aps"""
1494     bssid = apdev[0]['bssid']
1495     params = hs20_ap_params()
1496     params['hessid'] = bssid
1497     hostapd.add_ap(apdev[0], params)
1498
1499     dev[0].hs20_enable()
1500     values = { 'realm': "example.com",
1501                'ca_cert': "auth_serv/ca.pem",
1502                'username': "hs20-test",
1503                'password': "password",
1504                'domain': "example.com" }
1505     id = dev[0].add_cred_values(values)
1506
1507     dev[0].scan_for_bss(bssid, freq="2412")
1508
1509     logger.info("Verify disallow_aps bssid")
1510     dev[0].request("SET disallow_aps bssid " + bssid.translate(None, ':'))
1511     dev[0].request("INTERWORKING_SELECT auto")
1512     ev = dev[0].wait_event(["INTERWORKING-NO-MATCH"], timeout=15)
1513     if ev is None:
1514         raise Exception("Network selection timed out")
1515     dev[0].dump_monitor()
1516
1517     logger.info("Verify disallow_aps ssid")
1518     dev[0].request("SET disallow_aps ssid 746573742d68733230")
1519     dev[0].request("INTERWORKING_SELECT auto freq=2412")
1520     ev = dev[0].wait_event(["INTERWORKING-NO-MATCH"], timeout=15)
1521     if ev is None:
1522         raise Exception("Network selection timed out")
1523     dev[0].dump_monitor()
1524
1525     logger.info("Verify disallow_aps clear")
1526     dev[0].request("SET disallow_aps ")
1527     interworking_select(dev[0], bssid, "home", freq="2412")
1528
1529     dev[0].request("SET disallow_aps bssid " + bssid.translate(None, ':'))
1530     ret = dev[0].request("INTERWORKING_CONNECT " + bssid)
1531     if "FAIL" not in ret:
1532         raise Exception("INTERWORKING_CONNECT to disallowed BSS not rejected")
1533
1534     if "FAIL" not in dev[0].request("INTERWORKING_CONNECT foo"):
1535         raise Exception("Invalid INTERWORKING_CONNECT not rejected")
1536     if "FAIL" not in dev[0].request("INTERWORKING_CONNECT 00:11:22:33:44:55"):
1537         raise Exception("Invalid INTERWORKING_CONNECT not rejected")
1538
1539 def policy_test(dev, ap, values, only_one=True):
1540     dev.dump_monitor()
1541     if ap:
1542         logger.info("Verify network selection to AP " + ap['ifname'])
1543         bssid = ap['bssid']
1544         dev.scan_for_bss(bssid, freq="2412")
1545     else:
1546         logger.info("Verify network selection")
1547         bssid = None
1548     dev.hs20_enable()
1549     id = dev.add_cred_values(values)
1550     dev.request("INTERWORKING_SELECT auto freq=2412")
1551     events = []
1552     while True:
1553         ev = dev.wait_event(["INTERWORKING-AP", "INTERWORKING-NO-MATCH",
1554                              "INTERWORKING-BLACKLISTED",
1555                              "INTERWORKING-SELECTED"], timeout=15)
1556         if ev is None:
1557             raise Exception("Network selection timed out")
1558         events.append(ev)
1559         if "INTERWORKING-NO-MATCH" in ev:
1560             raise Exception("Matching AP not found")
1561         if bssid and only_one and "INTERWORKING-AP" in ev and bssid not in ev:
1562             raise Exception("Unexpected AP claimed acceptable")
1563         if "INTERWORKING-SELECTED" in ev:
1564             if bssid and bssid not in ev:
1565                 raise Exception("Selected incorrect BSS")
1566             break
1567
1568     ev = dev.wait_connected(timeout=15)
1569     if bssid and bssid not in ev:
1570         raise Exception("Connected to incorrect BSS")
1571
1572     conn_bssid = dev.get_status_field("bssid")
1573     if bssid and conn_bssid != bssid:
1574         raise Exception("bssid information points to incorrect BSS")
1575
1576     dev.remove_cred(id)
1577     dev.dump_monitor()
1578     return events
1579
1580 def default_cred(domain=None, user="hs20-test"):
1581     cred = { 'realm': "example.com",
1582              'ca_cert': "auth_serv/ca.pem",
1583              'username': user,
1584              'password': "password" }
1585     if domain:
1586         cred['domain'] = domain
1587     return cred
1588
1589 def test_ap_hs20_prefer_home(dev, apdev):
1590     """Hotspot 2.0 required roaming consortium"""
1591     check_eap_capa(dev[0], "MSCHAPV2")
1592     params = hs20_ap_params()
1593     params['domain_name'] = "example.org"
1594     hostapd.add_ap(apdev[0], params)
1595
1596     params = hs20_ap_params()
1597     params['ssid'] = "test-hs20-other"
1598     params['domain_name'] = "example.com"
1599     hostapd.add_ap(apdev[1], params)
1600
1601     values = default_cred()
1602     values['domain'] = "example.com"
1603     policy_test(dev[0], apdev[1], values, only_one=False)
1604     values['domain'] = "example.org"
1605     policy_test(dev[0], apdev[0], values, only_one=False)
1606
1607 def test_ap_hs20_req_roaming_consortium(dev, apdev):
1608     """Hotspot 2.0 required roaming consortium"""
1609     check_eap_capa(dev[0], "MSCHAPV2")
1610     params = hs20_ap_params()
1611     hostapd.add_ap(apdev[0], params)
1612
1613     params = hs20_ap_params()
1614     params['ssid'] = "test-hs20-other"
1615     params['roaming_consortium'] = [ "223344" ]
1616     hostapd.add_ap(apdev[1], params)
1617
1618     values = default_cred()
1619     values['required_roaming_consortium'] = "223344"
1620     policy_test(dev[0], apdev[1], values)
1621     values['required_roaming_consortium'] = "112233"
1622     policy_test(dev[0], apdev[0], values)
1623
1624     id = dev[0].add_cred()
1625     dev[0].set_cred(id, "required_roaming_consortium", "112233")
1626     dev[0].set_cred(id, "required_roaming_consortium", "112233445566778899aabbccddeeff")
1627
1628     for val in [ "", "1", "11", "1122", "1122334", "112233445566778899aabbccddeeff00" ]:
1629         if "FAIL" not in dev[0].request('SET_CRED {} required_roaming_consortium {}'.format(id, val)):
1630             raise Exception("Invalid roaming consortium value accepted: " + val)
1631
1632 def test_ap_hs20_req_roaming_consortium_no_match(dev, apdev):
1633     """Hotspot 2.0 required roaming consortium and no match"""
1634     check_eap_capa(dev[0], "MSCHAPV2")
1635     params = hs20_ap_params()
1636     del params['roaming_consortium']
1637     hostapd.add_ap(apdev[0], params)
1638
1639     params = hs20_ap_params()
1640     params['ssid'] = "test-hs20-other"
1641     params['roaming_consortium'] = [ "223345" ]
1642     hostapd.add_ap(apdev[1], params)
1643
1644     values = default_cred()
1645     values['required_roaming_consortium'] = "223344"
1646     dev[0].hs20_enable()
1647     id = dev[0].add_cred_values(values)
1648     dev[0].request("INTERWORKING_SELECT auto freq=2412")
1649     ev = dev[0].wait_event(["INTERWORKING-NO-MATCH"], timeout=10)
1650     if ev is None:
1651         raise Exception("INTERWORKING-NO-MATCH not reported")
1652
1653 def test_ap_hs20_excluded_ssid(dev, apdev):
1654     """Hotspot 2.0 exclusion based on SSID"""
1655     check_eap_capa(dev[0], "MSCHAPV2")
1656     params = hs20_ap_params()
1657     params['roaming_consortium'] = [ "223344" ]
1658     params['anqp_3gpp_cell_net'] = "555,444"
1659     hostapd.add_ap(apdev[0], params)
1660
1661     params = hs20_ap_params()
1662     params['ssid'] = "test-hs20-other"
1663     params['roaming_consortium'] = [ "223344" ]
1664     params['anqp_3gpp_cell_net'] = "555,444"
1665     hostapd.add_ap(apdev[1], params)
1666
1667     values = default_cred()
1668     values['excluded_ssid'] = "test-hs20"
1669     events = policy_test(dev[0], apdev[1], values)
1670     ev = [e for e in events if "INTERWORKING-BLACKLISTED " + apdev[0]['bssid'] in e]
1671     if len(ev) != 1:
1672         raise Exception("Excluded network not reported")
1673     values['excluded_ssid'] = "test-hs20-other"
1674     events = policy_test(dev[0], apdev[0], values)
1675     ev = [e for e in events if "INTERWORKING-BLACKLISTED " + apdev[1]['bssid'] in e]
1676     if len(ev) != 1:
1677         raise Exception("Excluded network not reported")
1678
1679     values = default_cred()
1680     values['roaming_consortium'] = "223344"
1681     values['eap'] = "TTLS"
1682     values['phase2'] = "auth=MSCHAPV2"
1683     values['excluded_ssid'] = "test-hs20"
1684     events = policy_test(dev[0], apdev[1], values)
1685     ev = [e for e in events if "INTERWORKING-BLACKLISTED " + apdev[0]['bssid'] in e]
1686     if len(ev) != 1:
1687         raise Exception("Excluded network not reported")
1688
1689     values = { 'imsi': "555444-333222111", 'eap': "SIM",
1690                'milenage': "5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123",
1691                'excluded_ssid': "test-hs20" }
1692     events = policy_test(dev[0], apdev[1], values)
1693     ev = [e for e in events if "INTERWORKING-BLACKLISTED " + apdev[0]['bssid'] in e]
1694     if len(ev) != 1:
1695         raise Exception("Excluded network not reported")
1696
1697 def test_ap_hs20_roam_to_higher_prio(dev, apdev):
1698     """Hotspot 2.0 and roaming from current to higher priority network"""
1699     check_eap_capa(dev[0], "MSCHAPV2")
1700     bssid = apdev[0]['bssid']
1701     params = hs20_ap_params(ssid="test-hs20-visited")
1702     params['domain_name'] = "visited.example.org"
1703     hostapd.add_ap(apdev[0], params)
1704
1705     dev[0].hs20_enable()
1706     id = dev[0].add_cred_values({ 'realm': "example.com",
1707                                   'ca_cert': "auth_serv/ca.pem",
1708                                   'username': "hs20-test",
1709                                   'password': "password",
1710                                   'domain': "example.com" })
1711     logger.info("Connect to the only network option")
1712     interworking_select(dev[0], bssid, "roaming", freq="2412")
1713     dev[0].dump_monitor()
1714     interworking_connect(dev[0], bssid, "TTLS")
1715
1716     logger.info("Start another AP (home operator) and reconnect")
1717     bssid2 = apdev[1]['bssid']
1718     params = hs20_ap_params(ssid="test-hs20-home")
1719     params['domain_name'] = "example.com"
1720     hostapd.add_ap(apdev[1], params)
1721
1722     dev[0].scan_for_bss(bssid2, freq="2412", force_scan=True)
1723     dev[0].request("INTERWORKING_SELECT auto freq=2412")
1724     ev = dev[0].wait_event(["INTERWORKING-NO-MATCH",
1725                             "INTERWORKING-ALREADY-CONNECTED",
1726                             "CTRL-EVENT-CONNECTED"], timeout=15)
1727     if ev is None:
1728         raise Exception("Connection timed out")
1729     if "INTERWORKING-NO-MATCH" in ev:
1730         raise Exception("Matching AP not found")
1731     if "INTERWORKING-ALREADY-CONNECTED" in ev:
1732         raise Exception("Unexpected AP selected")
1733     if bssid2 not in ev:
1734         raise Exception("Unexpected BSSID after reconnection")
1735
1736 def test_ap_hs20_domain_suffix_match_full(dev, apdev):
1737     """Hotspot 2.0 and domain_suffix_match"""
1738     check_domain_match_full(dev[0])
1739     check_eap_capa(dev[0], "MSCHAPV2")
1740     bssid = apdev[0]['bssid']
1741     params = hs20_ap_params()
1742     hostapd.add_ap(apdev[0], params)
1743
1744     dev[0].hs20_enable()
1745     id = dev[0].add_cred_values({ 'realm': "example.com",
1746                                   'username': "hs20-test",
1747                                   'password': "password",
1748                                   'ca_cert': "auth_serv/ca.pem",
1749                                   'domain': "example.com",
1750                                   'domain_suffix_match': "server.w1.fi" })
1751     interworking_select(dev[0], bssid, "home", freq="2412")
1752     dev[0].dump_monitor()
1753     interworking_connect(dev[0], bssid, "TTLS")
1754     dev[0].request("REMOVE_NETWORK all")
1755     dev[0].dump_monitor()
1756
1757     dev[0].set_cred_quoted(id, "domain_suffix_match", "no-match.example.com")
1758     interworking_select(dev[0], bssid, "home", freq="2412")
1759     dev[0].dump_monitor()
1760     dev[0].request("INTERWORKING_CONNECT " + bssid)
1761     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"])
1762     if ev is None:
1763         raise Exception("TLS certificate error not reported")
1764     if "Domain suffix mismatch" not in ev:
1765         raise Exception("Domain suffix mismatch not reported")
1766
1767 def test_ap_hs20_domain_suffix_match(dev, apdev):
1768     """Hotspot 2.0 and domain_suffix_match"""
1769     check_eap_capa(dev[0], "MSCHAPV2")
1770     check_domain_match_full(dev[0])
1771     bssid = apdev[0]['bssid']
1772     params = hs20_ap_params()
1773     hostapd.add_ap(apdev[0], params)
1774
1775     dev[0].hs20_enable()
1776     id = dev[0].add_cred_values({ 'realm': "example.com",
1777                                   'username': "hs20-test",
1778                                   'password': "password",
1779                                   'ca_cert': "auth_serv/ca.pem",
1780                                   'domain': "example.com",
1781                                   'domain_suffix_match': "w1.fi" })
1782     interworking_select(dev[0], bssid, "home", freq="2412")
1783     dev[0].dump_monitor()
1784     interworking_connect(dev[0], bssid, "TTLS")
1785
1786 def test_ap_hs20_roaming_partner_preference(dev, apdev):
1787     """Hotspot 2.0 and roaming partner preference"""
1788     check_eap_capa(dev[0], "MSCHAPV2")
1789     params = hs20_ap_params()
1790     params['domain_name'] = "roaming.example.org"
1791     hostapd.add_ap(apdev[0], params)
1792
1793     params = hs20_ap_params()
1794     params['ssid'] = "test-hs20-other"
1795     params['domain_name'] = "roaming.example.net"
1796     hostapd.add_ap(apdev[1], params)
1797
1798     logger.info("Verify default vs. specified preference")
1799     values = default_cred()
1800     values['roaming_partner'] = "roaming.example.net,1,127,*"
1801     policy_test(dev[0], apdev[1], values, only_one=False)
1802     values['roaming_partner'] = "roaming.example.net,1,129,*"
1803     policy_test(dev[0], apdev[0], values, only_one=False)
1804
1805     logger.info("Verify partial FQDN match")
1806     values['roaming_partner'] = "example.net,0,0,*"
1807     policy_test(dev[0], apdev[1], values, only_one=False)
1808     values['roaming_partner'] = "example.net,0,255,*"
1809     policy_test(dev[0], apdev[0], values, only_one=False)
1810
1811 def test_ap_hs20_max_bss_load(dev, apdev):
1812     """Hotspot 2.0 and maximum BSS load"""
1813     check_eap_capa(dev[0], "MSCHAPV2")
1814     params = hs20_ap_params()
1815     params['bss_load_test'] = "12:200:20000"
1816     hostapd.add_ap(apdev[0], params)
1817
1818     params = hs20_ap_params()
1819     params['ssid'] = "test-hs20-other"
1820     params['bss_load_test'] = "5:20:10000"
1821     hostapd.add_ap(apdev[1], params)
1822
1823     logger.info("Verify maximum BSS load constraint")
1824     values = default_cred()
1825     values['domain'] = "example.com"
1826     values['max_bss_load'] = "100"
1827     events = policy_test(dev[0], apdev[1], values, only_one=False)
1828
1829     ev = [e for e in events if "INTERWORKING-AP " + apdev[0]['bssid'] in e]
1830     if len(ev) != 1 or "over_max_bss_load=1" not in ev[0]:
1831         raise Exception("Maximum BSS Load case not noticed")
1832     ev = [e for e in events if "INTERWORKING-AP " + apdev[1]['bssid'] in e]
1833     if len(ev) != 1 or "over_max_bss_load=1" in ev[0]:
1834         raise Exception("Maximum BSS Load case reported incorrectly")
1835
1836     logger.info("Verify maximum BSS load does not prevent connection")
1837     values['max_bss_load'] = "1"
1838     events = policy_test(dev[0], None, values)
1839
1840     ev = [e for e in events if "INTERWORKING-AP " + apdev[0]['bssid'] in e]
1841     if len(ev) != 1 or "over_max_bss_load=1" not in ev[0]:
1842         raise Exception("Maximum BSS Load case not noticed")
1843     ev = [e for e in events if "INTERWORKING-AP " + apdev[1]['bssid'] in e]
1844     if len(ev) != 1 or "over_max_bss_load=1" not in ev[0]:
1845         raise Exception("Maximum BSS Load case not noticed")
1846
1847 def test_ap_hs20_max_bss_load2(dev, apdev):
1848     """Hotspot 2.0 and maximum BSS load with one AP not advertising"""
1849     check_eap_capa(dev[0], "MSCHAPV2")
1850     params = hs20_ap_params()
1851     params['bss_load_test'] = "12:200:20000"
1852     hostapd.add_ap(apdev[0], params)
1853
1854     params = hs20_ap_params()
1855     params['ssid'] = "test-hs20-other"
1856     hostapd.add_ap(apdev[1], params)
1857
1858     logger.info("Verify maximum BSS load constraint with AP advertisement")
1859     values = default_cred()
1860     values['domain'] = "example.com"
1861     values['max_bss_load'] = "100"
1862     events = policy_test(dev[0], apdev[1], values, only_one=False)
1863
1864     ev = [e for e in events if "INTERWORKING-AP " + apdev[0]['bssid'] in e]
1865     if len(ev) != 1 or "over_max_bss_load=1" not in ev[0]:
1866         raise Exception("Maximum BSS Load case not noticed")
1867     ev = [e for e in events if "INTERWORKING-AP " + apdev[1]['bssid'] in e]
1868     if len(ev) != 1 or "over_max_bss_load=1" in ev[0]:
1869         raise Exception("Maximum BSS Load case reported incorrectly")
1870
1871 def test_ap_hs20_max_bss_load_roaming(dev, apdev):
1872     """Hotspot 2.0 and maximum BSS load (roaming)"""
1873     check_eap_capa(dev[0], "MSCHAPV2")
1874     params = hs20_ap_params()
1875     params['bss_load_test'] = "12:200:20000"
1876     hostapd.add_ap(apdev[0], params)
1877
1878     values = default_cred()
1879     values['domain'] = "roaming.example.com"
1880     values['max_bss_load'] = "100"
1881     events = policy_test(dev[0], apdev[0], values, only_one=True)
1882     ev = [e for e in events if "INTERWORKING-AP " + apdev[0]['bssid'] in e]
1883     if len(ev) != 1:
1884         raise Exception("No INTERWORKING-AP event")
1885     if "over_max_bss_load=1" in ev[0]:
1886         raise Exception("Maximum BSS Load reported for roaming")
1887
1888 def test_ap_hs20_multi_cred_sp_prio(dev, apdev):
1889     """Hotspot 2.0 multi-cred sp_priority"""
1890     check_eap_capa(dev[0], "MSCHAPV2")
1891     try:
1892         _test_ap_hs20_multi_cred_sp_prio(dev, apdev)
1893     finally:
1894         dev[0].request("SET external_sim 0")
1895
1896 def _test_ap_hs20_multi_cred_sp_prio(dev, apdev):
1897     hlr_auc_gw_available()
1898     bssid = apdev[0]['bssid']
1899     params = hs20_ap_params()
1900     params['hessid'] = bssid
1901     del params['domain_name']
1902     params['anqp_3gpp_cell_net'] = "232,01"
1903     hostapd.add_ap(apdev[0], params)
1904
1905     dev[0].hs20_enable()
1906     dev[0].scan_for_bss(bssid, freq="2412")
1907     dev[0].request("SET external_sim 1")
1908     id1 = dev[0].add_cred_values({ 'imsi': "23201-0000000000", 'eap': "SIM",
1909                                    'provisioning_sp': "example.com",
1910                                    'sp_priority' :"1" })
1911     id2 = dev[0].add_cred_values({ 'realm': "example.com",
1912                                    'ca_cert': "auth_serv/ca.pem",
1913                                    'username': "hs20-test",
1914                                    'password': "password",
1915                                    'domain': "example.com",
1916                                    'provisioning_sp': "example.com",
1917                                    'sp_priority': "2" })
1918     dev[0].dump_monitor()
1919     dev[0].scan_for_bss(bssid, freq="2412")
1920     dev[0].request("INTERWORKING_SELECT auto freq=2412")
1921     interworking_ext_sim_auth(dev[0], "SIM")
1922     check_sp_type(dev[0], "unknown")
1923     dev[0].request("REMOVE_NETWORK all")
1924
1925     dev[0].set_cred(id1, "sp_priority", "2")
1926     dev[0].set_cred(id2, "sp_priority", "1")
1927     dev[0].dump_monitor()
1928     dev[0].request("INTERWORKING_SELECT auto freq=2412")
1929     interworking_auth(dev[0], "TTLS")
1930     check_sp_type(dev[0], "unknown")
1931
1932 def test_ap_hs20_multi_cred_sp_prio2(dev, apdev):
1933     """Hotspot 2.0 multi-cred sp_priority with two BSSes"""
1934     check_eap_capa(dev[0], "MSCHAPV2")
1935     try:
1936         _test_ap_hs20_multi_cred_sp_prio2(dev, apdev)
1937     finally:
1938         dev[0].request("SET external_sim 0")
1939
1940 def _test_ap_hs20_multi_cred_sp_prio2(dev, apdev):
1941     hlr_auc_gw_available()
1942     bssid = apdev[0]['bssid']
1943     params = hs20_ap_params()
1944     params['hessid'] = bssid
1945     del params['nai_realm']
1946     del params['domain_name']
1947     params['anqp_3gpp_cell_net'] = "232,01"
1948     hostapd.add_ap(apdev[0], params)
1949
1950     bssid2 = apdev[1]['bssid']
1951     params = hs20_ap_params()
1952     params['ssid'] = "test-hs20-other"
1953     params['hessid'] = bssid2
1954     del params['domain_name']
1955     del params['anqp_3gpp_cell_net']
1956     hostapd.add_ap(apdev[1], params)
1957
1958     dev[0].hs20_enable()
1959     dev[0].request("SET external_sim 1")
1960     id1 = dev[0].add_cred_values({ 'imsi': "23201-0000000000", 'eap': "SIM",
1961                                    'provisioning_sp': "example.com",
1962                                    'sp_priority': "1" })
1963     id2 = dev[0].add_cred_values({ 'realm': "example.com",
1964                                    'ca_cert': "auth_serv/ca.pem",
1965                                    'username': "hs20-test",
1966                                    'password': "password",
1967                                    'domain': "example.com",
1968                                    'provisioning_sp': "example.com",
1969                                    'sp_priority': "2" })
1970     dev[0].dump_monitor()
1971     dev[0].scan_for_bss(bssid, freq="2412")
1972     dev[0].scan_for_bss(bssid2, freq="2412")
1973     dev[0].request("INTERWORKING_SELECT auto freq=2412")
1974     interworking_ext_sim_auth(dev[0], "SIM")
1975     check_sp_type(dev[0], "unknown")
1976     conn_bssid = dev[0].get_status_field("bssid")
1977     if conn_bssid != bssid:
1978         raise Exception("Connected to incorrect BSS")
1979     dev[0].request("REMOVE_NETWORK all")
1980
1981     dev[0].set_cred(id1, "sp_priority", "2")
1982     dev[0].set_cred(id2, "sp_priority", "1")
1983     dev[0].dump_monitor()
1984     dev[0].request("INTERWORKING_SELECT auto freq=2412")
1985     interworking_auth(dev[0], "TTLS")
1986     check_sp_type(dev[0], "unknown")
1987     conn_bssid = dev[0].get_status_field("bssid")
1988     if conn_bssid != bssid2:
1989         raise Exception("Connected to incorrect BSS")
1990
1991 def test_ap_hs20_multi_cred_sp_prio_same(dev, apdev):
1992     """Hotspot 2.0 multi-cred and same sp_priority"""
1993     check_eap_capa(dev[0], "MSCHAPV2")
1994     hlr_auc_gw_available()
1995     bssid = apdev[0]['bssid']
1996     params = hs20_ap_params()
1997     params['hessid'] = bssid
1998     del params['domain_name']
1999     params['anqp_3gpp_cell_net'] = "232,01"
2000     hostapd.add_ap(apdev[0], params)
2001
2002     dev[0].hs20_enable()
2003     dev[0].scan_for_bss(bssid, freq="2412")
2004     id1 = dev[0].add_cred_values({ 'realm': "example.com",
2005                                    'ca_cert': "auth_serv/ca.pem",
2006                                    'username': "hs20-test",
2007                                    'password': "password",
2008                                    'domain': "domain1.example.com",
2009                                    'provisioning_sp': "example.com",
2010                                    'sp_priority': "1" })
2011     id2 = dev[0].add_cred_values({ 'realm': "example.com",
2012                                    'ca_cert': "auth_serv/ca.pem",
2013                                    'username': "hs20-test",
2014                                    'password': "password",
2015                                    'domain': "domain2.example.com",
2016                                    'provisioning_sp': "example.com",
2017                                    'sp_priority': "1" })
2018     dev[0].dump_monitor()
2019     dev[0].scan_for_bss(bssid, freq="2412")
2020     check_auto_select(dev[0], bssid)
2021
2022 def check_conn_capab_selection(dev, type, missing):
2023     dev.request("INTERWORKING_SELECT freq=2412")
2024     ev = dev.wait_event(["INTERWORKING-AP"])
2025     if ev is None:
2026         raise Exception("Network selection timed out")
2027     if "type=" + type not in ev:
2028         raise Exception("Unexpected network type")
2029     if missing and "conn_capab_missing=1" not in ev:
2030         raise Exception("conn_capab_missing not reported")
2031     if not missing and "conn_capab_missing=1" in ev:
2032         raise Exception("conn_capab_missing reported unexpectedly")
2033
2034 def conn_capab_cred(domain=None, req_conn_capab=None):
2035     cred = default_cred(domain=domain)
2036     if req_conn_capab:
2037         cred['req_conn_capab'] = req_conn_capab
2038     return cred
2039
2040 def test_ap_hs20_req_conn_capab(dev, apdev):
2041     """Hotspot 2.0 network selection with req_conn_capab"""
2042     check_eap_capa(dev[0], "MSCHAPV2")
2043     bssid = apdev[0]['bssid']
2044     params = hs20_ap_params()
2045     hostapd.add_ap(apdev[0], params)
2046
2047     dev[0].hs20_enable()
2048     dev[0].scan_for_bss(bssid, freq="2412")
2049     logger.info("Not used in home network")
2050     values = conn_capab_cred(domain="example.com", req_conn_capab="6:1234")
2051     id = dev[0].add_cred_values(values)
2052     check_conn_capab_selection(dev[0], "home", False)
2053
2054     logger.info("Used in roaming network")
2055     dev[0].remove_cred(id)
2056     values = conn_capab_cred(domain="example.org", req_conn_capab="6:1234")
2057     id = dev[0].add_cred_values(values)
2058     check_conn_capab_selection(dev[0], "roaming", True)
2059
2060     logger.info("Verify that req_conn_capab does not prevent connection if no other network is available")
2061     check_auto_select(dev[0], bssid)
2062
2063     logger.info("Additional req_conn_capab checks")
2064
2065     dev[0].remove_cred(id)
2066     values = conn_capab_cred(domain="example.org", req_conn_capab="1:0")
2067     id = dev[0].add_cred_values(values)
2068     check_conn_capab_selection(dev[0], "roaming", True)
2069
2070     dev[0].remove_cred(id)
2071     values = conn_capab_cred(domain="example.org", req_conn_capab="17:5060")
2072     id = dev[0].add_cred_values(values)
2073     check_conn_capab_selection(dev[0], "roaming", True)
2074
2075     bssid2 = apdev[1]['bssid']
2076     params = hs20_ap_params(ssid="test-hs20b")
2077     params['hs20_conn_capab'] = [ "1:0:2", "6:22:1", "17:5060:0", "50:0:1" ]
2078     hostapd.add_ap(apdev[1], params)
2079
2080     dev[0].remove_cred(id)
2081     values = conn_capab_cred(domain="example.org", req_conn_capab="50")
2082     id = dev[0].add_cred_values(values)
2083     dev[0].set_cred(id, "req_conn_capab", "6:22")
2084     dev[0].scan_for_bss(bssid2, freq="2412")
2085     dev[0].request("INTERWORKING_SELECT freq=2412")
2086     for i in range(0, 2):
2087         ev = dev[0].wait_event(["INTERWORKING-AP"])
2088         if ev is None:
2089             raise Exception("Network selection timed out")
2090         if bssid in ev and "conn_capab_missing=1" not in ev:
2091             raise Exception("Missing protocol connection capability not reported")
2092         if bssid2 in ev and "conn_capab_missing=1" in ev:
2093             raise Exception("Protocol connection capability not reported correctly")
2094
2095 def test_ap_hs20_req_conn_capab2(dev, apdev):
2096     """Hotspot 2.0 network selection with req_conn_capab (not present)"""
2097     check_eap_capa(dev[0], "MSCHAPV2")
2098     bssid = apdev[0]['bssid']
2099     params = hs20_ap_params()
2100     del params['hs20_conn_capab']
2101     hostapd.add_ap(apdev[0], params)
2102
2103     dev[0].hs20_enable()
2104     dev[0].scan_for_bss(bssid, freq="2412")
2105     values = conn_capab_cred(domain="example.org", req_conn_capab="6:1234")
2106     id = dev[0].add_cred_values(values)
2107     check_conn_capab_selection(dev[0], "roaming", False)
2108
2109 def test_ap_hs20_req_conn_capab_and_roaming_partner_preference(dev, apdev):
2110     """Hotspot 2.0 and req_conn_capab with roaming partner preference"""
2111     check_eap_capa(dev[0], "MSCHAPV2")
2112     bssid = apdev[0]['bssid']
2113     params = hs20_ap_params()
2114     params['domain_name'] = "roaming.example.org"
2115     params['hs20_conn_capab'] = [ "1:0:2", "6:22:1", "17:5060:0", "50:0:1" ]
2116     hostapd.add_ap(apdev[0], params)
2117
2118     bssid2 = apdev[1]['bssid']
2119     params = hs20_ap_params(ssid="test-hs20-b")
2120     params['domain_name'] = "roaming.example.net"
2121     hostapd.add_ap(apdev[1], params)
2122
2123     values = default_cred()
2124     values['roaming_partner'] = "roaming.example.net,1,127,*"
2125     id = dev[0].add_cred_values(values)
2126     check_auto_select(dev[0], bssid2)
2127
2128     dev[0].set_cred(id, "req_conn_capab", "50")
2129     check_auto_select(dev[0], bssid)
2130
2131     dev[0].remove_cred(id)
2132     id = dev[0].add_cred_values(values)
2133     dev[0].set_cred(id, "req_conn_capab", "51")
2134     check_auto_select(dev[0], bssid2)
2135
2136 def check_bandwidth_selection(dev, type, below):
2137     dev.request("INTERWORKING_SELECT freq=2412")
2138     ev = dev.wait_event(["INTERWORKING-AP"])
2139     if ev is None:
2140         raise Exception("Network selection timed out")
2141     logger.debug("BSS entries:\n" + dev.request("BSS RANGE=ALL"))
2142     if "type=" + type not in ev:
2143         raise Exception("Unexpected network type")
2144     if below and "below_min_backhaul=1" not in ev:
2145         raise Exception("below_min_backhaul not reported")
2146     if not below and "below_min_backhaul=1" in ev:
2147         raise Exception("below_min_backhaul reported unexpectedly")
2148
2149 def bw_cred(domain=None, dl_home=None, ul_home=None, dl_roaming=None, ul_roaming=None):
2150     cred = default_cred(domain=domain)
2151     if dl_home:
2152         cred['min_dl_bandwidth_home'] = str(dl_home)
2153     if ul_home:
2154         cred['min_ul_bandwidth_home'] = str(ul_home)
2155     if dl_roaming:
2156         cred['min_dl_bandwidth_roaming'] = str(dl_roaming)
2157     if ul_roaming:
2158         cred['min_ul_bandwidth_roaming'] = str(ul_roaming)
2159     return cred
2160
2161 def test_ap_hs20_min_bandwidth_home(dev, apdev):
2162     """Hotspot 2.0 network selection with min bandwidth (home)"""
2163     check_eap_capa(dev[0], "MSCHAPV2")
2164     bssid = apdev[0]['bssid']
2165     params = hs20_ap_params()
2166     hostapd.add_ap(apdev[0], params)
2167
2168     dev[0].hs20_enable()
2169     dev[0].scan_for_bss(bssid, freq="2412")
2170     values = bw_cred(domain="example.com", dl_home=5490, ul_home=58)
2171     id = dev[0].add_cred_values(values)
2172     check_bandwidth_selection(dev[0], "home", False)
2173     dev[0].remove_cred(id)
2174
2175     values = bw_cred(domain="example.com", dl_home=5491, ul_home=58)
2176     id = dev[0].add_cred_values(values)
2177     check_bandwidth_selection(dev[0], "home", True)
2178     dev[0].remove_cred(id)
2179
2180     values = bw_cred(domain="example.com", dl_home=5490, ul_home=59)
2181     id = dev[0].add_cred_values(values)
2182     check_bandwidth_selection(dev[0], "home", True)
2183     dev[0].remove_cred(id)
2184
2185     values = bw_cred(domain="example.com", dl_home=5491, ul_home=59)
2186     id = dev[0].add_cred_values(values)
2187     check_bandwidth_selection(dev[0], "home", True)
2188     check_auto_select(dev[0], bssid)
2189
2190     bssid2 = apdev[1]['bssid']
2191     params = hs20_ap_params(ssid="test-hs20-b")
2192     params['hs20_wan_metrics'] = "01:8000:1000:1:1:3000"
2193     hostapd.add_ap(apdev[1], params)
2194
2195     check_auto_select(dev[0], bssid2)
2196
2197 def test_ap_hs20_min_bandwidth_home2(dev, apdev):
2198     """Hotspot 2.0 network selection with min bandwidth - special cases"""
2199     check_eap_capa(dev[0], "MSCHAPV2")
2200     bssid = apdev[0]['bssid']
2201     params = hs20_ap_params()
2202     hapd = hostapd.add_ap(apdev[0], params)
2203
2204     dev[0].hs20_enable()
2205     dev[0].scan_for_bss(bssid, freq="2412")
2206     values = bw_cred(domain="example.com", dl_home=5490, ul_home=58)
2207     id = dev[0].add_cred_values(values)
2208     check_bandwidth_selection(dev[0], "home", False)
2209
2210     logger.info("WAN link at capacity")
2211     hapd.set('hs20_wan_metrics', "09:8000:1000:80:240:3000")
2212     check_bandwidth_selection(dev[0], "home", True)
2213
2214     logger.info("Downlink/Uplink Load was not measured")
2215     hapd.set('hs20_wan_metrics', "01:8000:1000:80:240:0")
2216     check_bandwidth_selection(dev[0], "home", False)
2217
2218     logger.info("Uplink and Downlink max values")
2219     hapd.set('hs20_wan_metrics', "01:4294967295:4294967295:80:240:3000")
2220     check_bandwidth_selection(dev[0], "home", False)
2221
2222     dev[0].remove_cred(id)
2223
2224 def test_ap_hs20_min_bandwidth_home_hidden_ssid_in_scan_res(dev, apdev):
2225     """Hotspot 2.0 network selection with min bandwidth (home) while hidden SSID is included in scan results"""
2226     check_eap_capa(dev[0], "MSCHAPV2")
2227     bssid = apdev[0]['bssid']
2228
2229     hapd = hostapd.add_ap(apdev[0], { "ssid": 'secret',
2230                                       "ignore_broadcast_ssid": "1" })
2231     dev[0].scan_for_bss(bssid, freq=2412)
2232     hapd.disable()
2233     hapd_global = hostapd.HostapdGlobal(apdev[0])
2234     hapd_global.flush()
2235     hapd_global.remove(apdev[0]['ifname'])
2236
2237     params = hs20_ap_params()
2238     hostapd.add_ap(apdev[0], params)
2239
2240     dev[0].hs20_enable()
2241     dev[0].scan_for_bss(bssid, freq="2412")
2242     values = bw_cred(domain="example.com", dl_home=5490, ul_home=58)
2243     id = dev[0].add_cred_values(values)
2244     check_bandwidth_selection(dev[0], "home", False)
2245     dev[0].remove_cred(id)
2246
2247     values = bw_cred(domain="example.com", dl_home=5491, ul_home=58)
2248     id = dev[0].add_cred_values(values)
2249     check_bandwidth_selection(dev[0], "home", True)
2250     dev[0].remove_cred(id)
2251
2252     values = bw_cred(domain="example.com", dl_home=5490, ul_home=59)
2253     id = dev[0].add_cred_values(values)
2254     check_bandwidth_selection(dev[0], "home", True)
2255     dev[0].remove_cred(id)
2256
2257     values = bw_cred(domain="example.com", dl_home=5491, ul_home=59)
2258     id = dev[0].add_cred_values(values)
2259     check_bandwidth_selection(dev[0], "home", True)
2260     check_auto_select(dev[0], bssid)
2261
2262     bssid2 = apdev[1]['bssid']
2263     params = hs20_ap_params(ssid="test-hs20-b")
2264     params['hs20_wan_metrics'] = "01:8000:1000:1:1:3000"
2265     hostapd.add_ap(apdev[1], params)
2266
2267     check_auto_select(dev[0], bssid2)
2268
2269     dev[0].flush_scan_cache()
2270
2271 def test_ap_hs20_min_bandwidth_roaming(dev, apdev):
2272     """Hotspot 2.0 network selection with min bandwidth (roaming)"""
2273     check_eap_capa(dev[0], "MSCHAPV2")
2274     bssid = apdev[0]['bssid']
2275     params = hs20_ap_params()
2276     hostapd.add_ap(apdev[0], params)
2277
2278     dev[0].hs20_enable()
2279     dev[0].scan_for_bss(bssid, freq="2412")
2280     values = bw_cred(domain="example.org", dl_roaming=5490, ul_roaming=58)
2281     id = dev[0].add_cred_values(values)
2282     check_bandwidth_selection(dev[0], "roaming", False)
2283     dev[0].remove_cred(id)
2284
2285     values = bw_cred(domain="example.org", dl_roaming=5491, ul_roaming=58)
2286     id = dev[0].add_cred_values(values)
2287     check_bandwidth_selection(dev[0], "roaming", True)
2288     dev[0].remove_cred(id)
2289
2290     values = bw_cred(domain="example.org", dl_roaming=5490, ul_roaming=59)
2291     id = dev[0].add_cred_values(values)
2292     check_bandwidth_selection(dev[0], "roaming", True)
2293     dev[0].remove_cred(id)
2294
2295     values = bw_cred(domain="example.org", dl_roaming=5491, ul_roaming=59)
2296     id = dev[0].add_cred_values(values)
2297     check_bandwidth_selection(dev[0], "roaming", True)
2298     check_auto_select(dev[0], bssid)
2299
2300     bssid2 = apdev[1]['bssid']
2301     params = hs20_ap_params(ssid="test-hs20-b")
2302     params['hs20_wan_metrics'] = "01:8000:1000:1:1:3000"
2303     hostapd.add_ap(apdev[1], params)
2304
2305     check_auto_select(dev[0], bssid2)
2306
2307 def test_ap_hs20_min_bandwidth_and_roaming_partner_preference(dev, apdev):
2308     """Hotspot 2.0 and minimum bandwidth with roaming partner preference"""
2309     check_eap_capa(dev[0], "MSCHAPV2")
2310     bssid = apdev[0]['bssid']
2311     params = hs20_ap_params()
2312     params['domain_name'] = "roaming.example.org"
2313     params['hs20_wan_metrics'] = "01:8000:1000:1:1:3000"
2314     hostapd.add_ap(apdev[0], params)
2315
2316     bssid2 = apdev[1]['bssid']
2317     params = hs20_ap_params(ssid="test-hs20-b")
2318     params['domain_name'] = "roaming.example.net"
2319     hostapd.add_ap(apdev[1], params)
2320
2321     values = default_cred()
2322     values['roaming_partner'] = "roaming.example.net,1,127,*"
2323     id = dev[0].add_cred_values(values)
2324     check_auto_select(dev[0], bssid2)
2325
2326     dev[0].set_cred(id, "min_dl_bandwidth_roaming", "6000")
2327     check_auto_select(dev[0], bssid)
2328
2329     dev[0].set_cred(id, "min_dl_bandwidth_roaming", "10000")
2330     check_auto_select(dev[0], bssid2)
2331
2332 def test_ap_hs20_min_bandwidth_no_wan_metrics(dev, apdev):
2333     """Hotspot 2.0 network selection with min bandwidth but no WAN Metrics"""
2334     bssid = apdev[0]['bssid']
2335     params = hs20_ap_params()
2336     del params['hs20_wan_metrics']
2337     hostapd.add_ap(apdev[0], params)
2338
2339     dev[0].hs20_enable()
2340     dev[0].scan_for_bss(bssid, freq="2412")
2341     values = bw_cred(domain="example.com", dl_home=10000, ul_home=10000,
2342                      dl_roaming=10000, ul_roaming=10000)
2343     dev[0].add_cred_values(values)
2344     check_bandwidth_selection(dev[0], "home", False)
2345
2346 def test_ap_hs20_deauth_req_ess(dev, apdev):
2347     """Hotspot 2.0 connection and deauthentication request for ESS"""
2348     check_eap_capa(dev[0], "MSCHAPV2")
2349     try:
2350         _test_ap_hs20_deauth_req_ess(dev, apdev)
2351     finally:
2352         dev[0].request("SET pmf 0")
2353
2354 def _test_ap_hs20_deauth_req_ess(dev, apdev):
2355     dev[0].request("SET pmf 2")
2356     eap_test(dev[0], apdev[0], "21[3:26]", "TTLS", "user")
2357     dev[0].dump_monitor()
2358     addr = dev[0].p2p_interface_addr()
2359     hapd = hostapd.Hostapd(apdev[0]['ifname'])
2360     hapd.request("HS20_DEAUTH_REQ " + addr + " 1 120 http://example.com/")
2361     ev = dev[0].wait_event(["HS20-DEAUTH-IMMINENT-NOTICE"])
2362     if ev is None:
2363         raise Exception("Timeout on deauth imminent notice")
2364     if "1 120 http://example.com/" not in ev:
2365         raise Exception("Unexpected deauth imminent notice: " + ev)
2366     hapd.request("DEAUTHENTICATE " + addr)
2367     dev[0].wait_disconnected(timeout=10)
2368     if "[TEMP-DISABLED]" not in dev[0].list_networks()[0]['flags']:
2369         raise Exception("Network not marked temporarily disabled")
2370     ev = dev[0].wait_event(["SME: Trying to authenticate",
2371                             "Trying to associate",
2372                             "CTRL-EVENT-CONNECTED"], timeout=5)
2373     if ev is not None:
2374         raise Exception("Unexpected connection attempt")
2375
2376 def test_ap_hs20_deauth_req_bss(dev, apdev):
2377     """Hotspot 2.0 connection and deauthentication request for BSS"""
2378     check_eap_capa(dev[0], "MSCHAPV2")
2379     try:
2380         _test_ap_hs20_deauth_req_bss(dev, apdev)
2381     finally:
2382         dev[0].request("SET pmf 0")
2383
2384 def _test_ap_hs20_deauth_req_bss(dev, apdev):
2385     dev[0].request("SET pmf 2")
2386     eap_test(dev[0], apdev[0], "21[3:26]", "TTLS", "user")
2387     dev[0].dump_monitor()
2388     addr = dev[0].p2p_interface_addr()
2389     hapd = hostapd.Hostapd(apdev[0]['ifname'])
2390     hapd.request("HS20_DEAUTH_REQ " + addr + " 0 120 http://example.com/")
2391     ev = dev[0].wait_event(["HS20-DEAUTH-IMMINENT-NOTICE"])
2392     if ev is None:
2393         raise Exception("Timeout on deauth imminent notice")
2394     if "0 120 http://example.com/" not in ev:
2395         raise Exception("Unexpected deauth imminent notice: " + ev)
2396     hapd.request("DEAUTHENTICATE " + addr + " reason=4")
2397     ev = dev[0].wait_disconnected(timeout=10)
2398     if "reason=4" not in ev:
2399         raise Exception("Unexpected disconnection reason")
2400     if "[TEMP-DISABLED]" not in dev[0].list_networks()[0]['flags']:
2401         raise Exception("Network not marked temporarily disabled")
2402     ev = dev[0].wait_event(["SME: Trying to authenticate",
2403                             "Trying to associate",
2404                             "CTRL-EVENT-CONNECTED"], timeout=5)
2405     if ev is not None:
2406         raise Exception("Unexpected connection attempt")
2407
2408 def test_ap_hs20_deauth_req_from_radius(dev, apdev):
2409     """Hotspot 2.0 connection and deauthentication request from RADIUS"""
2410     check_eap_capa(dev[0], "MSCHAPV2")
2411     try:
2412         _test_ap_hs20_deauth_req_from_radius(dev, apdev)
2413     finally:
2414         dev[0].request("SET pmf 0")
2415
2416 def _test_ap_hs20_deauth_req_from_radius(dev, apdev):
2417     bssid = apdev[0]['bssid']
2418     params = hs20_ap_params()
2419     params['nai_realm'] = [ "0,example.com,21[2:4]" ]
2420     params['hs20_deauth_req_timeout'] = "2"
2421     hostapd.add_ap(apdev[0], params)
2422
2423     dev[0].request("SET pmf 2")
2424     dev[0].hs20_enable()
2425     dev[0].add_cred_values({ 'realm': "example.com",
2426                              'username': "hs20-deauth-test",
2427                              'password': "password" })
2428     interworking_select(dev[0], bssid, freq="2412")
2429     interworking_connect(dev[0], bssid, "TTLS")
2430     ev = dev[0].wait_event(["HS20-DEAUTH-IMMINENT-NOTICE"], timeout=5)
2431     if ev is None:
2432         raise Exception("Timeout on deauth imminent notice")
2433     if " 1 100" not in ev:
2434         raise Exception("Unexpected deauth imminent contents")
2435     dev[0].wait_disconnected(timeout=3)
2436
2437 def test_ap_hs20_remediation_required(dev, apdev):
2438     """Hotspot 2.0 connection and remediation required from RADIUS"""
2439     check_eap_capa(dev[0], "MSCHAPV2")
2440     try:
2441         _test_ap_hs20_remediation_required(dev, apdev)
2442     finally:
2443         dev[0].request("SET pmf 0")
2444
2445 def _test_ap_hs20_remediation_required(dev, apdev):
2446     bssid = apdev[0]['bssid']
2447     params = hs20_ap_params()
2448     params['nai_realm'] = [ "0,example.com,21[2:4]" ]
2449     hostapd.add_ap(apdev[0], params)
2450
2451     dev[0].request("SET pmf 1")
2452     dev[0].hs20_enable()
2453     dev[0].add_cred_values({ 'realm': "example.com",
2454                              'username': "hs20-subrem-test",
2455                              'password': "password" })
2456     interworking_select(dev[0], bssid, freq="2412")
2457     interworking_connect(dev[0], bssid, "TTLS")
2458     ev = dev[0].wait_event(["HS20-SUBSCRIPTION-REMEDIATION"], timeout=5)
2459     if ev is None:
2460         raise Exception("Timeout on subscription remediation notice")
2461     if " 1 https://example.com/" not in ev:
2462         raise Exception("Unexpected subscription remediation event contents")
2463
2464 def test_ap_hs20_remediation_required_ctrl(dev, apdev):
2465     """Hotspot 2.0 connection and subrem from ctrl_iface"""
2466     check_eap_capa(dev[0], "MSCHAPV2")
2467     try:
2468         _test_ap_hs20_remediation_required_ctrl(dev, apdev)
2469     finally:
2470         dev[0].request("SET pmf 0")
2471
2472 def _test_ap_hs20_remediation_required_ctrl(dev, apdev):
2473     bssid = apdev[0]['bssid']
2474     addr = dev[0].own_addr()
2475     params = hs20_ap_params()
2476     params['nai_realm'] = [ "0,example.com,21[2:4]" ]
2477     hapd = hostapd.add_ap(apdev[0], params)
2478
2479     dev[0].request("SET pmf 1")
2480     dev[0].hs20_enable()
2481     dev[0].add_cred_values(default_cred())
2482     interworking_select(dev[0], bssid, freq="2412")
2483     interworking_connect(dev[0], bssid, "TTLS")
2484
2485     hapd.request("HS20_WNM_NOTIF " + addr + " https://example.com/")
2486     ev = dev[0].wait_event(["HS20-SUBSCRIPTION-REMEDIATION"], timeout=5)
2487     if ev is None:
2488         raise Exception("Timeout on subscription remediation notice")
2489     if " 1 https://example.com/" not in ev:
2490         raise Exception("Unexpected subscription remediation event contents")
2491
2492     hapd.request("HS20_WNM_NOTIF " + addr)
2493     ev = dev[0].wait_event(["HS20-SUBSCRIPTION-REMEDIATION"], timeout=5)
2494     if ev is None:
2495         raise Exception("Timeout on subscription remediation notice")
2496     if not ev.endswith("HS20-SUBSCRIPTION-REMEDIATION "):
2497         raise Exception("Unexpected subscription remediation event contents: " + ev)
2498
2499     if "FAIL" not in hapd.request("HS20_WNM_NOTIF "):
2500         raise Exception("Unexpected HS20_WNM_NOTIF success")
2501     if "FAIL" not in hapd.request("HS20_WNM_NOTIF foo"):
2502         raise Exception("Unexpected HS20_WNM_NOTIF success")
2503     if "FAIL" not in hapd.request("HS20_WNM_NOTIF " + addr + " https://12345678923456789842345678456783456712345678923456789842345678456783456712345678923456789842345678456783456712345678923456789842345678456783456712345678923456789842345678456783456712345678923456789842345678456783456712345678923456789842345678456783456712345678927.very.long.example.com/"):
2504         raise Exception("Unexpected HS20_WNM_NOTIF success")
2505
2506 def test_ap_hs20_session_info(dev, apdev):
2507     """Hotspot 2.0 connection and session information from RADIUS"""
2508     check_eap_capa(dev[0], "MSCHAPV2")
2509     try:
2510         _test_ap_hs20_session_info(dev, apdev)
2511     finally:
2512         dev[0].request("SET pmf 0")
2513
2514 def _test_ap_hs20_session_info(dev, apdev):
2515     bssid = apdev[0]['bssid']
2516     params = hs20_ap_params()
2517     params['nai_realm'] = [ "0,example.com,21[2:4]" ]
2518     hostapd.add_ap(apdev[0], params)
2519
2520     dev[0].request("SET pmf 1")
2521     dev[0].hs20_enable()
2522     dev[0].add_cred_values({ 'realm': "example.com",
2523                              'username': "hs20-session-info-test",
2524                              'password': "password" })
2525     interworking_select(dev[0], bssid, freq="2412")
2526     interworking_connect(dev[0], bssid, "TTLS")
2527     ev = dev[0].wait_event(["ESS-DISASSOC-IMMINENT"], timeout=10)
2528     if ev is None:
2529         raise Exception("Timeout on ESS disassociation imminent notice")
2530     if " 1 59904 https://example.com/" not in ev:
2531         raise Exception("Unexpected ESS disassociation imminent event contents")
2532     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"])
2533     if ev is None:
2534         raise Exception("Scan not started")
2535     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=30)
2536     if ev is None:
2537         raise Exception("Scan not completed")
2538
2539 def test_ap_hs20_osen(dev, apdev):
2540     """Hotspot 2.0 OSEN connection"""
2541     params = { 'ssid': "osen",
2542                'osen': "1",
2543                'auth_server_addr': "127.0.0.1",
2544                'auth_server_port': "1812",
2545                'auth_server_shared_secret': "radius" }
2546     hostapd.add_ap(apdev[0], params)
2547
2548     dev[1].connect("osen", key_mgmt="NONE", scan_freq="2412",
2549                    wait_connect=False)
2550     dev[2].connect("osen", key_mgmt="NONE", wep_key0='"hello"',
2551                    scan_freq="2412", wait_connect=False)
2552     dev[0].flush_scan_cache()
2553     dev[0].connect("osen", proto="OSEN", key_mgmt="OSEN", pairwise="CCMP",
2554                    group="GTK_NOT_USED",
2555                    eap="WFA-UNAUTH-TLS", identity="osen@example.com",
2556                    ca_cert="auth_serv/ca.pem",
2557                    scan_freq="2412")
2558     res = dev[0].get_bss(apdev[0]['bssid'])['flags']
2559     if "[OSEN-OSEN-CCMP]" not in res:
2560         raise Exception("OSEN not reported in BSS")
2561     if "[WEP]" in res:
2562         raise Exception("WEP reported in BSS")
2563     res = dev[0].request("SCAN_RESULTS")
2564     if "[OSEN-OSEN-CCMP]" not in res:
2565         raise Exception("OSEN not reported in SCAN_RESULTS")
2566
2567     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
2568     wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
2569     wpas.connect("osen", proto="OSEN", key_mgmt="OSEN", pairwise="CCMP",
2570                  group="GTK_NOT_USED",
2571                  eap="WFA-UNAUTH-TLS", identity="osen@example.com",
2572                  ca_cert="auth_serv/ca.pem",
2573                  scan_freq="2412")
2574     wpas.request("DISCONNECT")
2575
2576 def test_ap_hs20_network_preference(dev, apdev):
2577     """Hotspot 2.0 network selection with preferred home network"""
2578     check_eap_capa(dev[0], "MSCHAPV2")
2579     bssid = apdev[0]['bssid']
2580     params = hs20_ap_params()
2581     hostapd.add_ap(apdev[0], params)
2582
2583     dev[0].hs20_enable()
2584     values = { 'realm': "example.com",
2585                'username': "hs20-test",
2586                'password': "password",
2587                'domain': "example.com" }
2588     dev[0].add_cred_values(values)
2589
2590     id = dev[0].add_network()
2591     dev[0].set_network_quoted(id, "ssid", "home")
2592     dev[0].set_network_quoted(id, "psk", "12345678")
2593     dev[0].set_network(id, "priority", "1")
2594     dev[0].request("ENABLE_NETWORK %s no-connect" % id)
2595
2596     dev[0].scan_for_bss(bssid, freq="2412")
2597     dev[0].request("INTERWORKING_SELECT auto freq=2412")
2598     ev = dev[0].wait_connected(timeout=15)
2599     if bssid not in ev:
2600         raise Exception("Unexpected network selected")
2601
2602     bssid2 = apdev[1]['bssid']
2603     params = hostapd.wpa2_params(ssid="home", passphrase="12345678")
2604     hostapd.add_ap(apdev[1], params)
2605
2606     dev[0].scan_for_bss(bssid2, freq="2412")
2607     dev[0].request("INTERWORKING_SELECT auto freq=2412")
2608     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
2609                             "INTERWORKING-ALREADY-CONNECTED" ], timeout=15)
2610     if ev is None:
2611         raise Exception("Connection timed out")
2612     if "INTERWORKING-ALREADY-CONNECTED" in ev:
2613         raise Exception("No roam to higher priority network")
2614     if bssid2 not in ev:
2615         raise Exception("Unexpected network selected")
2616
2617 def test_ap_hs20_network_preference2(dev, apdev):
2618     """Hotspot 2.0 network selection with preferred credential"""
2619     check_eap_capa(dev[0], "MSCHAPV2")
2620     bssid2 = apdev[1]['bssid']
2621     params = hostapd.wpa2_params(ssid="home", passphrase="12345678")
2622     hostapd.add_ap(apdev[1], params)
2623
2624     dev[0].hs20_enable()
2625     values = { 'realm': "example.com",
2626                'username': "hs20-test",
2627                'password': "password",
2628                'domain': "example.com",
2629                'priority': "1" }
2630     dev[0].add_cred_values(values)
2631
2632     id = dev[0].add_network()
2633     dev[0].set_network_quoted(id, "ssid", "home")
2634     dev[0].set_network_quoted(id, "psk", "12345678")
2635     dev[0].request("ENABLE_NETWORK %s no-connect" % id)
2636
2637     dev[0].scan_for_bss(bssid2, freq="2412")
2638     dev[0].request("INTERWORKING_SELECT auto freq=2412")
2639     ev = dev[0].wait_connected(timeout=15)
2640     if bssid2 not in ev:
2641         raise Exception("Unexpected network selected")
2642
2643     bssid = apdev[0]['bssid']
2644     params = hs20_ap_params()
2645     hostapd.add_ap(apdev[0], params)
2646
2647     dev[0].scan_for_bss(bssid, freq="2412")
2648     dev[0].request("INTERWORKING_SELECT auto freq=2412")
2649     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
2650                             "INTERWORKING-ALREADY-CONNECTED" ], timeout=15)
2651     if ev is None:
2652         raise Exception("Connection timed out")
2653     if "INTERWORKING-ALREADY-CONNECTED" in ev:
2654         raise Exception("No roam to higher priority network")
2655     if bssid not in ev:
2656         raise Exception("Unexpected network selected")
2657
2658 def test_ap_hs20_network_preference3(dev, apdev):
2659     """Hotspot 2.0 network selection with two credential (one preferred)"""
2660     check_eap_capa(dev[0], "MSCHAPV2")
2661     bssid = apdev[0]['bssid']
2662     params = hs20_ap_params()
2663     hostapd.add_ap(apdev[0], params)
2664
2665     bssid2 = apdev[1]['bssid']
2666     params = hs20_ap_params(ssid="test-hs20b")
2667     params['nai_realm'] = "0,example.org,13[5:6],21[2:4][5:7]"
2668     hostapd.add_ap(apdev[1], params)
2669
2670     dev[0].hs20_enable()
2671     values = { 'realm': "example.com",
2672                'username': "hs20-test",
2673                'password': "password",
2674                'priority': "1" }
2675     dev[0].add_cred_values(values)
2676     values = { 'realm': "example.org",
2677                'username': "hs20-test",
2678                'password': "password" }
2679     id = dev[0].add_cred_values(values)
2680
2681     dev[0].scan_for_bss(bssid, freq="2412")
2682     dev[0].scan_for_bss(bssid2, freq="2412")
2683     dev[0].request("INTERWORKING_SELECT auto freq=2412")
2684     ev = dev[0].wait_connected(timeout=15)
2685     if bssid not in ev:
2686         raise Exception("Unexpected network selected")
2687
2688     dev[0].set_cred(id, "priority", "2")
2689     dev[0].request("INTERWORKING_SELECT auto freq=2412")
2690     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
2691                             "INTERWORKING-ALREADY-CONNECTED" ], timeout=15)
2692     if ev is None:
2693         raise Exception("Connection timed out")
2694     if "INTERWORKING-ALREADY-CONNECTED" in ev:
2695         raise Exception("No roam to higher priority network")
2696     if bssid2 not in ev:
2697         raise Exception("Unexpected network selected")
2698
2699 def test_ap_hs20_network_preference4(dev, apdev):
2700     """Hotspot 2.0 network selection with username vs. SIM credential"""
2701     check_eap_capa(dev[0], "MSCHAPV2")
2702     bssid = apdev[0]['bssid']
2703     params = hs20_ap_params()
2704     hostapd.add_ap(apdev[0], params)
2705
2706     bssid2 = apdev[1]['bssid']
2707     params = hs20_ap_params(ssid="test-hs20b")
2708     params['hessid'] = bssid2
2709     params['anqp_3gpp_cell_net'] = "555,444"
2710     params['domain_name'] = "wlan.mnc444.mcc555.3gppnetwork.org"
2711     hostapd.add_ap(apdev[1], params)
2712
2713     dev[0].hs20_enable()
2714     values = { 'realm': "example.com",
2715                'username': "hs20-test",
2716                'password': "password",
2717                'priority': "1" }
2718     dev[0].add_cred_values(values)
2719     values = { 'imsi': "555444-333222111",
2720                'eap': "SIM",
2721                'milenage': "5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123" }
2722     id = dev[0].add_cred_values(values)
2723
2724     dev[0].scan_for_bss(bssid, freq="2412")
2725     dev[0].scan_for_bss(bssid2, freq="2412")
2726     dev[0].request("INTERWORKING_SELECT auto freq=2412")
2727     ev = dev[0].wait_connected(timeout=15)
2728     if bssid not in ev:
2729         raise Exception("Unexpected network selected")
2730
2731     dev[0].set_cred(id, "priority", "2")
2732     dev[0].request("INTERWORKING_SELECT auto freq=2412")
2733     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
2734                             "INTERWORKING-ALREADY-CONNECTED" ], timeout=15)
2735     if ev is None:
2736         raise Exception("Connection timed out")
2737     if "INTERWORKING-ALREADY-CONNECTED" in ev:
2738         raise Exception("No roam to higher priority network")
2739     if bssid2 not in ev:
2740         raise Exception("Unexpected network selected")
2741
2742 def test_ap_hs20_interworking_select_blocking_scan(dev, apdev):
2743     """Ongoing INTERWORKING_SELECT blocking SCAN"""
2744     check_eap_capa(dev[0], "MSCHAPV2")
2745     bssid = apdev[0]['bssid']
2746     params = hs20_ap_params()
2747     hostapd.add_ap(apdev[0], params)
2748
2749     dev[0].hs20_enable()
2750     values = { 'realm': "example.com",
2751                'username': "hs20-test",
2752                'password': "password",
2753                'domain': "example.com" }
2754     dev[0].add_cred_values(values)
2755
2756     dev[0].scan_for_bss(bssid, freq="2412")
2757     dev[0].request("INTERWORKING_SELECT auto freq=2412")
2758     if "FAIL-BUSY" not in dev[0].request("SCAN"):
2759         raise Exception("Unexpected SCAN command result")
2760     dev[0].wait_connected(timeout=15)
2761
2762 def test_ap_hs20_fetch_osu(dev, apdev):
2763     """Hotspot 2.0 OSU provider and icon fetch"""
2764     bssid = apdev[0]['bssid']
2765     params = hs20_ap_params()
2766     params['hs20_icon'] = "128:80:zxx:image/png:w1fi_logo:w1fi_logo.png"
2767     params['osu_ssid'] = '"HS 2.0 OSU open"'
2768     params['osu_method_list'] = "1"
2769     params['osu_friendly_name'] = [ "eng:Test OSU", "fin:Testi-OSU" ]
2770     params['osu_icon'] = "w1fi_logo"
2771     params['osu_service_desc'] = [ "eng:Example services", "fin:Esimerkkipalveluja" ]
2772     params['osu_server_uri'] = "https://example.com/osu/"
2773     hostapd.add_ap(apdev[0], params)
2774
2775     bssid2 = apdev[1]['bssid']
2776     params = hs20_ap_params(ssid="test-hs20b")
2777     params['hessid'] = bssid2
2778     params['hs20_icon'] = "128:80:zxx:image/png:w1fi_logo:w1fi_logo.png"
2779     params['osu_ssid'] = '"HS 2.0 OSU OSEN"'
2780     params['osu_method_list'] = "0"
2781     params['osu_nai'] = "osen@example.com"
2782     params['osu_friendly_name'] = [ "eng:Test2 OSU", "fin:Testi2-OSU" ]
2783     params['osu_icon'] = "w1fi_logo"
2784     params['osu_service_desc'] = [ "eng:Example services2", "fin:Esimerkkipalveluja2" ]
2785     params['osu_server_uri'] = "https://example.org/osu/"
2786     hostapd.add_ap(apdev[1], params)
2787
2788     with open("w1fi_logo.png", "r") as f:
2789         orig_logo = f.read()
2790     dev[0].hs20_enable()
2791     dir = "/tmp/osu-fetch"
2792     if os.path.isdir(dir):
2793        files = [ f for f in os.listdir(dir) if f.startswith("osu-") ]
2794        for f in files:
2795            os.remove(dir + "/" + f)
2796     else:
2797         try:
2798             os.makedirs(dir)
2799         except:
2800             pass
2801     try:
2802         dev[1].scan_for_bss(bssid, freq="2412")
2803         dev[2].scan_for_bss(bssid, freq="2412")
2804         dev[0].request("SET osu_dir " + dir)
2805         dev[0].request("FETCH_OSU")
2806         if "FAIL" not in dev[1].request("HS20_ICON_REQUEST foo w1fi_logo"):
2807             raise Exception("Invalid HS20_ICON_REQUEST accepted")
2808         if "OK" not in dev[1].request("HS20_ICON_REQUEST " + bssid + " w1fi_logo"):
2809             raise Exception("HS20_ICON_REQUEST failed")
2810         if "OK" not in dev[2].request("REQ_HS20_ICON " + bssid + " w1fi_logo"):
2811             raise Exception("REQ_HS20_ICON failed")
2812         icons = 0
2813         while True:
2814             ev = dev[0].wait_event(["OSU provider fetch completed",
2815                                     "RX-HS20-ANQP-ICON"], timeout=15)
2816             if ev is None:
2817                 raise Exception("Timeout on OSU fetch")
2818             if "OSU provider fetch completed" in ev:
2819                 break
2820             if "RX-HS20-ANQP-ICON" in ev:
2821                 with open(ev.split(' ')[1], "r") as f:
2822                     logo = f.read()
2823                     if logo == orig_logo:
2824                         icons += 1
2825
2826         with open(dir + "/osu-providers.txt", "r") as f:
2827             prov = f.read()
2828             logger.debug("osu-providers.txt: " + prov)
2829         if "OSU-PROVIDER " + bssid not in prov:
2830             raise Exception("Missing OSU_PROVIDER(1)")
2831         if "OSU-PROVIDER " + bssid2 not in prov:
2832             raise Exception("Missing OSU_PROVIDER(2)")
2833     finally:
2834         files = [ f for f in os.listdir(dir) if f.startswith("osu-") ]
2835         for f in files:
2836             os.remove(dir + "/" + f)
2837         os.rmdir(dir)
2838
2839     if icons != 2:
2840         raise Exception("Unexpected number of icons fetched")
2841
2842     ev = dev[1].wait_event(["GAS-QUERY-START"], timeout=5)
2843     if ev is None:
2844         raise Exception("Timeout on GAS-QUERY-DONE")
2845     ev = dev[1].wait_event(["GAS-QUERY-DONE"], timeout=5)
2846     if ev is None:
2847         raise Exception("Timeout on GAS-QUERY-DONE")
2848     if "freq=2412 status_code=0 result=SUCCESS" not in ev:
2849         raise Exception("Unexpected GAS-QUERY-DONE: " + ev)
2850     ev = dev[1].wait_event(["RX-HS20-ANQP"], timeout=15)
2851     if ev is None:
2852         raise Exception("Timeout on icon fetch")
2853     if "Icon Binary File" not in ev:
2854         raise Exception("Unexpected ANQP element")
2855
2856     ev = dev[2].wait_event(["RX-HS20-ICON"], timeout=5)
2857     if ev is None:
2858         raise Exception("Timeout on RX-HS20-ICON")
2859     event_icon_len = ev.split(' ')[3]
2860     if " w1fi_logo " not in ev:
2861         raise Exception("RX-HS20-ICON did not have the expected file name")
2862     if bssid not in ev:
2863         raise Exception("RX-HS20-ICON did not have the expected BSSID")
2864     if "FAIL" in dev[2].request("GET_HS20_ICON " + bssid + " w1fi_logo 0 10"):
2865         raise Exception("GET_HS20_ICON 0..10 failed")
2866     if "FAIL" in dev[2].request("GET_HS20_ICON " + bssid + " w1fi_logo 5 10"):
2867         raise Exception("GET_HS20_ICON 5..15 failed")
2868     if "FAIL" not in  dev[2].request("GET_HS20_ICON " + bssid + " w1fi_logo 100000 10"):
2869         raise Exception("Unexpected success of GET_HS20_ICON with too large offset")
2870     icon = ""
2871     pos = 0
2872     while True:
2873         if pos > 100000:
2874             raise Exception("Unexpectedly long icon")
2875         res = dev[2].request("GET_HS20_ICON " + bssid + " w1fi_logo %d 1000" % pos)
2876         if res.startswith("FAIL"):
2877             break
2878         icon += base64.b64decode(res)
2879         pos += 1000
2880     hex = binascii.hexlify(icon)
2881     if not hex.startswith("0009696d6167652f706e677d1d"):
2882         raise Exception("Unexpected beacon binary header: " + hex)
2883     with open('w1fi_logo.png', 'r') as f:
2884         data = f.read()
2885         if icon[13:] != data:
2886             raise Exception("Unexpected icon data")
2887     if len(icon) != int(event_icon_len):
2888         raise Exception("Unexpected RX-HS20-ICON event length: " + event_icon_len)
2889
2890     for i in range(3):
2891         if "OK" not in dev[i].request("REQ_HS20_ICON " + bssid + " w1fi_logo"):
2892             raise Exception("REQ_HS20_ICON failed [2]")
2893     for i in range(3):
2894         ev = dev[i].wait_event(["RX-HS20-ICON"], timeout=5)
2895         if ev is None:
2896             raise Exception("Timeout on RX-HS20-ICON [2]")
2897
2898     if "FAIL" not in dev[2].request("DEL_HS20_ICON foo w1fi_logo"):
2899         raise Exception("Invalid DEL_HS20_ICON accepted")
2900     if "OK" not in dev[2].request("DEL_HS20_ICON " + bssid + " w1fi_logo"):
2901         raise Exception("DEL_HS20_ICON failed")
2902     if "OK" not in dev[1].request("DEL_HS20_ICON " + bssid):
2903         raise Exception("DEL_HS20_ICON failed")
2904     if "OK" not in dev[0].request("DEL_HS20_ICON "):
2905         raise Exception("DEL_HS20_ICON failed")
2906     for i in range(3):
2907         if "FAIL" not in dev[i].request("DEL_HS20_ICON "):
2908             raise Exception("DEL_HS20_ICON accepted when no icons left")
2909
2910 def test_ap_hs20_fetch_osu_no_info(dev, apdev):
2911     """Hotspot 2.0 OSU provider and no AP with info"""
2912     bssid = apdev[0]['bssid']
2913     params = hs20_ap_params()
2914     hostapd.add_ap(apdev[0], params)
2915
2916     dev[0].hs20_enable()
2917     dir = "/tmp/osu-fetch"
2918     if os.path.isdir(dir):
2919        files = [ f for f in os.listdir(dir) if f.startswith("osu-") ]
2920        for f in files:
2921            os.remove(dir + "/" + f)
2922     else:
2923         try:
2924             os.makedirs(dir)
2925         except:
2926             pass
2927     dev[0].scan_for_bss(bssid, freq="2412")
2928     try:
2929         dev[0].request("SET osu_dir " + dir)
2930         dev[0].request("FETCH_OSU")
2931         ev = dev[0].wait_event(["OSU provider fetch completed"], timeout=30)
2932         if ev is None:
2933             raise Exception("Timeout on OSU fetch")
2934     finally:
2935         files = [ f for f in os.listdir(dir) if f.startswith("osu-") ]
2936         for f in files:
2937             os.remove(dir + "/" + f)
2938         os.rmdir(dir)
2939
2940 def get_icon(dev, bssid, iconname):
2941     icon = ""
2942     pos = 0
2943     while True:
2944         if pos > 100000:
2945             raise Exception("Unexpectedly long icon")
2946         res = dev.request("GET_HS20_ICON " + bssid + " " + iconname + " %d 3000" % pos)
2947         if res.startswith("FAIL"):
2948             break
2949         icon += base64.b64decode(res)
2950         pos += 3000
2951     if len(icon) < 13:
2952         raise Exception("Too short GET_HS20_ICON response")
2953     return icon[0:13], icon[13:]
2954
2955 def test_ap_hs20_req_hs20_icon(dev, apdev):
2956     """Hotspot 2.0 OSU provider and multi-icon fetch with REQ_HS20_ICON"""
2957     bssid = apdev[0]['bssid']
2958     params = hs20_ap_params()
2959     params['hs20_icon'] = [ "128:80:zxx:image/png:w1fi_logo:w1fi_logo.png",
2960                             "128:80:zxx:image/png:test_logo:auth_serv/sha512-server.pem" ]
2961     params['osu_ssid'] = '"HS 2.0 OSU open"'
2962     params['osu_method_list'] = "1"
2963     params['osu_friendly_name'] = [ "eng:Test OSU", "fin:Testi-OSU" ]
2964     params['osu_icon'] = [ "w1fi_logo", "w1fi_logo2" ]
2965     params['osu_service_desc'] = [ "eng:Example services", "fin:Esimerkkipalveluja" ]
2966     params['osu_server_uri'] = "https://example.com/osu/"
2967     hostapd.add_ap(apdev[0], params)
2968
2969     dev[0].scan_for_bss(bssid, freq="2412")
2970
2971     # First, fetch two icons from the AP to wpa_supplicant
2972
2973     if "OK" not in dev[0].request("REQ_HS20_ICON " + bssid + " w1fi_logo"):
2974         raise Exception("REQ_HS20_ICON failed")
2975     ev = dev[0].wait_event(["RX-HS20-ICON"], timeout=5)
2976     if ev is None:
2977         raise Exception("Timeout on RX-HS20-ICON (1)")
2978
2979     if "OK" not in dev[0].request("REQ_HS20_ICON " + bssid + " test_logo"):
2980         raise Exception("REQ_HS20_ICON failed")
2981     ev = dev[0].wait_event(["RX-HS20-ICON"], timeout=5)
2982     if ev is None:
2983         raise Exception("Timeout on RX-HS20-ICON (2)")
2984
2985     # Then, fetch the icons from wpa_supplicant for validation
2986
2987     hdr, data1 = get_icon(dev[0], bssid, "w1fi_logo")
2988     hdr, data2 = get_icon(dev[0], bssid, "test_logo")
2989
2990     with open('w1fi_logo.png', 'r') as f:
2991         data = f.read()
2992         if data1 != data:
2993             raise Exception("Unexpected icon data (1)")
2994
2995     with open('auth_serv/sha512-server.pem', 'r') as f:
2996         data = f.read()
2997         if data2 != data:
2998             raise Exception("Unexpected icon data (2)")
2999
3000     # Finally, delete the icons from wpa_supplicant
3001
3002     if "OK" not in dev[0].request("DEL_HS20_ICON " + bssid + " w1fi_logo"):
3003         raise Exception("DEL_HS20_ICON failed")
3004     if "OK" not in dev[0].request("DEL_HS20_ICON " + bssid + " test_logo"):
3005         raise Exception("DEL_HS20_ICON failed")
3006
3007 def test_ap_hs20_req_hs20_icon_parallel(dev, apdev):
3008     """Hotspot 2.0 OSU provider and multi-icon parallel fetch with REQ_HS20_ICON"""
3009     bssid = apdev[0]['bssid']
3010     params = hs20_ap_params()
3011     params['hs20_icon'] = [ "128:80:zxx:image/png:w1fi_logo:w1fi_logo.png",
3012                             "128:80:zxx:image/png:test_logo:auth_serv/sha512-server.pem" ]
3013     params['osu_ssid'] = '"HS 2.0 OSU open"'
3014     params['osu_method_list'] = "1"
3015     params['osu_friendly_name'] = [ "eng:Test OSU", "fin:Testi-OSU" ]
3016     params['osu_icon'] = [ "w1fi_logo", "w1fi_logo2" ]
3017     params['osu_service_desc'] = [ "eng:Example services", "fin:Esimerkkipalveluja" ]
3018     params['osu_server_uri'] = "https://example.com/osu/"
3019     hostapd.add_ap(apdev[0], params)
3020
3021     dev[0].scan_for_bss(bssid, freq="2412")
3022
3023     # First, fetch two icons from the AP to wpa_supplicant
3024
3025     if "OK" not in dev[0].request("REQ_HS20_ICON " + bssid + " w1fi_logo"):
3026         raise Exception("REQ_HS20_ICON failed")
3027
3028     if "OK" not in dev[0].request("REQ_HS20_ICON " + bssid + " test_logo"):
3029         raise Exception("REQ_HS20_ICON failed")
3030     ev = dev[0].wait_event(["RX-HS20-ICON"], timeout=5)
3031     if ev is None:
3032         raise Exception("Timeout on RX-HS20-ICON (1)")
3033     ev = dev[0].wait_event(["RX-HS20-ICON"], timeout=5)
3034     if ev is None:
3035         raise Exception("Timeout on RX-HS20-ICON (2)")
3036
3037     # Then, fetch the icons from wpa_supplicant for validation
3038
3039     hdr, data1 = get_icon(dev[0], bssid, "w1fi_logo")
3040     hdr, data2 = get_icon(dev[0], bssid, "test_logo")
3041
3042     with open('w1fi_logo.png', 'r') as f:
3043         data = f.read()
3044         if data1 != data:
3045             raise Exception("Unexpected icon data (1)")
3046
3047     with open('auth_serv/sha512-server.pem', 'r') as f:
3048         data = f.read()
3049         if data2 != data:
3050             raise Exception("Unexpected icon data (2)")
3051
3052     # Finally, delete the icons from wpa_supplicant
3053
3054     if "OK" not in dev[0].request("DEL_HS20_ICON " + bssid + " w1fi_logo"):
3055         raise Exception("DEL_HS20_ICON failed")
3056     if "OK" not in dev[0].request("DEL_HS20_ICON " + bssid + " test_logo"):
3057         raise Exception("DEL_HS20_ICON failed")
3058
3059 def test_ap_hs20_fetch_osu_stop(dev, apdev):
3060     """Hotspot 2.0 OSU provider fetch stopped"""
3061     bssid = apdev[0]['bssid']
3062     params = hs20_ap_params()
3063     params['hs20_icon'] = "128:80:zxx:image/png:w1fi_logo:w1fi_logo.png"
3064     params['osu_ssid'] = '"HS 2.0 OSU open"'
3065     params['osu_method_list'] = "1"
3066     params['osu_friendly_name'] = [ "eng:Test OSU", "fin:Testi-OSU" ]
3067     params['osu_icon'] = "w1fi_logo"
3068     params['osu_service_desc'] = [ "eng:Example services", "fin:Esimerkkipalveluja" ]
3069     params['osu_server_uri'] = "https://example.com/osu/"
3070     hapd = hostapd.add_ap(apdev[0], params)
3071
3072     dev[0].hs20_enable()
3073     dir = "/tmp/osu-fetch"
3074     if os.path.isdir(dir):
3075        files = [ f for f in os.listdir(dir) if f.startswith("osu-") ]
3076        for f in files:
3077            os.remove(dir + "/" + f)
3078     else:
3079         try:
3080             os.makedirs(dir)
3081         except:
3082             pass
3083     try:
3084         dev[0].request("SET osu_dir " + dir)
3085         dev[0].request("SCAN freq=2412-2462")
3086         ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], timeout=10)
3087         if ev is None:
3088             raise Exception("Scan did not start")
3089         if "FAIL" not in dev[0].request("FETCH_OSU"):
3090             raise Exception("FETCH_OSU accepted while scanning")
3091         ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 10)
3092         if ev is None:
3093             raise Exception("Scan timed out")
3094         hapd.set("ext_mgmt_frame_handling", "1")
3095         dev[0].request("FETCH_ANQP")
3096         if "FAIL" not in dev[0].request("FETCH_OSU"):
3097             raise Exception("FETCH_OSU accepted while in FETCH_ANQP")
3098         dev[0].request("STOP_FETCH_ANQP")
3099         dev[0].wait_event(["GAS-QUERY-DONE"], timeout=5)
3100         dev[0].dump_monitor()
3101         hapd.dump_monitor()
3102         dev[0].request("INTERWORKING_SELECT freq=2412")
3103         for i in range(5):
3104             msg = hapd.mgmt_rx()
3105             if msg['subtype'] == 13:
3106                 break
3107         if "FAIL" not in dev[0].request("FETCH_OSU"):
3108             raise Exception("FETCH_OSU accepted while in INTERWORKING_SELECT")
3109         ev = dev[0].wait_event(["INTERWORKING-AP", "INTERWORKING-NO-MATCH"],
3110                                timeout=15)
3111         if ev is None:
3112             raise Exception("Network selection timed out")
3113
3114         dev[0].dump_monitor()
3115         if "OK" not in dev[0].request("FETCH_OSU"):
3116             raise Exception("FETCH_OSU failed")
3117         dev[0].request("CANCEL_FETCH_OSU")
3118
3119         for i in range(15):
3120             time.sleep(0.5)
3121             if dev[0].get_driver_status_field("scan_state") == "SCAN_COMPLETED":
3122                 break
3123
3124         dev[0].dump_monitor()
3125         if "OK" not in dev[0].request("FETCH_OSU"):
3126             raise Exception("FETCH_OSU failed")
3127         if "FAIL" not in dev[0].request("FETCH_OSU"):
3128             raise Exception("FETCH_OSU accepted while in FETCH_OSU")
3129         ev = dev[0].wait_event(["GAS-QUERY-START"], 10)
3130         if ev is None:
3131             raise Exception("GAS timed out")
3132         if "FAIL" not in dev[0].request("FETCH_OSU"):
3133             raise Exception("FETCH_OSU accepted while in FETCH_OSU")
3134         dev[0].request("CANCEL_FETCH_OSU")
3135         ev = dev[0].wait_event(["GAS-QUERY-DONE"], 10)
3136         if ev is None:
3137             raise Exception("GAS event timed out after CANCEL_FETCH_OSU")
3138     finally:
3139         files = [ f for f in os.listdir(dir) if f.startswith("osu-") ]
3140         for f in files:
3141             os.remove(dir + "/" + f)
3142         os.rmdir(dir)
3143
3144 def test_ap_hs20_ft(dev, apdev):
3145     """Hotspot 2.0 connection with FT"""
3146     check_eap_capa(dev[0], "MSCHAPV2")
3147     bssid = apdev[0]['bssid']
3148     params = hs20_ap_params()
3149     params['wpa_key_mgmt'] = "FT-EAP"
3150     params['nas_identifier'] = "nas1.w1.fi"
3151     params['r1_key_holder'] = "000102030405"
3152     params["mobility_domain"] = "a1b2"
3153     params["reassociation_deadline"] = "1000"
3154     hostapd.add_ap(apdev[0], params)
3155
3156     dev[0].hs20_enable()
3157     id = dev[0].add_cred_values({ 'realm': "example.com",
3158                                   'username': "hs20-test",
3159                                   'password': "password",
3160                                   'ca_cert': "auth_serv/ca.pem",
3161                                   'domain': "example.com",
3162                                   'update_identifier': "1234" })
3163     interworking_select(dev[0], bssid, "home", freq="2412")
3164     interworking_connect(dev[0], bssid, "TTLS")
3165
3166 def test_ap_hs20_remediation_sql(dev, apdev, params):
3167     """Hotspot 2.0 connection and remediation required using SQLite for user DB"""
3168     check_eap_capa(dev[0], "MSCHAPV2")
3169     try:
3170         import sqlite3
3171     except ImportError:
3172         raise HwsimSkip("No sqlite3 module available")
3173     dbfile = os.path.join(params['logdir'], "eap-user.db")
3174     try:
3175         os.remove(dbfile)
3176     except:
3177         pass
3178     con = sqlite3.connect(dbfile)
3179     with con:
3180         cur = con.cursor()
3181         cur.execute("CREATE TABLE users(identity TEXT PRIMARY KEY, methods TEXT, password TEXT, remediation TEXT, phase2 INTEGER)")
3182         cur.execute("CREATE TABLE wildcards(identity TEXT PRIMARY KEY, methods TEXT)")
3183         cur.execute("INSERT INTO users(identity,methods,password,phase2,remediation) VALUES ('user-mschapv2','TTLS-MSCHAPV2','password',1,'user')")
3184         cur.execute("INSERT INTO wildcards(identity,methods) VALUES ('','TTLS,TLS')")
3185         cur.execute("CREATE TABLE authlog(timestamp TEXT, session TEXT, nas_ip TEXT, username TEXT, note TEXT)")
3186
3187     try:
3188         params = { "ssid": "as", "beacon_int": "2000",
3189                    "radius_server_clients": "auth_serv/radius_clients.conf",
3190                    "radius_server_auth_port": '18128',
3191                    "eap_server": "1",
3192                    "eap_user_file": "sqlite:" + dbfile,
3193                    "ca_cert": "auth_serv/ca.pem",
3194                    "server_cert": "auth_serv/server.pem",
3195                    "private_key": "auth_serv/server.key",
3196                    "subscr_remediation_url": "https://example.org/",
3197                    "subscr_remediation_method": "1" }
3198         hostapd.add_ap(apdev[1], params)
3199
3200         bssid = apdev[0]['bssid']
3201         params = hs20_ap_params()
3202         params['auth_server_port'] = "18128"
3203         hostapd.add_ap(apdev[0], params)
3204
3205         dev[0].request("SET pmf 1")
3206         dev[0].hs20_enable()
3207         id = dev[0].add_cred_values({ 'realm': "example.com",
3208                                       'username': "user-mschapv2",
3209                                       'password': "password",
3210                                       'ca_cert': "auth_serv/ca.pem" })
3211         interworking_select(dev[0], bssid, freq="2412")
3212         interworking_connect(dev[0], bssid, "TTLS")
3213         ev = dev[0].wait_event(["HS20-SUBSCRIPTION-REMEDIATION"], timeout=5)
3214         if ev is None:
3215             raise Exception("Timeout on subscription remediation notice")
3216         if " 1 https://example.org/" not in ev:
3217             raise Exception("Unexpected subscription remediation event contents")
3218
3219         with con:
3220             cur = con.cursor()
3221             cur.execute("SELECT * from authlog")
3222             rows = cur.fetchall()
3223             if len(rows) < 1:
3224                 raise Exception("No authlog entries")
3225
3226     finally:
3227         os.remove(dbfile)
3228         dev[0].request("SET pmf 0")
3229
3230 def test_ap_hs20_external_selection(dev, apdev):
3231     """Hotspot 2.0 connection using external network selection and creation"""
3232     check_eap_capa(dev[0], "MSCHAPV2")
3233     bssid = apdev[0]['bssid']
3234     params = hs20_ap_params()
3235     params['hessid'] = bssid
3236     params['disable_dgaf'] = '1'
3237     hostapd.add_ap(apdev[0], params)
3238
3239     dev[0].hs20_enable()
3240     dev[0].connect("test-hs20", proto="RSN", key_mgmt="WPA-EAP", eap="TTLS",
3241                    identity="hs20-test", password="password",
3242                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3243                    scan_freq="2412", update_identifier="54321")
3244     if dev[0].get_status_field("hs20") != "2":
3245         raise Exception("Unexpected hs20 indication")
3246
3247 def test_ap_hs20_random_mac_addr(dev, apdev):
3248     """Hotspot 2.0 connection with random MAC address"""
3249     check_eap_capa(dev[0], "MSCHAPV2")
3250     bssid = apdev[0]['bssid']
3251     params = hs20_ap_params()
3252     params['hessid'] = bssid
3253     params['disable_dgaf'] = '1'
3254     hapd = hostapd.add_ap(apdev[0], params)
3255
3256     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
3257     wpas.interface_add("wlan5")
3258     addr = wpas.p2p_interface_addr()
3259     wpas.request("SET mac_addr 1")
3260     wpas.request("SET preassoc_mac_addr 1")
3261     wpas.request("SET rand_addr_lifetime 60")
3262     wpas.hs20_enable()
3263     wpas.flush_scan_cache()
3264     id = wpas.add_cred_values({ 'realm': "example.com",
3265                                   'username': "hs20-test",
3266                                   'password': "password",
3267                                   'ca_cert': "auth_serv/ca.pem",
3268                                   'domain': "example.com",
3269                                   'update_identifier': "1234" })
3270     interworking_select(wpas, bssid, "home", freq="2412")
3271     interworking_connect(wpas, bssid, "TTLS")
3272     addr1 = wpas.get_driver_status_field("addr")
3273     if addr == addr1:
3274         raise Exception("Did not use random MAC address")
3275
3276     sta = hapd.get_sta(addr)
3277     if sta['addr'] != "FAIL":
3278         raise Exception("Unexpected STA association with permanent address")
3279     sta = hapd.get_sta(addr1)
3280     if sta['addr'] != addr1:
3281         raise Exception("STA association with random address not found")
3282
3283 def test_ap_hs20_multi_network_and_cred_removal(dev, apdev):
3284     """Multiple networks and cred removal"""
3285     check_eap_capa(dev[0], "MSCHAPV2")
3286     bssid = apdev[0]['bssid']
3287     params = hs20_ap_params()
3288     params['nai_realm'] = [ "0,example.com,25[3:26]"]
3289     hapd = hostapd.add_ap(apdev[0], params)
3290
3291     dev[0].add_network()
3292     dev[0].hs20_enable()
3293     id = dev[0].add_cred_values({ 'realm': "example.com",
3294                                   'username': "user",
3295                                   'password': "password" })
3296     interworking_select(dev[0], bssid, freq="2412")
3297     interworking_connect(dev[0], bssid, "PEAP")
3298     dev[0].add_network()
3299
3300     dev[0].request("DISCONNECT")
3301     dev[0].wait_disconnected(timeout=10)
3302
3303     hapd.disable()
3304     hapd.set("ssid", "another ssid")
3305     hapd.enable()
3306
3307     interworking_select(dev[0], bssid, freq="2412")
3308     interworking_connect(dev[0], bssid, "PEAP")
3309     dev[0].add_network()
3310     if len(dev[0].list_networks()) != 5:
3311         raise Exception("Unexpected number of networks prior to remove_crec")
3312
3313     dev[0].dump_monitor()
3314     dev[0].remove_cred(id)
3315     if len(dev[0].list_networks()) != 3:
3316         raise Exception("Unexpected number of networks after to remove_crec")
3317     dev[0].wait_disconnected(timeout=10)
3318
3319 def test_ap_hs20_interworking_add_network(dev, apdev):
3320     """Hotspot 2.0 connection using INTERWORKING_ADD_NETWORK"""
3321     check_eap_capa(dev[0], "MSCHAPV2")
3322     bssid = apdev[0]['bssid']
3323     params = hs20_ap_params()
3324     params['nai_realm'] = [ "0,example.com,21[3:26][6:7][99:99]" ]
3325     hostapd.add_ap(apdev[0], params)
3326
3327     dev[0].hs20_enable()
3328     dev[0].add_cred_values(default_cred(user="user"))
3329     interworking_select(dev[0], bssid, freq=2412)
3330     id = dev[0].interworking_add_network(bssid)
3331     dev[0].select_network(id, freq=2412)
3332     dev[0].wait_connected()
3333
3334 def _test_ap_hs20_proxyarp(dev, apdev):
3335     bssid = apdev[0]['bssid']
3336     params = hs20_ap_params()
3337     params['hessid'] = bssid
3338     params['disable_dgaf'] = '0'
3339     params['proxy_arp'] = '1'
3340     hapd = hostapd.add_ap(apdev[0], params, no_enable=True)
3341     if "OK" in hapd.request("ENABLE"):
3342         raise Exception("Incomplete hostapd configuration was accepted")
3343     hapd.set("ap_isolate", "1")
3344     if "OK" in hapd.request("ENABLE"):
3345         raise Exception("Incomplete hostapd configuration was accepted")
3346     hapd.set('bridge', 'ap-br0')
3347     hapd.dump_monitor()
3348     try:
3349         hapd.enable()
3350     except:
3351         # For now, do not report failures due to missing kernel support
3352         raise HwsimSkip("Could not start hostapd - assume proxyarp not supported in kernel version")
3353     ev = hapd.wait_event(["AP-ENABLED", "AP-DISABLED"], timeout=10)
3354     if ev is None:
3355         raise Exception("AP startup timed out")
3356     if "AP-ENABLED" not in ev:
3357         raise Exception("AP startup failed")
3358
3359     dev[0].hs20_enable()
3360     subprocess.call(['brctl', 'setfd', 'ap-br0', '0'])
3361     subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'up'])
3362
3363     id = dev[0].add_cred_values({ 'realm': "example.com",
3364                                   'username': "hs20-test",
3365                                   'password': "password",
3366                                   'ca_cert': "auth_serv/ca.pem",
3367                                   'domain': "example.com",
3368                                   'update_identifier': "1234" })
3369     interworking_select(dev[0], bssid, "home", freq="2412")
3370     interworking_connect(dev[0], bssid, "TTLS")
3371
3372     dev[1].connect("test-hs20", key_mgmt="WPA-EAP", eap="TTLS",
3373                    identity="hs20-test", password="password",
3374                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3375                    scan_freq="2412")
3376     time.sleep(0.1)
3377
3378     addr0 = dev[0].p2p_interface_addr()
3379     addr1 = dev[1].p2p_interface_addr()
3380
3381     src_ll_opt0 = "\x01\x01" + binascii.unhexlify(addr0.replace(':',''))
3382     src_ll_opt1 = "\x01\x01" + binascii.unhexlify(addr1.replace(':',''))
3383
3384     pkt = build_ns(src_ll=addr0, ip_src="aaaa:bbbb:cccc::2",
3385                    ip_dst="ff02::1:ff00:2", target="aaaa:bbbb:cccc::2",
3386                    opt=src_ll_opt0)
3387     if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
3388         raise Exception("DATA_TEST_FRAME failed")
3389
3390     pkt = build_ns(src_ll=addr1, ip_src="aaaa:bbbb:dddd::2",
3391                    ip_dst="ff02::1:ff00:2", target="aaaa:bbbb:dddd::2",
3392                    opt=src_ll_opt1)
3393     if "OK" not in dev[1].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
3394         raise Exception("DATA_TEST_FRAME failed")
3395
3396     pkt = build_ns(src_ll=addr1, ip_src="aaaa:bbbb:eeee::2",
3397                    ip_dst="ff02::1:ff00:2", target="aaaa:bbbb:eeee::2",
3398                    opt=src_ll_opt1)
3399     if "OK" not in dev[1].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
3400         raise Exception("DATA_TEST_FRAME failed")
3401
3402     matches = get_permanent_neighbors("ap-br0")
3403     logger.info("After connect: " + str(matches))
3404     if len(matches) != 3:
3405         raise Exception("Unexpected number of neighbor entries after connect")
3406     if 'aaaa:bbbb:cccc::2 dev ap-br0 lladdr 02:00:00:00:00:00 PERMANENT' not in matches:
3407         raise Exception("dev0 addr missing")
3408     if 'aaaa:bbbb:dddd::2 dev ap-br0 lladdr 02:00:00:00:01:00 PERMANENT' not in matches:
3409         raise Exception("dev1 addr(1) missing")
3410     if 'aaaa:bbbb:eeee::2 dev ap-br0 lladdr 02:00:00:00:01:00 PERMANENT' not in matches:
3411         raise Exception("dev1 addr(2) missing")
3412     dev[0].request("DISCONNECT")
3413     dev[1].request("DISCONNECT")
3414     time.sleep(0.5)
3415     matches = get_permanent_neighbors("ap-br0")
3416     logger.info("After disconnect: " + str(matches))
3417     if len(matches) > 0:
3418         raise Exception("Unexpected neighbor entries after disconnect")
3419
3420 def test_ap_hs20_hidden_ssid_in_scan_res(dev, apdev):
3421     """Hotspot 2.0 connection with hidden SSId in scan results"""
3422     check_eap_capa(dev[0], "MSCHAPV2")
3423     bssid = apdev[0]['bssid']
3424
3425     hapd = hostapd.add_ap(apdev[0], { "ssid": 'secret',
3426                                       "ignore_broadcast_ssid": "1" })
3427     dev[0].scan_for_bss(bssid, freq=2412)
3428     hapd.disable()
3429     hapd_global = hostapd.HostapdGlobal(apdev[0])
3430     hapd_global.flush()
3431     hapd_global.remove(apdev[0]['ifname'])
3432
3433     params = hs20_ap_params()
3434     params['hessid'] = bssid
3435     hapd = hostapd.add_ap(apdev[0], params)
3436
3437     dev[0].hs20_enable()
3438     id = dev[0].add_cred_values({ 'realm': "example.com",
3439                                   'username': "hs20-test",
3440                                   'password': "password",
3441                                   'ca_cert': "auth_serv/ca.pem",
3442                                   'domain': "example.com" })
3443     interworking_select(dev[0], bssid, "home", freq="2412")
3444     interworking_connect(dev[0], bssid, "TTLS")
3445
3446     # clear BSS table to avoid issues in following test cases
3447     dev[0].request("DISCONNECT")
3448     dev[0].wait_disconnected()
3449     hapd.disable()
3450     dev[0].flush_scan_cache()
3451     dev[0].flush_scan_cache()
3452
3453 def test_ap_hs20_proxyarp(dev, apdev):
3454     """Hotspot 2.0 and ProxyARP"""
3455     check_eap_capa(dev[0], "MSCHAPV2")
3456     try:
3457         _test_ap_hs20_proxyarp(dev, apdev)
3458     finally:
3459         subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'down'],
3460                         stderr=open('/dev/null', 'w'))
3461         subprocess.call(['brctl', 'delbr', 'ap-br0'],
3462                         stderr=open('/dev/null', 'w'))
3463
3464 def _test_ap_hs20_proxyarp_dgaf(dev, apdev, disabled):
3465     bssid = apdev[0]['bssid']
3466     params = hs20_ap_params()
3467     params['hessid'] = bssid
3468     params['disable_dgaf'] = '1' if disabled else '0'
3469     params['proxy_arp'] = '1'
3470     params['na_mcast_to_ucast'] = '1'
3471     params['ap_isolate'] = '1'
3472     params['bridge'] = 'ap-br0'
3473     hapd = hostapd.add_ap(apdev[0], params, no_enable=True)
3474     try:
3475         hapd.enable()
3476     except:
3477         # For now, do not report failures due to missing kernel support
3478         raise HwsimSkip("Could not start hostapd - assume proxyarp not supported in kernel version")
3479     ev = hapd.wait_event(["AP-ENABLED"], timeout=10)
3480     if ev is None:
3481         raise Exception("AP startup timed out")
3482
3483     dev[0].hs20_enable()
3484     subprocess.call(['brctl', 'setfd', 'ap-br0', '0'])
3485     subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'up'])
3486
3487     id = dev[0].add_cred_values({ 'realm': "example.com",
3488                                   'username': "hs20-test",
3489                                   'password': "password",
3490                                   'ca_cert': "auth_serv/ca.pem",
3491                                   'domain': "example.com",
3492                                   'update_identifier': "1234" })
3493     interworking_select(dev[0], bssid, "home", freq="2412")
3494     interworking_connect(dev[0], bssid, "TTLS")
3495
3496     dev[1].connect("test-hs20", key_mgmt="WPA-EAP", eap="TTLS",
3497                    identity="hs20-test", password="password",
3498                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3499                    scan_freq="2412")
3500     time.sleep(0.1)
3501
3502     addr0 = dev[0].p2p_interface_addr()
3503
3504     src_ll_opt0 = "\x01\x01" + binascii.unhexlify(addr0.replace(':',''))
3505
3506     pkt = build_ns(src_ll=addr0, ip_src="aaaa:bbbb:cccc::2",
3507                    ip_dst="ff02::1:ff00:2", target="aaaa:bbbb:cccc::2",
3508                    opt=src_ll_opt0)
3509     if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
3510         raise Exception("DATA_TEST_FRAME failed")
3511
3512     pkt = build_ra(src_ll=apdev[0]['bssid'], ip_src="aaaa:bbbb:cccc::33",
3513                    ip_dst="ff01::1")
3514     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
3515         raise Exception("DATA_TEST_FRAME failed")
3516
3517     pkt = build_na(src_ll=apdev[0]['bssid'], ip_src="aaaa:bbbb:cccc::44",
3518                    ip_dst="ff01::1", target="aaaa:bbbb:cccc::55")
3519     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
3520         raise Exception("DATA_TEST_FRAME failed")
3521
3522     pkt = build_dhcp_ack(dst_ll="ff:ff:ff:ff:ff:ff", src_ll=bssid,
3523                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
3524                          yiaddr="192.168.1.123", chaddr=addr0)
3525     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
3526         raise Exception("DATA_TEST_FRAME failed")
3527     # another copy for additional code coverage
3528     pkt = build_dhcp_ack(dst_ll=addr0, src_ll=bssid,
3529                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
3530                          yiaddr="192.168.1.123", chaddr=addr0)
3531     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
3532         raise Exception("DATA_TEST_FRAME failed")
3533
3534     matches = get_permanent_neighbors("ap-br0")
3535     logger.info("After connect: " + str(matches))
3536     if len(matches) != 2:
3537         raise Exception("Unexpected number of neighbor entries after connect")
3538     if 'aaaa:bbbb:cccc::2 dev ap-br0 lladdr 02:00:00:00:00:00 PERMANENT' not in matches:
3539         raise Exception("dev0 addr missing")
3540     if '192.168.1.123 dev ap-br0 lladdr 02:00:00:00:00:00 PERMANENT' not in matches:
3541         raise Exception("dev0 IPv4 addr missing")
3542     dev[0].request("DISCONNECT")
3543     dev[1].request("DISCONNECT")
3544     time.sleep(0.5)
3545     matches = get_permanent_neighbors("ap-br0")
3546     logger.info("After disconnect: " + str(matches))
3547     if len(matches) > 0:
3548         raise Exception("Unexpected neighbor entries after disconnect")
3549
3550 def test_ap_hs20_proxyarp_disable_dgaf(dev, apdev):
3551     """Hotspot 2.0 and ProxyARP with DGAF disabled"""
3552     check_eap_capa(dev[0], "MSCHAPV2")
3553     try:
3554         _test_ap_hs20_proxyarp_dgaf(dev, apdev, True)
3555     finally:
3556         subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'down'],
3557                         stderr=open('/dev/null', 'w'))
3558         subprocess.call(['brctl', 'delbr', 'ap-br0'],
3559                         stderr=open('/dev/null', 'w'))
3560
3561 def test_ap_hs20_proxyarp_enable_dgaf(dev, apdev):
3562     """Hotspot 2.0 and ProxyARP with DGAF enabled"""
3563     check_eap_capa(dev[0], "MSCHAPV2")
3564     try:
3565         _test_ap_hs20_proxyarp_dgaf(dev, apdev, False)
3566     finally:
3567         subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'down'],
3568                         stderr=open('/dev/null', 'w'))
3569         subprocess.call(['brctl', 'delbr', 'ap-br0'],
3570                         stderr=open('/dev/null', 'w'))
3571
3572 def ip_checksum(buf):
3573     sum = 0
3574     if len(buf) & 0x01:
3575         buf += '\0x00'
3576     for i in range(0, len(buf), 2):
3577         val, = struct.unpack('H', buf[i:i+2])
3578         sum += val
3579     while (sum >> 16):
3580         sum = (sum & 0xffff) + (sum >> 16)
3581     return struct.pack('H', ~sum & 0xffff)
3582
3583 def ipv6_solicited_node_mcaddr(target):
3584     prefix = socket.inet_pton(socket.AF_INET6, "ff02::1:ff00:0")
3585     mask = socket.inet_pton(socket.AF_INET6, "::ff:ffff")
3586     _target = socket.inet_pton(socket.AF_INET6, target)
3587     p = struct.unpack('4I', prefix)
3588     m = struct.unpack('4I', mask)
3589     t = struct.unpack('4I', _target)
3590     res = (p[0] | (t[0] & m[0]),
3591            p[1] | (t[1] & m[1]),
3592            p[2] | (t[2] & m[2]),
3593            p[3] | (t[3] & m[3]))
3594     return socket.inet_ntop(socket.AF_INET6, struct.pack('4I', *res))
3595
3596 def build_icmpv6(ipv6_addrs, type, code, payload):
3597     start = struct.pack("BB", type, code)
3598     end = payload
3599     icmp = start + '\x00\x00' + end
3600     pseudo = ipv6_addrs + struct.pack(">LBBBB", len(icmp), 0, 0, 0, 58)
3601     csum = ip_checksum(pseudo + icmp)
3602     return start + csum + end
3603
3604 def build_ra(src_ll, ip_src, ip_dst, cur_hop_limit=0, router_lifetime=0,
3605              reachable_time=0, retrans_timer=0, opt=None):
3606     link_mc = binascii.unhexlify("3333ff000002")
3607     _src_ll = binascii.unhexlify(src_ll.replace(':',''))
3608     proto = '\x86\xdd'
3609     ehdr = link_mc + _src_ll + proto
3610     _ip_src = socket.inet_pton(socket.AF_INET6, ip_src)
3611     _ip_dst = socket.inet_pton(socket.AF_INET6, ip_dst)
3612
3613     adv = struct.pack('>BBHLL', cur_hop_limit, 0, router_lifetime,
3614                       reachable_time, retrans_timer)
3615     if opt:
3616         payload = adv + opt
3617     else:
3618         payload = adv
3619     icmp = build_icmpv6(_ip_src + _ip_dst, 134, 0, payload)
3620
3621     ipv6 = struct.pack('>BBBBHBB', 0x60, 0, 0, 0, len(icmp), 58, 255)
3622     ipv6 += _ip_src + _ip_dst
3623
3624     return ehdr + ipv6 + icmp
3625
3626 def build_ns(src_ll, ip_src, ip_dst, target, opt=None):
3627     link_mc = binascii.unhexlify("3333ff000002")
3628     _src_ll = binascii.unhexlify(src_ll.replace(':',''))
3629     proto = '\x86\xdd'
3630     ehdr = link_mc + _src_ll + proto
3631     _ip_src = socket.inet_pton(socket.AF_INET6, ip_src)
3632     if ip_dst is None:
3633         ip_dst = ipv6_solicited_node_mcaddr(target)
3634     _ip_dst = socket.inet_pton(socket.AF_INET6, ip_dst)
3635
3636     reserved = '\x00\x00\x00\x00'
3637     _target = socket.inet_pton(socket.AF_INET6, target)
3638     if opt:
3639         payload = reserved + _target + opt
3640     else:
3641         payload = reserved + _target
3642     icmp = build_icmpv6(_ip_src + _ip_dst, 135, 0, payload)
3643
3644     ipv6 = struct.pack('>BBBBHBB', 0x60, 0, 0, 0, len(icmp), 58, 255)
3645     ipv6 += _ip_src + _ip_dst
3646
3647     return ehdr + ipv6 + icmp
3648
3649 def send_ns(dev, src_ll=None, target=None, ip_src=None, ip_dst=None, opt=None,
3650             hapd_bssid=None):
3651     if hapd_bssid:
3652         if src_ll is None:
3653             src_ll = hapd_bssid
3654         cmd = "DATA_TEST_FRAME ifname=ap-br0 "
3655     else:
3656         if src_ll is None:
3657             src_ll = dev.p2p_interface_addr()
3658         cmd = "DATA_TEST_FRAME "
3659
3660     if opt is None:
3661         opt = "\x01\x01" + binascii.unhexlify(src_ll.replace(':',''))
3662
3663     pkt = build_ns(src_ll=src_ll, ip_src=ip_src, ip_dst=ip_dst, target=target,
3664                    opt=opt)
3665     if "OK" not in dev.request(cmd + binascii.hexlify(pkt)):
3666         raise Exception("DATA_TEST_FRAME failed")
3667
3668 def build_na(src_ll, ip_src, ip_dst, target, opt=None, flags=0):
3669     link_mc = binascii.unhexlify("3333ff000002")
3670     _src_ll = binascii.unhexlify(src_ll.replace(':',''))
3671     proto = '\x86\xdd'
3672     ehdr = link_mc + _src_ll + proto
3673     _ip_src = socket.inet_pton(socket.AF_INET6, ip_src)
3674     _ip_dst = socket.inet_pton(socket.AF_INET6, ip_dst)
3675
3676     _target = socket.inet_pton(socket.AF_INET6, target)
3677     if opt:
3678         payload = struct.pack('>Bxxx', flags) + _target + opt
3679     else:
3680         payload = struct.pack('>Bxxx', flags) + _target
3681     icmp = build_icmpv6(_ip_src + _ip_dst, 136, 0, payload)
3682
3683     ipv6 = struct.pack('>BBBBHBB', 0x60, 0, 0, 0, len(icmp), 58, 255)
3684     ipv6 += _ip_src + _ip_dst
3685
3686     return ehdr + ipv6 + icmp
3687
3688 def send_na(dev, src_ll=None, target=None, ip_src=None, ip_dst=None, opt=None,
3689             hapd_bssid=None):
3690     if hapd_bssid:
3691         if src_ll is None:
3692             src_ll = hapd_bssid
3693         cmd = "DATA_TEST_FRAME ifname=ap-br0 "
3694     else:
3695         if src_ll is None:
3696             src_ll = dev.p2p_interface_addr()
3697         cmd = "DATA_TEST_FRAME "
3698
3699     pkt = build_na(src_ll=src_ll, ip_src=ip_src, ip_dst=ip_dst, target=target,
3700                    opt=opt)
3701     if "OK" not in dev.request(cmd + binascii.hexlify(pkt)):
3702         raise Exception("DATA_TEST_FRAME failed")
3703
3704 def build_dhcp_ack(dst_ll, src_ll, ip_src, ip_dst, yiaddr, chaddr,
3705                    subnet_mask="255.255.255.0", truncated_opt=False,
3706                    wrong_magic=False, force_tot_len=None, no_dhcp=False):
3707     _dst_ll = binascii.unhexlify(dst_ll.replace(':',''))
3708     _src_ll = binascii.unhexlify(src_ll.replace(':',''))
3709     proto = '\x08\x00'
3710     ehdr = _dst_ll + _src_ll + proto
3711     _ip_src = socket.inet_pton(socket.AF_INET, ip_src)
3712     _ip_dst = socket.inet_pton(socket.AF_INET, ip_dst)
3713     _subnet_mask = socket.inet_pton(socket.AF_INET, subnet_mask)
3714
3715     _ciaddr = '\x00\x00\x00\x00'
3716     _yiaddr = socket.inet_pton(socket.AF_INET, yiaddr)
3717     _siaddr = '\x00\x00\x00\x00'
3718     _giaddr = '\x00\x00\x00\x00'
3719     _chaddr = binascii.unhexlify(chaddr.replace(':','') + "00000000000000000000")
3720     payload = struct.pack('>BBBBL3BB', 2, 1, 6, 0, 12345, 0, 0, 0, 0)
3721     payload += _ciaddr + _yiaddr + _siaddr + _giaddr + _chaddr + 192*'\x00'
3722     # magic
3723     if wrong_magic:
3724         payload += '\x63\x82\x53\x00'
3725     else:
3726         payload += '\x63\x82\x53\x63'
3727     if truncated_opt:
3728         payload += '\x22\xff\x00'
3729     # Option: DHCP Message Type = ACK
3730     payload += '\x35\x01\x05'
3731     # Pad Option
3732     payload += '\x00'
3733     # Option: Subnet Mask
3734     payload += '\x01\x04' + _subnet_mask
3735     # Option: Time Offset
3736     payload += struct.pack('>BBL', 2, 4, 0)
3737     # End Option
3738     payload += '\xff'
3739     # Pad Option
3740     payload += '\x00\x00\x00\x00'
3741
3742     if no_dhcp:
3743         payload = struct.pack('>BBBBL3BB', 2, 1, 6, 0, 12345, 0, 0, 0, 0)
3744         payload += _ciaddr + _yiaddr + _siaddr + _giaddr + _chaddr + 192*'\x00'
3745
3746     udp = struct.pack('>HHHH', 67, 68, 8 + len(payload), 0) + payload
3747
3748     if force_tot_len:
3749         tot_len = force_tot_len
3750     else:
3751         tot_len = 20 + len(udp)
3752     start = struct.pack('>BBHHBBBB', 0x45, 0, tot_len, 0, 0, 0, 128, 17)
3753     ipv4 = start + '\x00\x00' + _ip_src + _ip_dst
3754     csum = ip_checksum(ipv4)
3755     ipv4 = start + csum + _ip_src + _ip_dst
3756
3757     return ehdr + ipv4 + udp
3758
3759 def build_arp(dst_ll, src_ll, opcode, sender_mac, sender_ip,
3760               target_mac, target_ip):
3761     _dst_ll = binascii.unhexlify(dst_ll.replace(':',''))
3762     _src_ll = binascii.unhexlify(src_ll.replace(':',''))
3763     proto = '\x08\x06'
3764     ehdr = _dst_ll + _src_ll + proto
3765
3766     _sender_mac = binascii.unhexlify(sender_mac.replace(':',''))
3767     _sender_ip = socket.inet_pton(socket.AF_INET, sender_ip)
3768     _target_mac = binascii.unhexlify(target_mac.replace(':',''))
3769     _target_ip = socket.inet_pton(socket.AF_INET, target_ip)
3770
3771     arp = struct.pack('>HHBBH', 1, 0x0800, 6, 4, opcode)
3772     arp += _sender_mac + _sender_ip
3773     arp += _target_mac + _target_ip
3774
3775     return ehdr + arp
3776
3777 def send_arp(dev, dst_ll="ff:ff:ff:ff:ff:ff", src_ll=None, opcode=1,
3778              sender_mac=None, sender_ip="0.0.0.0",
3779              target_mac="00:00:00:00:00:00", target_ip="0.0.0.0",
3780              hapd_bssid=None):
3781     if hapd_bssid:
3782         if src_ll is None:
3783             src_ll = hapd_bssid
3784         if sender_mac is None:
3785             sender_mac = hapd_bssid
3786         cmd = "DATA_TEST_FRAME ifname=ap-br0 "
3787     else:
3788         if src_ll is None:
3789             src_ll = dev.p2p_interface_addr()
3790         if sender_mac is None:
3791             sender_mac = dev.p2p_interface_addr()
3792         cmd = "DATA_TEST_FRAME "
3793
3794     pkt = build_arp(dst_ll=dst_ll, src_ll=src_ll, opcode=opcode,
3795                     sender_mac=sender_mac, sender_ip=sender_ip,
3796                     target_mac=target_mac, target_ip=target_ip)
3797     if "OK" not in dev.request(cmd + binascii.hexlify(pkt)):
3798         raise Exception("DATA_TEST_FRAME failed")
3799
3800 def get_permanent_neighbors(ifname):
3801     cmd = subprocess.Popen(['ip', 'nei'], stdout=subprocess.PIPE)
3802     res = cmd.stdout.read()
3803     cmd.stdout.close()
3804     return [ line for line in res.splitlines() if "PERMANENT" in line and ifname in line ]
3805
3806 def get_bridge_macs(ifname):
3807     cmd = subprocess.Popen(['brctl', 'showmacs', ifname],
3808                            stdout=subprocess.PIPE)
3809     res = cmd.stdout.read()
3810     cmd.stdout.close()
3811     return res
3812
3813 def tshark_get_arp(cap, filter):
3814     res = run_tshark(cap, filter,
3815                      [ "eth.dst", "eth.src",
3816                        "arp.src.hw_mac", "arp.src.proto_ipv4",
3817                        "arp.dst.hw_mac", "arp.dst.proto_ipv4" ],
3818                      wait=False)
3819     frames = []
3820     for l in res.splitlines():
3821         frames.append(l.split('\t'))
3822     return frames
3823
3824 def tshark_get_ns(cap):
3825     res = run_tshark(cap, "icmpv6.type == 135",
3826                      [ "eth.dst", "eth.src",
3827                        "ipv6.src", "ipv6.dst",
3828                        "icmpv6.nd.ns.target_address",
3829                        "icmpv6.opt.linkaddr" ],
3830                      wait=False)
3831     frames = []
3832     for l in res.splitlines():
3833         frames.append(l.split('\t'))
3834     return frames
3835
3836 def tshark_get_na(cap):
3837     res = run_tshark(cap, "icmpv6.type == 136",
3838                      [ "eth.dst", "eth.src",
3839                        "ipv6.src", "ipv6.dst",
3840                        "icmpv6.nd.na.target_address",
3841                        "icmpv6.opt.linkaddr" ],
3842                      wait=False)
3843     frames = []
3844     for l in res.splitlines():
3845         frames.append(l.split('\t'))
3846     return frames
3847
3848 def _test_proxyarp_open(dev, apdev, params, ebtables=False):
3849     prefix = "proxyarp_open"
3850     if ebtables:
3851         prefix += "_ebtables"
3852     cap_br = os.path.join(params['logdir'], prefix + ".ap-br0.pcap")
3853     cap_dev0 = os.path.join(params['logdir'],
3854                             prefix + ".%s.pcap" % dev[0].ifname)
3855     cap_dev1 = os.path.join(params['logdir'],
3856                             prefix + ".%s.pcap" % dev[1].ifname)
3857     cap_dev2 = os.path.join(params['logdir'],
3858                             prefix + ".%s.pcap" % dev[2].ifname)
3859
3860     bssid = apdev[0]['bssid']
3861     params = { 'ssid': 'open' }
3862     params['proxy_arp'] = '1'
3863     hapd = hostapd.add_ap(apdev[0], params, no_enable=True)
3864     hapd.set("ap_isolate", "1")
3865     hapd.set('bridge', 'ap-br0')
3866     hapd.dump_monitor()
3867     try:
3868         hapd.enable()
3869     except:
3870         # For now, do not report failures due to missing kernel support
3871         raise HwsimSkip("Could not start hostapd - assume proxyarp not supported in kernel version")
3872     ev = hapd.wait_event(["AP-ENABLED", "AP-DISABLED"], timeout=10)
3873     if ev is None:
3874         raise Exception("AP startup timed out")
3875     if "AP-ENABLED" not in ev:
3876         raise Exception("AP startup failed")
3877
3878     params2 = { 'ssid': 'another' }
3879     hapd2 = hostapd.add_ap(apdev[1], params2, no_enable=True)
3880     hapd2.set('bridge', 'ap-br0')
3881     hapd2.enable()
3882
3883     subprocess.call(['brctl', 'setfd', 'ap-br0', '0'])
3884     subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'up'])
3885
3886     if ebtables:
3887         for chain in [ 'FORWARD', 'OUTPUT' ]:
3888             subprocess.call(['ebtables', '-A', chain, '-p', 'ARP',
3889                              '-d', 'Broadcast', '-o', apdev[0]['ifname'],
3890                              '-j', 'DROP'])
3891             subprocess.call(['ebtables', '-A', chain, '-d', 'Multicast',
3892                              '-p', 'IPv6', '--ip6-protocol', 'ipv6-icmp',
3893                              '--ip6-icmp-type', 'neighbor-solicitation',
3894                              '-o', apdev[0]['ifname'], '-j', 'DROP'])
3895             subprocess.call(['ebtables', '-A', chain, '-d', 'Multicast',
3896                              '-p', 'IPv6', '--ip6-protocol', 'ipv6-icmp',
3897                              '--ip6-icmp-type', 'neighbor-advertisement',
3898                              '-o', apdev[0]['ifname'], '-j', 'DROP'])
3899             subprocess.call(['ebtables', '-A', chain,
3900                              '-p', 'IPv6', '--ip6-protocol', 'ipv6-icmp',
3901                              '--ip6-icmp-type', 'router-solicitation',
3902                              '-o', apdev[0]['ifname'], '-j', 'DROP'])
3903             # Multicast Listener Report Message
3904             subprocess.call(['ebtables', '-A', chain, '-d', 'Multicast',
3905                              '-p', 'IPv6', '--ip6-protocol', 'ipv6-icmp',
3906                              '--ip6-icmp-type', '143',
3907                              '-o', apdev[0]['ifname'], '-j', 'DROP'])
3908
3909     time.sleep(0.5)
3910     cmd = {}
3911     cmd[0] = subprocess.Popen(['tcpdump', '-p', '-U', '-i', 'ap-br0',
3912                                '-w', cap_br, '-s', '2000'],
3913                               stderr=open('/dev/null', 'w'))
3914     cmd[1] = subprocess.Popen(['tcpdump', '-p', '-U', '-i', dev[0].ifname,
3915                                '-w', cap_dev0, '-s', '2000'],
3916                               stderr=open('/dev/null', 'w'))
3917     cmd[2] = subprocess.Popen(['tcpdump', '-p', '-U', '-i', dev[1].ifname,
3918                                '-w', cap_dev1, '-s', '2000'],
3919                               stderr=open('/dev/null', 'w'))
3920     cmd[3] = subprocess.Popen(['tcpdump', '-p', '-U', '-i', dev[2].ifname,
3921                                '-w', cap_dev2, '-s', '2000'],
3922                               stderr=open('/dev/null', 'w'))
3923
3924     dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3925     dev[1].connect("open", key_mgmt="NONE", scan_freq="2412")
3926     dev[2].connect("another", key_mgmt="NONE", scan_freq="2412")
3927     time.sleep(0.1)
3928
3929     brcmd = subprocess.Popen(['brctl', 'show'], stdout=subprocess.PIPE)
3930     res = brcmd.stdout.read()
3931     brcmd.stdout.close()
3932     logger.info("Bridge setup: " + res)
3933
3934     brcmd = subprocess.Popen(['brctl', 'showstp', 'ap-br0'],
3935                              stdout=subprocess.PIPE)
3936     res = brcmd.stdout.read()
3937     brcmd.stdout.close()
3938     logger.info("Bridge showstp: " + res)
3939
3940     addr0 = dev[0].p2p_interface_addr()
3941     addr1 = dev[1].p2p_interface_addr()
3942     addr2 = dev[2].p2p_interface_addr()
3943
3944     src_ll_opt0 = "\x01\x01" + binascii.unhexlify(addr0.replace(':',''))
3945     src_ll_opt1 = "\x01\x01" + binascii.unhexlify(addr1.replace(':',''))
3946
3947     # DAD NS
3948     send_ns(dev[0], ip_src="::", target="aaaa:bbbb:cccc::2")
3949
3950     send_ns(dev[0], ip_src="aaaa:bbbb:cccc::2", target="aaaa:bbbb:cccc::2")
3951     # test frame without source link-layer address option
3952     send_ns(dev[0], ip_src="aaaa:bbbb:cccc::2", target="aaaa:bbbb:cccc::2",
3953             opt='')
3954     # test frame with bogus option
3955     send_ns(dev[0], ip_src="aaaa:bbbb:cccc::2", target="aaaa:bbbb:cccc::2",
3956             opt="\x70\x01\x01\x02\x03\x04\x05\x05")
3957     # test frame with truncated source link-layer address option
3958     send_ns(dev[0], ip_src="aaaa:bbbb:cccc::2", target="aaaa:bbbb:cccc::2",
3959             opt="\x01\x01\x01\x02\x03\x04")
3960     # test frame with foreign source link-layer address option
3961     send_ns(dev[0], ip_src="aaaa:bbbb:cccc::2", target="aaaa:bbbb:cccc::2",
3962             opt="\x01\x01\x01\x02\x03\x04\x05\x06")
3963
3964     send_ns(dev[1], ip_src="aaaa:bbbb:dddd::2", target="aaaa:bbbb:dddd::2")
3965
3966     send_ns(dev[1], ip_src="aaaa:bbbb:eeee::2", target="aaaa:bbbb:eeee::2")
3967     # another copy for additional code coverage
3968     send_ns(dev[1], ip_src="aaaa:bbbb:eeee::2", target="aaaa:bbbb:eeee::2")
3969
3970     pkt = build_dhcp_ack(dst_ll="ff:ff:ff:ff:ff:ff", src_ll=bssid,
3971                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
3972                          yiaddr="192.168.1.124", chaddr=addr0)
3973     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
3974         raise Exception("DATA_TEST_FRAME failed")
3975     # Change address and verify unicast
3976     pkt = build_dhcp_ack(dst_ll=addr0, src_ll=bssid,
3977                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
3978                          yiaddr="192.168.1.123", chaddr=addr0)
3979     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
3980         raise Exception("DATA_TEST_FRAME failed")
3981
3982     # Not-associated client MAC address
3983     pkt = build_dhcp_ack(dst_ll="ff:ff:ff:ff:ff:ff", src_ll=bssid,
3984                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
3985                          yiaddr="192.168.1.125", chaddr="22:33:44:55:66:77")
3986     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
3987         raise Exception("DATA_TEST_FRAME failed")
3988
3989     # No IP address
3990     pkt = build_dhcp_ack(dst_ll=addr1, src_ll=bssid,
3991                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
3992                          yiaddr="0.0.0.0", chaddr=addr1)
3993     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
3994         raise Exception("DATA_TEST_FRAME failed")
3995
3996     # Zero subnet mask
3997     pkt = build_dhcp_ack(dst_ll=addr1, src_ll=bssid,
3998                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
3999                          yiaddr="192.168.1.126", chaddr=addr1,
4000                          subnet_mask="0.0.0.0")
4001     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
4002         raise Exception("DATA_TEST_FRAME failed")
4003
4004     # Truncated option
4005     pkt = build_dhcp_ack(dst_ll=addr1, src_ll=bssid,
4006                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
4007                          yiaddr="192.168.1.127", chaddr=addr1,
4008                          truncated_opt=True)
4009     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
4010         raise Exception("DATA_TEST_FRAME failed")
4011
4012     # Wrong magic
4013     pkt = build_dhcp_ack(dst_ll=addr1, src_ll=bssid,
4014                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
4015                          yiaddr="192.168.1.128", chaddr=addr1,
4016                          wrong_magic=True)
4017     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
4018         raise Exception("DATA_TEST_FRAME failed")
4019
4020     # Wrong IPv4 total length
4021     pkt = build_dhcp_ack(dst_ll=addr1, src_ll=bssid,
4022                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
4023                          yiaddr="192.168.1.129", chaddr=addr1,
4024                          force_tot_len=1000)
4025     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
4026         raise Exception("DATA_TEST_FRAME failed")
4027
4028     # BOOTP
4029     pkt = build_dhcp_ack(dst_ll=addr1, src_ll=bssid,
4030                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
4031                          yiaddr="192.168.1.129", chaddr=addr1,
4032                          no_dhcp=True)
4033     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
4034         raise Exception("DATA_TEST_FRAME failed")
4035
4036     macs = get_bridge_macs("ap-br0")
4037     logger.info("After connect (showmacs): " + str(macs))
4038
4039     matches = get_permanent_neighbors("ap-br0")
4040     logger.info("After connect: " + str(matches))
4041     if len(matches) != 4:
4042         raise Exception("Unexpected number of neighbor entries after connect")
4043     if 'aaaa:bbbb:cccc::2 dev ap-br0 lladdr 02:00:00:00:00:00 PERMANENT' not in matches:
4044         raise Exception("dev0 addr missing")
4045     if 'aaaa:bbbb:dddd::2 dev ap-br0 lladdr 02:00:00:00:01:00 PERMANENT' not in matches:
4046         raise Exception("dev1 addr(1) missing")
4047     if 'aaaa:bbbb:eeee::2 dev ap-br0 lladdr 02:00:00:00:01:00 PERMANENT' not in matches:
4048         raise Exception("dev1 addr(2) missing")
4049     if '192.168.1.123 dev ap-br0 lladdr 02:00:00:00:00:00 PERMANENT' not in matches:
4050         raise Exception("dev0 IPv4 addr missing")
4051
4052     targets = [ "192.168.1.123", "192.168.1.124", "192.168.1.125",
4053                 "192.168.1.126" ]
4054     for target in targets:
4055         send_arp(dev[1], sender_ip="192.168.1.100", target_ip=target)
4056
4057     for target in targets:
4058         send_arp(hapd, hapd_bssid=bssid, sender_ip="192.168.1.101",
4059                  target_ip=target)
4060
4061     for target in targets:
4062         send_arp(dev[2], sender_ip="192.168.1.103", target_ip=target)
4063
4064     # ARP Probe from wireless STA
4065     send_arp(dev[1], target_ip="192.168.1.127")
4066     # ARP Announcement from wireless STA
4067     send_arp(dev[1], sender_ip="192.168.1.127", target_ip="192.168.1.127")
4068     send_arp(dev[1], sender_ip="192.168.1.127", target_ip="192.168.1.127",
4069              opcode=2)
4070
4071     macs = get_bridge_macs("ap-br0")
4072     logger.info("After ARP Probe + Announcement (showmacs): " + str(macs))
4073
4074     matches = get_permanent_neighbors("ap-br0")
4075     logger.info("After ARP Probe + Announcement: " + str(matches))
4076
4077     # ARP Request for the newly introduced IP address from wireless STA
4078     send_arp(dev[0], sender_ip="192.168.1.123", target_ip="192.168.1.127")
4079
4080     # ARP Request for the newly introduced IP address from bridge
4081     send_arp(hapd, hapd_bssid=bssid, sender_ip="192.168.1.102",
4082              target_ip="192.168.1.127")
4083     send_arp(dev[2], sender_ip="192.168.1.103", target_ip="192.168.1.127")
4084
4085     # ARP Probe from bridge
4086     send_arp(hapd, hapd_bssid=bssid, target_ip="192.168.1.130")
4087     send_arp(dev[2], target_ip="192.168.1.131")
4088     # ARP Announcement from bridge (not to be learned by AP for proxyarp)
4089     send_arp(hapd, hapd_bssid=bssid, sender_ip="192.168.1.130",
4090              target_ip="192.168.1.130")
4091     send_arp(hapd, hapd_bssid=bssid, sender_ip="192.168.1.130",
4092              target_ip="192.168.1.130", opcode=2)
4093     send_arp(dev[2], sender_ip="192.168.1.131", target_ip="192.168.1.131")
4094     send_arp(dev[2], sender_ip="192.168.1.131", target_ip="192.168.1.131",
4095              opcode=2)
4096
4097     macs = get_bridge_macs("ap-br0")
4098     logger.info("After ARP Probe + Announcement (showmacs): " + str(macs))
4099
4100     matches = get_permanent_neighbors("ap-br0")
4101     logger.info("After ARP Probe + Announcement: " + str(matches))
4102
4103     # ARP Request for the newly introduced IP address from wireless STA
4104     send_arp(dev[0], sender_ip="192.168.1.123", target_ip="192.168.1.130")
4105     # ARP Response from bridge (AP does not proxy for non-wireless devices)
4106     send_arp(hapd, hapd_bssid=bssid, dst_ll=addr0, sender_ip="192.168.1.130",
4107              target_ip="192.168.1.123", opcode=2)
4108
4109     # ARP Request for the newly introduced IP address from wireless STA
4110     send_arp(dev[0], sender_ip="192.168.1.123", target_ip="192.168.1.131")
4111     # ARP Response from bridge (AP does not proxy for non-wireless devices)
4112     send_arp(dev[2], dst_ll=addr0, sender_ip="192.168.1.131",
4113              target_ip="192.168.1.123", opcode=2)
4114
4115     # ARP Request for the newly introduced IP address from bridge
4116     send_arp(hapd, hapd_bssid=bssid, sender_ip="192.168.1.102",
4117              target_ip="192.168.1.130")
4118     send_arp(dev[2], sender_ip="192.168.1.104", target_ip="192.168.1.131")
4119
4120     # ARP Probe from wireless STA (duplicate address; learned through DHCP)
4121     send_arp(dev[1], target_ip="192.168.1.123")
4122     # ARP Probe from wireless STA (duplicate address; learned through ARP)
4123     send_arp(dev[0], target_ip="192.168.1.127")
4124
4125     # Gratuitous ARP Reply for another STA's IP address
4126     send_arp(dev[0], opcode=2, sender_mac=addr0, sender_ip="192.168.1.127",
4127              target_mac=addr1, target_ip="192.168.1.127")
4128     send_arp(dev[1], opcode=2, sender_mac=addr1, sender_ip="192.168.1.123",
4129              target_mac=addr0, target_ip="192.168.1.123")
4130     # ARP Request to verify previous mapping
4131     send_arp(dev[1], sender_ip="192.168.1.127", target_ip="192.168.1.123")
4132     send_arp(dev[0], sender_ip="192.168.1.123", target_ip="192.168.1.127")
4133
4134     time.sleep(0.1)
4135
4136     send_ns(dev[0], target="aaaa:bbbb:dddd::2", ip_src="aaaa:bbbb:cccc::2")
4137     time.sleep(0.1)
4138     send_ns(dev[1], target="aaaa:bbbb:cccc::2", ip_src="aaaa:bbbb:dddd::2")
4139     time.sleep(0.1)
4140     send_ns(hapd, hapd_bssid=bssid, target="aaaa:bbbb:dddd::2",
4141             ip_src="aaaa:bbbb:ffff::2")
4142     time.sleep(0.1)
4143     send_ns(dev[2], target="aaaa:bbbb:cccc::2", ip_src="aaaa:bbbb:ff00::2")
4144     time.sleep(0.1)
4145     send_ns(dev[2], target="aaaa:bbbb:dddd::2", ip_src="aaaa:bbbb:ff00::2")
4146     time.sleep(0.1)
4147     send_ns(dev[2], target="aaaa:bbbb:eeee::2", ip_src="aaaa:bbbb:ff00::2")
4148     time.sleep(0.1)
4149
4150     # Try to probe for an already assigned address
4151     send_ns(dev[1], target="aaaa:bbbb:cccc::2", ip_src="::")
4152     time.sleep(0.1)
4153     send_ns(hapd, hapd_bssid=bssid, target="aaaa:bbbb:cccc::2", ip_src="::")
4154     time.sleep(0.1)
4155     send_ns(dev[2], target="aaaa:bbbb:cccc::2", ip_src="::")
4156     time.sleep(0.1)
4157
4158     # Unsolicited NA
4159     send_na(dev[1], target="aaaa:bbbb:cccc:aeae::3",
4160             ip_src="aaaa:bbbb:cccc:aeae::3", ip_dst="ff02::1")
4161     send_na(hapd, hapd_bssid=bssid, target="aaaa:bbbb:cccc:aeae::4",
4162             ip_src="aaaa:bbbb:cccc:aeae::4", ip_dst="ff02::1")
4163     send_na(dev[2], target="aaaa:bbbb:cccc:aeae::5",
4164             ip_src="aaaa:bbbb:cccc:aeae::5", ip_dst="ff02::1")
4165
4166     try:
4167         hwsim_utils.test_connectivity_iface(dev[0], hapd, "ap-br0")
4168     except Exception, e:
4169         logger.info("test_connectibity_iface failed: " + str(e))
4170         raise HwsimSkip("Assume kernel did not have the required patches for proxyarp")
4171     hwsim_utils.test_connectivity_iface(dev[1], hapd, "ap-br0")
4172     hwsim_utils.test_connectivity(dev[0], dev[1])
4173
4174     dev[0].request("DISCONNECT")
4175     dev[1].request("DISCONNECT")
4176     time.sleep(0.5)
4177     for i in range(len(cmd)):
4178         cmd[i].terminate()
4179     macs = get_bridge_macs("ap-br0")
4180     logger.info("After disconnect (showmacs): " + str(macs))
4181     matches = get_permanent_neighbors("ap-br0")
4182     logger.info("After disconnect: " + str(matches))
4183     if len(matches) > 0:
4184         raise Exception("Unexpected neighbor entries after disconnect")
4185     if ebtables:
4186         cmd = subprocess.Popen(['ebtables', '-L', '--Lc'],
4187                                stdout=subprocess.PIPE)
4188         res = cmd.stdout.read()
4189         cmd.stdout.close()
4190         logger.info("ebtables results:\n" + res)
4191
4192     # Verify that expected ARP messages were seen and no unexpected
4193     # ARP messages were seen.
4194
4195     arp_req = tshark_get_arp(cap_dev0, "arp.opcode == 1")
4196     arp_reply = tshark_get_arp(cap_dev0, "arp.opcode == 2")
4197     logger.info("dev0 seen ARP requests:\n" + str(arp_req))
4198     logger.info("dev0 seen ARP replies:\n" + str(arp_reply))
4199
4200     if [ 'ff:ff:ff:ff:ff:ff', addr1,
4201          addr1, '192.168.1.100',
4202          '00:00:00:00:00:00', '192.168.1.123' ] in arp_req:
4203         raise Exception("dev0 saw ARP request from dev1")
4204     if [ 'ff:ff:ff:ff:ff:ff', addr2,
4205          addr2, '192.168.1.103',
4206          '00:00:00:00:00:00', '192.168.1.123' ] in arp_req:
4207         raise Exception("dev0 saw ARP request from dev2")
4208     # TODO: Uncomment once fixed in kernel
4209     #if [ 'ff:ff:ff:ff:ff:ff', bssid,
4210     #     bssid, '192.168.1.101',
4211     #     '00:00:00:00:00:00', '192.168.1.123' ] in arp_req:
4212     #    raise Exception("dev0 saw ARP request from br")
4213
4214     if ebtables:
4215         for req in arp_req:
4216             if req[1] != addr0:
4217                 raise Exception("Unexpected foreign ARP request on dev0")
4218
4219     arp_req = tshark_get_arp(cap_dev1, "arp.opcode == 1")
4220     arp_reply = tshark_get_arp(cap_dev1, "arp.opcode == 2")
4221     logger.info("dev1 seen ARP requests:\n" + str(arp_req))
4222     logger.info("dev1 seen ARP replies:\n" + str(arp_reply))
4223
4224     if [ 'ff:ff:ff:ff:ff:ff', addr2,
4225          addr2, '192.168.1.103',
4226          '00:00:00:00:00:00', '192.168.1.123' ] in arp_req:
4227         raise Exception("dev1 saw ARP request from dev2")
4228     if [addr1, addr0, addr0, '192.168.1.123', addr1, '192.168.1.100'] not in arp_reply:
4229         raise Exception("dev1 did not get ARP response for 192.168.1.123")
4230
4231     if ebtables:
4232         for req in arp_req:
4233             if req[1] != addr1:
4234                 raise Exception("Unexpected foreign ARP request on dev1")
4235
4236     arp_req = tshark_get_arp(cap_dev2, "arp.opcode == 1")
4237     arp_reply = tshark_get_arp(cap_dev2, "arp.opcode == 2")
4238     logger.info("dev2 seen ARP requests:\n" + str(arp_req))
4239     logger.info("dev2 seen ARP replies:\n" + str(arp_reply))
4240
4241     if [ addr2, addr0,
4242          addr0, '192.168.1.123',
4243          addr2, '192.168.1.103' ] not in arp_reply:
4244         raise Exception("dev2 did not get ARP response for 192.168.1.123")
4245
4246     arp_req = tshark_get_arp(cap_br, "arp.opcode == 1")
4247     arp_reply = tshark_get_arp(cap_br, "arp.opcode == 2")
4248     logger.info("br seen ARP requests:\n" + str(arp_req))
4249     logger.info("br seen ARP replies:\n" + str(arp_reply))
4250
4251     # TODO: Uncomment once fixed in kernel
4252     #if [ bssid, addr0,
4253     #     addr0, '192.168.1.123',
4254     #     bssid, '192.168.1.101' ] not in arp_reply:
4255     #    raise Exception("br did not get ARP response for 192.168.1.123")
4256
4257     ns = tshark_get_ns(cap_dev0)
4258     logger.info("dev0 seen NS: " + str(ns))
4259     na = tshark_get_na(cap_dev0)
4260     logger.info("dev0 seen NA: " + str(na))
4261
4262     if [ addr0, addr1, 'aaaa:bbbb:dddd::2', 'aaaa:bbbb:cccc::2',
4263          'aaaa:bbbb:dddd::2', addr1 ] not in na:
4264         raise Exception("dev0 did not get NA for aaaa:bbbb:dddd::2")
4265
4266     if ebtables:
4267         for req in ns:
4268             if req[1] != addr0:
4269                 raise Exception("Unexpected foreign NS on dev0: " + str(req))
4270
4271     ns = tshark_get_ns(cap_dev1)
4272     logger.info("dev1 seen NS: " + str(ns))
4273     na = tshark_get_na(cap_dev1)
4274     logger.info("dev1 seen NA: " + str(na))
4275
4276     if [ addr1, addr0, 'aaaa:bbbb:cccc::2', 'aaaa:bbbb:dddd::2',
4277          'aaaa:bbbb:cccc::2', addr0 ] not in na:
4278         raise Exception("dev1 did not get NA for aaaa:bbbb:cccc::2")
4279
4280     if ebtables:
4281         for req in ns:
4282             if req[1] != addr1:
4283                 raise Exception("Unexpected foreign NS on dev1: " + str(req))
4284
4285     ns = tshark_get_ns(cap_dev2)
4286     logger.info("dev2 seen NS: " + str(ns))
4287     na = tshark_get_na(cap_dev2)
4288     logger.info("dev2 seen NA: " + str(na))
4289
4290     # FIX: enable once kernel implementation for proxyarp IPv6 is fixed
4291     #if [ addr2, addr0, 'aaaa:bbbb:cccc::2', 'aaaa:bbbb:ff00::2',
4292     #     'aaaa:bbbb:cccc::2', addr0 ] not in na:
4293     #    raise Exception("dev2 did not get NA for aaaa:bbbb:cccc::2")
4294     #if [ addr2, addr1, 'aaaa:bbbb:dddd::2', 'aaaa:bbbb:ff00::2',
4295     #     'aaaa:bbbb:dddd::2', addr1 ] not in na:
4296     #    raise Exception("dev2 did not get NA for aaaa:bbbb:dddd::2")
4297     #if [ addr2, addr1, 'aaaa:bbbb:eeee::2', 'aaaa:bbbb:ff00::2',
4298     #     'aaaa:bbbb:eeee::2', addr1 ] not in na:
4299     #    raise Exception("dev2 did not get NA for aaaa:bbbb:eeee::2")
4300
4301 def test_proxyarp_open(dev, apdev, params):
4302     """ProxyARP with open network"""
4303     try:
4304         _test_proxyarp_open(dev, apdev, params)
4305     finally:
4306         subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'down'],
4307                         stderr=open('/dev/null', 'w'))
4308         subprocess.call(['brctl', 'delbr', 'ap-br0'],
4309                         stderr=open('/dev/null', 'w'))
4310
4311 def test_proxyarp_open_ebtables(dev, apdev, params):
4312     """ProxyARP with open network"""
4313     try:
4314         _test_proxyarp_open(dev, apdev, params, ebtables=True)
4315     finally:
4316         try:
4317             subprocess.call(['ebtables', '-F', 'FORWARD'])
4318             subprocess.call(['ebtables', '-F', 'OUTPUT'])
4319         except:
4320             pass
4321         subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'down'],
4322                         stderr=open('/dev/null', 'w'))
4323         subprocess.call(['brctl', 'delbr', 'ap-br0'],
4324                         stderr=open('/dev/null', 'w'))
4325
4326 def test_ap_hs20_connect_deinit(dev, apdev):
4327     """Hotspot 2.0 connection interrupted with deinit"""
4328     check_eap_capa(dev[0], "MSCHAPV2")
4329     bssid = apdev[0]['bssid']
4330     params = hs20_ap_params()
4331     params['hessid'] = bssid
4332     hapd = hostapd.add_ap(apdev[0], params)
4333
4334     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
4335     wpas.interface_add("wlan5", drv_params="")
4336     wpas.hs20_enable()
4337     wpas.flush_scan_cache()
4338     wpas.add_cred_values({ 'realm': "example.com",
4339                            'username': "hs20-test",
4340                            'password': "password",
4341                            'ca_cert': "auth_serv/ca.pem",
4342                            'domain': "example.com" })
4343
4344     wpas.scan_for_bss(bssid, freq=2412)
4345     hapd.disable()
4346
4347     wpas.request("INTERWORKING_SELECT freq=2412")
4348
4349     id = wpas.request("RADIO_WORK add block-work")
4350     ev = wpas.wait_event(["GAS-QUERY-START", "EXT-RADIO-WORK-START"], timeout=5)
4351     if ev is None:
4352         raise Exception("Timeout while waiting radio work to start")
4353     ev = wpas.wait_event(["GAS-QUERY-START", "EXT-RADIO-WORK-START"], timeout=5)
4354     if ev is None:
4355         raise Exception("Timeout while waiting radio work to start (2)")
4356
4357     # Remove the interface while the gas-query radio work is still pending and
4358     # GAS query has not yet been started.
4359     wpas.interface_remove("wlan5")
4360
4361 def test_ap_hs20_anqp_format_errors(dev, apdev):
4362     """Interworking network selection and ANQP format errors"""
4363     bssid = apdev[0]['bssid']
4364     params = hs20_ap_params()
4365     params['hessid'] = bssid
4366     hapd = hostapd.add_ap(apdev[0], params)
4367
4368     dev[0].hs20_enable()
4369     values = { 'realm': "example.com",
4370                'ca_cert': "auth_serv/ca.pem",
4371                'username': "hs20-test",
4372                'password': "password",
4373                'domain': "example.com" }
4374     id = dev[0].add_cred_values(values)
4375
4376     dev[0].scan_for_bss(bssid, freq="2412")
4377
4378     tests = [ "00", "ffff", "010011223344", "020008000005112233445500",
4379               "01000400000000", "01000000000000",
4380               "01000300000200", "0100040000ff0000", "01000300000100",
4381               "01000300000001",
4382               "01000600000056112233",
4383               "01000900000002050001000111",
4384               "01000600000001000000", "01000600000001ff0000",
4385               "01000600000001020001",
4386               "010008000000010400010001", "0100080000000104000100ff",
4387               "010011000000010d00050200020100030005000600",
4388               "0000" ]
4389     for t in tests:
4390         hapd.set("anqp_elem", "263:" + t)
4391         dev[0].request("INTERWORKING_SELECT freq=2412")
4392         ev = dev[0].wait_event(["INTERWORKING-NO-MATCH"], timeout=5)
4393         if ev is None:
4394             raise Exception("Network selection timed out")
4395         dev[0].dump_monitor()
4396
4397     dev[0].remove_cred(id)
4398     id = dev[0].add_cred_values({ 'imsi': "555444-333222111", 'eap': "AKA",
4399                                   'milenage': "5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123"})
4400
4401     tests = [ "00", "0100", "0001", "00ff", "000200ff", "0003000101",
4402               "00020100" ]
4403     for t in tests:
4404         hapd.set("anqp_elem", "264:" + t)
4405         dev[0].request("INTERWORKING_SELECT freq=2412")
4406         ev = dev[0].wait_event(["INTERWORKING-NO-MATCH"], timeout=5)
4407         if ev is None:
4408             raise Exception("Network selection timed out")
4409         dev[0].dump_monitor()
4410
4411 def test_ap_hs20_cred_with_nai_realm(dev, apdev):
4412     """Hotspot 2.0 network selection and cred_with_nai_realm cred->realm"""
4413     bssid = apdev[0]['bssid']
4414     params = hs20_ap_params()
4415     params['hessid'] = bssid
4416     hostapd.add_ap(apdev[0], params)
4417
4418     dev[0].hs20_enable()
4419
4420     id = dev[0].add_cred_values({ 'realm': "example.com",
4421                                   'username': "test",
4422                                   'password': "secret",
4423                                   'domain': "example.com",
4424                                   'eap': 'TTLS' })
4425     interworking_select(dev[0], bssid, "home", freq=2412)
4426     dev[0].remove_cred(id)
4427
4428     id = dev[0].add_cred_values({ 'realm': "foo.com",
4429                                   'username': "test",
4430                                   'password': "secret",
4431                                   'domain': "example.com",
4432                                   'roaming_consortium': "112234",
4433                                   'eap': 'TTLS' })
4434     interworking_select(dev[0], bssid, "home", freq=2412, no_match=True)
4435     dev[0].remove_cred(id)
4436
4437 def test_ap_hs20_cred_and_no_roaming_consortium(dev, apdev):
4438     """Hotspot 2.0 network selection and no roaming consortium"""
4439     bssid = apdev[0]['bssid']
4440     params = hs20_ap_params()
4441     params['hessid'] = bssid
4442     del params['roaming_consortium']
4443     hostapd.add_ap(apdev[0], params)
4444
4445     dev[0].hs20_enable()
4446
4447     id = dev[0].add_cred_values({ 'realm': "example.com",
4448                                   'username': "test",
4449                                   'password': "secret",
4450                                   'domain': "example.com",
4451                                   'roaming_consortium': "112234",
4452                                   'eap': 'TTLS' })
4453     interworking_select(dev[0], bssid, "home", freq=2412, no_match=True)
4454
4455 def test_ap_hs20_interworking_oom(dev, apdev):
4456     """Hotspot 2.0 network selection and OOM"""
4457     bssid = apdev[0]['bssid']
4458     params = hs20_ap_params()
4459     params['hessid'] = bssid
4460     params['nai_realm'] = [ "0,no.match.here;example.com;no.match.here.either,21[2:1][5:7]",
4461                             "0,example.com,13[5:6],21[2:4][5:7]",
4462                             "0,another.example.com" ]
4463     hostapd.add_ap(apdev[0], params)
4464
4465     dev[0].hs20_enable()
4466
4467     id = dev[0].add_cred_values({ 'realm': "example.com",
4468                                   'username': "test",
4469                                   'password': "secret",
4470                                   'domain': "example.com",
4471                                   'eap': 'TTLS' })
4472
4473     dev[0].scan_for_bss(bssid, freq="2412")
4474
4475     funcs = [ "wpabuf_alloc;interworking_anqp_send_req",
4476               "anqp_build_req;interworking_anqp_send_req",
4477               "gas_query_req;interworking_anqp_send_req",
4478               "dup_binstr;nai_realm_parse_realm",
4479               "=nai_realm_parse_realm",
4480               "=nai_realm_parse",
4481               "=nai_realm_match" ]
4482     for func in funcs:
4483         with alloc_fail(dev[0], 1, func):
4484             dev[0].request("INTERWORKING_SELECT auto freq=2412")
4485             ev = dev[0].wait_event(["Starting ANQP"], timeout=5)
4486             if ev is None:
4487                 raise Exception("ANQP did not start")
4488             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4489
4490 def test_ap_hs20_no_cred_connect(dev, apdev):
4491     """Hotspot 2.0 and connect attempt without credential"""
4492     bssid = apdev[0]['bssid']
4493     params = hs20_ap_params()
4494     params['hessid'] = bssid
4495     hapd = hostapd.add_ap(apdev[0], params)
4496
4497     dev[0].hs20_enable()
4498     dev[0].scan_for_bss(bssid, freq="2412")
4499     if "FAIL" not in dev[0].request("INTERWORKING_CONNECT " + bssid):
4500         raise Exception("Unexpected INTERWORKING_CONNECT success")
4501
4502 def test_ap_hs20_no_rsn_connect(dev, apdev):
4503     """Hotspot 2.0 and connect attempt without RSN"""
4504     bssid = apdev[0]['bssid']
4505     params = hostapd.wpa_params(ssid="test-hs20")
4506     params['wpa_key_mgmt'] = "WPA-EAP"
4507     params['ieee80211w'] = "1"
4508     params['ieee8021x'] = "1"
4509     params['auth_server_addr'] = "127.0.0.1"
4510     params['auth_server_port'] = "1812"
4511     params['auth_server_shared_secret'] = "radius"
4512     params['interworking'] = "1"
4513     params['roaming_consortium'] = [ "112233", "1020304050", "010203040506",
4514                                      "fedcba" ]
4515     params['nai_realm'] = [ "0,example.com,13[5:6],21[2:4][5:7]",
4516                             "0,another.example.com" ]
4517     hapd = hostapd.add_ap(apdev[0], params)
4518
4519     dev[0].hs20_enable()
4520     dev[0].scan_for_bss(bssid, freq="2412")
4521
4522     id = dev[0].add_cred_values({ 'realm': "example.com",
4523                                   'username': "test",
4524                                   'password': "secret",
4525                                   'domain': "example.com",
4526                                   'roaming_consortium': "112233",
4527                                   'eap': 'TTLS' })
4528
4529     interworking_select(dev[0], bssid, freq=2412, no_match=True)
4530     if "FAIL" not in dev[0].request("INTERWORKING_CONNECT " + bssid):
4531         raise Exception("Unexpected INTERWORKING_CONNECT success")
4532
4533 def test_ap_hs20_no_match_connect(dev, apdev):
4534     """Hotspot 2.0 and connect attempt without matching cred"""
4535     bssid = apdev[0]['bssid']
4536     params = hs20_ap_params()
4537     hapd = hostapd.add_ap(apdev[0], params)
4538
4539     dev[0].hs20_enable()
4540     dev[0].scan_for_bss(bssid, freq="2412")
4541
4542     id = dev[0].add_cred_values({ 'realm': "example.org",
4543                                   'username': "test",
4544                                   'password': "secret",
4545                                   'domain': "example.org",
4546                                   'roaming_consortium': "112234",
4547                                   'eap': 'TTLS' })
4548
4549     interworking_select(dev[0], bssid, freq=2412, no_match=True)
4550     if "FAIL" not in dev[0].request("INTERWORKING_CONNECT " + bssid):
4551         raise Exception("Unexpected INTERWORKING_CONNECT success")
4552
4553 def test_ap_hs20_multiple_home_cred(dev, apdev):
4554     """Hotspot 2.0 and select with multiple matching home credentials"""
4555     bssid = apdev[0]['bssid']
4556     params = hs20_ap_params()
4557     params['hessid'] = bssid
4558     params['nai_realm'] = [ "0,example.com,13[5:6],21[2:4][5:7]" ]
4559     params['domain_name'] = "example.com"
4560     hapd = hostapd.add_ap(apdev[0], params)
4561
4562     bssid2 = apdev[1]['bssid']
4563     params = hs20_ap_params(ssid="test-hs20-other")
4564     params['hessid'] = bssid2
4565     params['nai_realm'] = [ "0,example.org,13[5:6],21[2:4][5:7]" ]
4566     params['domain_name'] = "example.org"
4567     hapd2 = hostapd.add_ap(apdev[1], params)
4568
4569     dev[0].hs20_enable()
4570     dev[0].scan_for_bss(bssid2, freq="2412")
4571     dev[0].scan_for_bss(bssid, freq="2412")
4572     id = dev[0].add_cred_values({ 'realm': "example.com",
4573                                   'priority': '2',
4574                                   'username': "hs20-test",
4575                                   'password': "password",
4576                                   'domain': "example.com" })
4577     id2 = dev[0].add_cred_values({ 'realm': "example.org",
4578                                    'priority': '3',
4579                                    'username': "hs20-test",
4580                                    'password': "password",
4581                                    'domain': "example.org" })
4582     dev[0].request("INTERWORKING_SELECT auto freq=2412")
4583     ev = dev[0].wait_connected(timeout=15)
4584     if bssid2 not in ev:
4585         raise Exception("Connected to incorrect network")
4586
4587 def test_ap_hs20_anqp_invalid_gas_response(dev, apdev):
4588     """Hotspot 2.0 network selection and invalid GAS response"""
4589     bssid = apdev[0]['bssid']
4590     params = hs20_ap_params()
4591     params['hessid'] = bssid
4592     hapd = hostapd.add_ap(apdev[0], params)
4593
4594     dev[0].scan_for_bss(bssid, freq="2412")
4595     hapd.set("ext_mgmt_frame_handling", "1")
4596
4597     dev[0].hs20_enable()
4598
4599     id = dev[0].add_cred_values({ 'realm': "example.com",
4600                                   'username': "test",
4601                                   'password': "secret",
4602                                   'domain': "example.com",
4603                                   'roaming_consortium': "112234",
4604                                   'eap': 'TTLS' })
4605     dev[0].request("INTERWORKING_SELECT freq=2412")
4606
4607     query = gas_rx(hapd)
4608     gas = parse_gas(query['payload'])
4609
4610     logger.info("ANQP: Unexpected Advertisement Protocol in response")
4611     resp = action_response(query)
4612     adv_proto = struct.pack('8B', 108, 6, 127, 0xdd, 0x00, 0x11, 0x22, 0x33)
4613     data = struct.pack('<H', 0)
4614     resp['payload'] = struct.pack('<BBBHH', ACTION_CATEG_PUBLIC,
4615                                   GAS_INITIAL_RESPONSE,
4616                                   gas['dialog_token'], 0, 0) + adv_proto + data
4617     send_gas_resp(hapd, resp)
4618
4619     ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=5)
4620     if ev is None:
4621         raise Exception("No ANQP-QUERY-DONE seen")
4622     if "result=INVALID_FRAME" not in ev:
4623         raise Exception("Unexpected result: " + ev)
4624
4625     dev[0].request("INTERWORKING_SELECT freq=2412")
4626
4627     query = gas_rx(hapd)
4628     gas = parse_gas(query['payload'])
4629
4630     logger.info("ANQP: Invalid element length for Info ID 1234")
4631     resp = action_response(query)
4632     adv_proto = struct.pack('BBBB', 108, 2, 127, 0)
4633     elements = struct.pack('<HH', 1234, 1)
4634     data = struct.pack('<H', len(elements)) + elements
4635     resp['payload'] = struct.pack('<BBBHH', ACTION_CATEG_PUBLIC,
4636                                   GAS_INITIAL_RESPONSE,
4637                                   gas['dialog_token'], 0, 0) + adv_proto + data
4638     send_gas_resp(hapd, resp)
4639
4640     ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=5)
4641     if ev is None:
4642         raise Exception("No ANQP-QUERY-DONE seen")
4643     if "result=INVALID_FRAME" not in ev:
4644         raise Exception("Unexpected result: " + ev)
4645
4646     with alloc_fail(dev[0], 1, "=anqp_add_extra"):
4647         dev[0].request("INTERWORKING_SELECT freq=2412")
4648
4649         query = gas_rx(hapd)
4650         gas = parse_gas(query['payload'])
4651
4652         resp = action_response(query)
4653         elements = struct.pack('<HHHH', 1, 0, 1, 0)
4654         data = struct.pack('<H', len(elements)) + elements
4655         resp['payload'] = struct.pack('<BBBHH', ACTION_CATEG_PUBLIC,
4656                                       GAS_INITIAL_RESPONSE,
4657                                       gas['dialog_token'], 0, 0) + adv_proto + data
4658         send_gas_resp(hapd, resp)
4659
4660         ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=5)
4661         if ev is None:
4662             raise Exception("No ANQP-QUERY-DONE seen")
4663         if "result=SUCCESS" not in ev:
4664             raise Exception("Unexpected result: " + ev)
4665
4666     with alloc_fail(dev[0], 1, "wpabuf_alloc_copy;anqp_add_extra"):
4667         dev[0].request("INTERWORKING_SELECT freq=2412")
4668
4669         query = gas_rx(hapd)
4670         gas = parse_gas(query['payload'])
4671
4672         resp = action_response(query)
4673         elements = struct.pack('<HHHH', 1, 0, 1, 0)
4674         data = struct.pack('<H', len(elements)) + elements
4675         resp['payload'] = struct.pack('<BBBHH', ACTION_CATEG_PUBLIC,
4676                                       GAS_INITIAL_RESPONSE,
4677                                       gas['dialog_token'], 0, 0) + adv_proto + data
4678         send_gas_resp(hapd, resp)
4679
4680         ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=5)
4681         if ev is None:
4682             raise Exception("No ANQP-QUERY-DONE seen")
4683         if "result=SUCCESS" not in ev:
4684             raise Exception("Unexpected result: " + ev)
4685
4686     tests = [ struct.pack('<HH', 0xdddd, 0),
4687               struct.pack('<HH3B', 0xdddd, 3, 0x50, 0x6f, 0x9a),
4688               struct.pack('<HH4B', 0xdddd, 4, 0x50, 0x6f, 0x9a, 0),
4689               struct.pack('<HH4B', 0xdddd, 4, 0x11, 0x22, 0x33, 0),
4690               struct.pack('<HHHH', 1, 0, 1, 0) ]
4691     for elements in tests:
4692         dev[0].request("INTERWORKING_SELECT freq=2412")
4693
4694         query = gas_rx(hapd)
4695         gas = parse_gas(query['payload'])
4696
4697         resp = action_response(query)
4698         data = struct.pack('<H', len(elements)) + elements
4699         resp['payload'] = struct.pack('<BBBHH', ACTION_CATEG_PUBLIC,
4700                                       GAS_INITIAL_RESPONSE,
4701                                       gas['dialog_token'], 0, 0) + adv_proto + data
4702         send_gas_resp(hapd, resp)
4703
4704         ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=5)
4705         if ev is None:
4706             raise Exception("No ANQP-QUERY-DONE seen")
4707         if "result=SUCCESS" not in ev:
4708             raise Exception("Unexpected result: " + ev)
4709
4710 def test_ap_hs20_set_profile_failures(dev, apdev):
4711     """Hotspot 2.0 and failures during profile configuration"""
4712     bssid = apdev[0]['bssid']
4713     params = hs20_ap_params()
4714     params['hessid'] = bssid
4715     params['anqp_3gpp_cell_net'] = "555,444"
4716     hapd = hostapd.add_ap(apdev[0], params)
4717
4718     dev[0].hs20_enable()
4719     dev[0].scan_for_bss(bssid, freq="2412")
4720
4721     id = dev[0].add_cred_values({ 'realm': "example.com",
4722                                   'domain': "example.com",
4723                                   'username': "test",
4724                                   'password': "secret",
4725                                   'eap': 'TTLS' })
4726     interworking_select(dev[0], bssid, "home", freq=2412)
4727     dev[0].dump_monitor()
4728     dev[0].request("NOTE ssid->eap.eap_methods = os_malloc()")
4729     with alloc_fail(dev[0], 1, "interworking_set_eap_params"):
4730         dev[0].request("INTERWORKING_CONNECT " + bssid)
4731         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4732     dev[0].remove_cred(id)
4733
4734     id = dev[0].add_cred_values({ 'realm': "example.com",
4735                                   'domain': "example.com",
4736                                   'username': "hs20-test-with-domain@example.com",
4737                                   'password': "password" })
4738     interworking_select(dev[0], bssid, "home", freq=2412)
4739     dev[0].dump_monitor()
4740     dev[0].request("NOTE anon = os_malloc()")
4741     with alloc_fail(dev[0], 1, "interworking_set_eap_params"):
4742         dev[0].request("INTERWORKING_CONNECT " + bssid)
4743         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4744     dev[0].request("NOTE Successful connection with cred->username including realm")
4745     dev[0].request("INTERWORKING_CONNECT " + bssid)
4746     dev[0].wait_connected()
4747     dev[0].remove_cred(id)
4748     dev[0].wait_disconnected()
4749
4750     id = dev[0].add_cred_values({ 'realm': "example.com",
4751                                   'domain': "example.com",
4752                                   'username': "hs20-test",
4753                                   'password': "password" })
4754     interworking_select(dev[0], bssid, "home", freq=2412)
4755     dev[0].dump_monitor()
4756     dev[0].request("NOTE anon = os_malloc() (second)")
4757     with alloc_fail(dev[0], 1, "interworking_set_eap_params"):
4758         dev[0].request("INTERWORKING_CONNECT " + bssid)
4759         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4760     with alloc_fail(dev[0], 1, "wpa_config_add_network;interworking_connect"):
4761         dev[0].request("INTERWORKING_CONNECT " + bssid)
4762         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4763     with alloc_fail(dev[0], 1, "=interworking_connect"):
4764         dev[0].request("INTERWORKING_CONNECT " + bssid)
4765         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4766     dev[0].request("NOTE wpa_config_set(eap)")
4767     with alloc_fail(dev[0], 1, "wpa_config_parse_eap;wpa_config_set;interworking_connect"):
4768         dev[0].request("INTERWORKING_CONNECT " + bssid)
4769         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4770     dev[0].request("NOTE wpa_config_set(TTLS-NON_EAP_MSCHAPV2-phase2)")
4771     with alloc_fail(dev[0], 1, "wpa_config_parse_str;wpa_config_set;interworking_connect"):
4772         dev[0].request("INTERWORKING_CONNECT " + bssid)
4773         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4774     dev[0].remove_cred(id)
4775
4776     id = dev[0].add_cred_values({ 'roaming_consortium': "112233",
4777                                   'domain': "example.com",
4778                                   'username': "hs20-test",
4779                                   'password': "password",
4780                                   'eap': 'TTLS',
4781                                   'phase2': "auth=MSCHAPV2" })
4782     interworking_select(dev[0], bssid, "home", freq=2412)
4783     dev[0].dump_monitor()
4784     dev[0].request("NOTE anon = os_strdup()")
4785     with alloc_fail(dev[0], 2, "interworking_set_eap_params"):
4786         dev[0].request("INTERWORKING_CONNECT " + bssid)
4787         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4788     dev[0].request("NOTE wpa_config_set_quoted(anonymous_identity)")
4789     with alloc_fail(dev[0], 1, "=wpa_config_set_quoted;interworking_set_eap_params"):
4790         dev[0].request("INTERWORKING_CONNECT " + bssid)
4791         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4792     dev[0].request("NOTE Successful connection with cred->realm not included")
4793     dev[0].request("INTERWORKING_CONNECT " + bssid)
4794     dev[0].wait_connected()
4795     dev[0].remove_cred(id)
4796     dev[0].wait_disconnected()
4797
4798     id = dev[0].add_cred_values({ 'roaming_consortium': "112233",
4799                                   'domain': "example.com",
4800                                   'realm': "example.com",
4801                                   'username': "user",
4802                                   'password': "password",
4803                                   'eap': 'PEAP' })
4804     interworking_select(dev[0], bssid, "home", freq=2412)
4805     dev[0].dump_monitor()
4806     dev[0].request("NOTE id = os_strdup()")
4807     with alloc_fail(dev[0], 2, "interworking_set_eap_params"):
4808         dev[0].request("INTERWORKING_CONNECT " + bssid)
4809         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4810     dev[0].request("NOTE wpa_config_set_quoted(identity)")
4811     with alloc_fail(dev[0], 1, "=wpa_config_set_quoted;interworking_set_eap_params"):
4812         dev[0].request("INTERWORKING_CONNECT " + bssid)
4813         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4814     dev[0].remove_cred(id)
4815
4816     id = dev[0].add_cred_values({ 'roaming_consortium': "112233",
4817                                   'domain': "example.com",
4818                                   'realm': "example.com",
4819                                   'username': "user",
4820                                   'password': "password",
4821                                   'eap': "TTLS" })
4822     interworking_select(dev[0], bssid, "home", freq=2412)
4823     dev[0].dump_monitor()
4824     dev[0].request("NOTE wpa_config_set_quoted(identity) (second)")
4825     with alloc_fail(dev[0], 2, "=wpa_config_set_quoted;interworking_set_eap_params"):
4826         dev[0].request("INTERWORKING_CONNECT " + bssid)
4827         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4828     dev[0].request("NOTE wpa_config_set_quoted(password)")
4829     with alloc_fail(dev[0], 3, "=wpa_config_set_quoted;interworking_set_eap_params"):
4830         dev[0].request("INTERWORKING_CONNECT " + bssid)
4831         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4832     with alloc_fail(dev[0], 1, "wpa_config_add_network;interworking_connect_roaming_consortium"):
4833         dev[0].request("INTERWORKING_CONNECT " + bssid)
4834         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4835     with alloc_fail(dev[0], 1, "=interworking_connect_roaming_consortium"):
4836         dev[0].request("INTERWORKING_CONNECT " + bssid)
4837         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4838     dev[0].remove_cred(id)
4839
4840     id = dev[0].add_cred_values({ 'roaming_consortium': "112233",
4841                                   'domain': "example.com",
4842                                   'realm': "example.com",
4843                                   'username': "user",
4844                                   'eap': "PEAP" })
4845     dev[0].set_cred(id, "password", "ext:password");
4846     interworking_select(dev[0], bssid, "home", freq=2412)
4847     dev[0].dump_monitor()
4848     dev[0].request("NOTE wpa_config_set(password)")
4849     with alloc_fail(dev[0], 3, "wpa_config_set;interworking_set_eap_params"):
4850         dev[0].request("INTERWORKING_CONNECT " + bssid)
4851         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4852     with alloc_fail(dev[0], 1, "interworking_set_hs20_params"):
4853         dev[0].request("INTERWORKING_CONNECT " + bssid)
4854         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4855     dev[0].remove_cred(id)
4856
4857     id = dev[0].add_cred_values({ 'realm': "example.com",
4858                                   'domain': "example.com",
4859                                   'username': "certificate-user",
4860                                   'phase1': "include_tls_length=0",
4861                                   'domain_suffix_match': "example.com",
4862                                   'ca_cert': "auth_serv/ca.pem",
4863                                   'client_cert': "auth_serv/user.pem",
4864                                   'private_key': "auth_serv/user.key",
4865                                   'private_key_passwd': "secret" })
4866     interworking_select(dev[0], bssid, "home", freq=2412)
4867     dev[0].dump_monitor()
4868     dev[0].request("NOTE wpa_config_set_quoted(client_cert)")
4869     with alloc_fail(dev[0], 2, "=wpa_config_set_quoted;interworking_set_eap_params"):
4870         dev[0].request("INTERWORKING_CONNECT " + bssid)
4871         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4872     dev[0].request("NOTE wpa_config_set_quoted(private_key)")
4873     with alloc_fail(dev[0], 3, "=wpa_config_set_quoted;interworking_set_eap_params"):
4874         dev[0].request("INTERWORKING_CONNECT " + bssid)
4875         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4876     dev[0].request("NOTE wpa_config_set_quoted(private_key_passwd)")
4877     with alloc_fail(dev[0], 4, "=wpa_config_set_quoted;interworking_set_eap_params"):
4878         dev[0].request("INTERWORKING_CONNECT " + bssid)
4879         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4880     dev[0].request("NOTE wpa_config_set_quoted(ca_cert)")
4881     with alloc_fail(dev[0], 5, "=wpa_config_set_quoted;interworking_set_eap_params"):
4882         dev[0].request("INTERWORKING_CONNECT " + bssid)
4883         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4884     dev[0].request("NOTE wpa_config_set_quoted(domain_suffix_match)")
4885     with alloc_fail(dev[0], 6, "=wpa_config_set_quoted;interworking_set_eap_params"):
4886         dev[0].request("INTERWORKING_CONNECT " + bssid)
4887         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4888     with alloc_fail(dev[0], 1, "interworking_set_hs20_params"):
4889         dev[0].request("INTERWORKING_CONNECT " + bssid)
4890         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4891     dev[0].remove_cred(id)
4892
4893     id = dev[0].add_cred_values({ 'imsi': "555444-333222111", 'eap': "SIM",
4894                                   'milenage': "5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123"})
4895     interworking_select(dev[0], bssid, freq=2412)
4896     dev[0].dump_monitor()
4897     with alloc_fail(dev[0], 1, "interworking_set_hs20_params"):
4898         dev[0].request("INTERWORKING_CONNECT " + bssid)
4899         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4900     dev[0].request("NOTE wpa_config_set_quoted(password;milenage)")
4901     with alloc_fail(dev[0], 2, "=wpa_config_set_quoted;interworking_connect_3gpp"):
4902         dev[0].request("INTERWORKING_CONNECT " + bssid)
4903         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4904     dev[0].request("NOTE wpa_config_set(eap)")
4905     with alloc_fail(dev[0], 1, "wpa_config_parse_eap;wpa_config_set;interworking_connect_3gpp"):
4906         dev[0].request("INTERWORKING_CONNECT " + bssid)
4907         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4908     dev[0].request("NOTE set_root_nai:wpa_config_set(identity)")
4909     with alloc_fail(dev[0], 1, "wpa_config_parse_str;interworking_connect_3gpp"):
4910             dev[0].request("INTERWORKING_CONNECT " + bssid)
4911             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4912     dev[0].remove_cred(id)
4913
4914     id = dev[0].add_cred_values({ 'roaming_consortium': "112233",
4915                                   'username': "user@example.com",
4916                                   'password': "password" })
4917     interworking_select(dev[0], bssid, freq=2412)
4918     dev[0].dump_monitor()
4919     dev[0].request("NOTE Interworking: No EAP method set for credential using roaming consortium")
4920     dev[0].request("INTERWORKING_CONNECT " + bssid)
4921     dev[0].remove_cred(id)
4922
4923     hapd.disable()
4924     params = hs20_ap_params()
4925     params['nai_realm'] = "0,example.com,25[3:26]"
4926     hapd = hostapd.add_ap(apdev[0], params)
4927     id = dev[0].add_cred_values({ 'realm': "example.com",
4928                                   'domain': "example.com",
4929                                   'username': "hs20-test",
4930                                   'password': "password" })
4931     interworking_select(dev[0], bssid, freq=2412)
4932     dev[0].dump_monitor()
4933     dev[0].request("NOTE wpa_config_set(PEAP/FAST-phase1)")
4934     with alloc_fail(dev[0], 1, "wpa_config_parse_str;wpa_config_set;interworking_connect"):
4935         dev[0].request("INTERWORKING_CONNECT " + bssid)
4936         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4937     dev[0].request("NOTE wpa_config_set(PEAP/FAST-pac_interworking)")
4938     with alloc_fail(dev[0], 2, "wpa_config_parse_str;wpa_config_set;interworking_connect"):
4939         dev[0].request("INTERWORKING_CONNECT " + bssid)
4940         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4941     dev[0].request("NOTE wpa_config_set(PEAP/FAST-phase2)")
4942     with alloc_fail(dev[0], 3, "wpa_config_parse_str;wpa_config_set;interworking_connect"):
4943         dev[0].request("INTERWORKING_CONNECT " + bssid)
4944         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4945
4946     hapd.disable()
4947     params = hs20_ap_params()
4948     params['nai_realm'] = "0,example.com,21"
4949     hapd = hostapd.add_ap(apdev[0], params)
4950     interworking_select(dev[0], bssid, freq=2412)
4951     dev[0].request("NOTE wpa_config_set(TTLS-defaults-phase2)")
4952     with alloc_fail(dev[0], 1, "wpa_config_parse_str;wpa_config_set;interworking_connect"):
4953         dev[0].request("INTERWORKING_CONNECT " + bssid)
4954         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4955
4956     hapd.disable()
4957     params = hs20_ap_params()
4958     params['nai_realm'] = "0,example.com,21[2:3]"
4959     hapd = hostapd.add_ap(apdev[0], params)
4960     interworking_select(dev[0], bssid, freq=2412)
4961     dev[0].request("NOTE wpa_config_set(TTLS-NON_EAP_MSCHAP-phase2)")
4962     with alloc_fail(dev[0], 1, "wpa_config_parse_str;wpa_config_set;interworking_connect"):
4963         dev[0].request("INTERWORKING_CONNECT " + bssid)
4964         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4965
4966     hapd.disable()
4967     params = hs20_ap_params()
4968     params['nai_realm'] = "0,example.com,21[2:2]"
4969     hapd = hostapd.add_ap(apdev[0], params)
4970     interworking_select(dev[0], bssid, freq=2412)
4971     dev[0].request("NOTE wpa_config_set(TTLS-NON_EAP_CHAP-phase2)")
4972     with alloc_fail(dev[0], 1, "wpa_config_parse_str;wpa_config_set;interworking_connect"):
4973         dev[0].request("INTERWORKING_CONNECT " + bssid)
4974         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4975
4976     hapd.disable()
4977     params = hs20_ap_params()
4978     params['nai_realm'] = "0,example.com,21[2:1]"
4979     hapd = hostapd.add_ap(apdev[0], params)
4980     interworking_select(dev[0], bssid, freq=2412)
4981     dev[0].request("NOTE wpa_config_set(TTLS-NON_EAP_PAP-phase2)")
4982     with alloc_fail(dev[0], 1, "wpa_config_parse_str;wpa_config_set;interworking_connect"):
4983         dev[0].request("INTERWORKING_CONNECT " + bssid)
4984         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4985
4986     hapd.disable()
4987     params = hs20_ap_params()
4988     params['nai_realm'] = "0,example.com,21[3:26]"
4989     hapd = hostapd.add_ap(apdev[0], params)
4990     interworking_select(dev[0], bssid, freq=2412)
4991     dev[0].request("NOTE wpa_config_set(TTLS-EAP-MSCHAPV2-phase2)")
4992     with alloc_fail(dev[0], 1, "wpa_config_parse_str;wpa_config_set;interworking_connect"):
4993         dev[0].request("INTERWORKING_CONNECT " + bssid)
4994         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4995
4996     dev[0].remove_cred(id)