93e9ae926dd88dce871a2849d6a3ac0a8d53e706
[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_deauth_req_without_pmf(dev, apdev):
2438     """Hotspot 2.0 connection and deauthentication request without PMF"""
2439     check_eap_capa(dev[0], "MSCHAPV2")
2440     dev[0].request("SET pmf 0")
2441     eap_test(dev[0], apdev[0], "21[3:26]", "TTLS", "user")
2442     dev[0].dump_monitor()
2443     addr = dev[0].own_addr()
2444     hapd = hostapd.Hostapd(apdev[0]['ifname'])
2445     hapd.request("HS20_DEAUTH_REQ " + addr + " 1 120 http://example.com/")
2446     ev = dev[0].wait_event(["HS20-DEAUTH-IMMINENT-NOTICE"], timeout=0.2)
2447     if ev is not None:
2448         raise Exception("Deauth imminent notice without PMF accepted")
2449
2450 def test_ap_hs20_remediation_required(dev, apdev):
2451     """Hotspot 2.0 connection and remediation required from RADIUS"""
2452     check_eap_capa(dev[0], "MSCHAPV2")
2453     try:
2454         _test_ap_hs20_remediation_required(dev, apdev)
2455     finally:
2456         dev[0].request("SET pmf 0")
2457
2458 def _test_ap_hs20_remediation_required(dev, apdev):
2459     bssid = apdev[0]['bssid']
2460     params = hs20_ap_params()
2461     params['nai_realm'] = [ "0,example.com,21[2:4]" ]
2462     hostapd.add_ap(apdev[0], params)
2463
2464     dev[0].request("SET pmf 1")
2465     dev[0].hs20_enable()
2466     dev[0].add_cred_values({ 'realm': "example.com",
2467                              'username': "hs20-subrem-test",
2468                              'password': "password" })
2469     interworking_select(dev[0], bssid, freq="2412")
2470     interworking_connect(dev[0], bssid, "TTLS")
2471     ev = dev[0].wait_event(["HS20-SUBSCRIPTION-REMEDIATION"], timeout=5)
2472     if ev is None:
2473         raise Exception("Timeout on subscription remediation notice")
2474     if " 1 https://example.com/" not in ev:
2475         raise Exception("Unexpected subscription remediation event contents")
2476
2477 def test_ap_hs20_remediation_required_ctrl(dev, apdev):
2478     """Hotspot 2.0 connection and subrem from ctrl_iface"""
2479     check_eap_capa(dev[0], "MSCHAPV2")
2480     try:
2481         _test_ap_hs20_remediation_required_ctrl(dev, apdev)
2482     finally:
2483         dev[0].request("SET pmf 0")
2484
2485 def _test_ap_hs20_remediation_required_ctrl(dev, apdev):
2486     bssid = apdev[0]['bssid']
2487     addr = dev[0].own_addr()
2488     params = hs20_ap_params()
2489     params['nai_realm'] = [ "0,example.com,21[2:4]" ]
2490     hapd = hostapd.add_ap(apdev[0], params)
2491
2492     dev[0].request("SET pmf 1")
2493     dev[0].hs20_enable()
2494     dev[0].add_cred_values(default_cred())
2495     interworking_select(dev[0], bssid, freq="2412")
2496     interworking_connect(dev[0], bssid, "TTLS")
2497
2498     hapd.request("HS20_WNM_NOTIF " + addr + " https://example.com/")
2499     ev = dev[0].wait_event(["HS20-SUBSCRIPTION-REMEDIATION"], timeout=5)
2500     if ev is None:
2501         raise Exception("Timeout on subscription remediation notice")
2502     if " 1 https://example.com/" not in ev:
2503         raise Exception("Unexpected subscription remediation event contents")
2504
2505     hapd.request("HS20_WNM_NOTIF " + addr)
2506     ev = dev[0].wait_event(["HS20-SUBSCRIPTION-REMEDIATION"], timeout=5)
2507     if ev is None:
2508         raise Exception("Timeout on subscription remediation notice")
2509     if not ev.endswith("HS20-SUBSCRIPTION-REMEDIATION "):
2510         raise Exception("Unexpected subscription remediation event contents: " + ev)
2511
2512     if "FAIL" not in hapd.request("HS20_WNM_NOTIF "):
2513         raise Exception("Unexpected HS20_WNM_NOTIF success")
2514     if "FAIL" not in hapd.request("HS20_WNM_NOTIF foo"):
2515         raise Exception("Unexpected HS20_WNM_NOTIF success")
2516     if "FAIL" not in hapd.request("HS20_WNM_NOTIF " + addr + " https://12345678923456789842345678456783456712345678923456789842345678456783456712345678923456789842345678456783456712345678923456789842345678456783456712345678923456789842345678456783456712345678923456789842345678456783456712345678923456789842345678456783456712345678927.very.long.example.com/"):
2517         raise Exception("Unexpected HS20_WNM_NOTIF success")
2518
2519 def test_ap_hs20_session_info(dev, apdev):
2520     """Hotspot 2.0 connection and session information from RADIUS"""
2521     check_eap_capa(dev[0], "MSCHAPV2")
2522     try:
2523         _test_ap_hs20_session_info(dev, apdev)
2524     finally:
2525         dev[0].request("SET pmf 0")
2526
2527 def _test_ap_hs20_session_info(dev, apdev):
2528     bssid = apdev[0]['bssid']
2529     params = hs20_ap_params()
2530     params['nai_realm'] = [ "0,example.com,21[2:4]" ]
2531     hostapd.add_ap(apdev[0], params)
2532
2533     dev[0].request("SET pmf 1")
2534     dev[0].hs20_enable()
2535     dev[0].add_cred_values({ 'realm': "example.com",
2536                              'username': "hs20-session-info-test",
2537                              'password': "password" })
2538     interworking_select(dev[0], bssid, freq="2412")
2539     interworking_connect(dev[0], bssid, "TTLS")
2540     ev = dev[0].wait_event(["ESS-DISASSOC-IMMINENT"], timeout=10)
2541     if ev is None:
2542         raise Exception("Timeout on ESS disassociation imminent notice")
2543     if " 1 59904 https://example.com/" not in ev:
2544         raise Exception("Unexpected ESS disassociation imminent event contents")
2545     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"])
2546     if ev is None:
2547         raise Exception("Scan not started")
2548     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=30)
2549     if ev is None:
2550         raise Exception("Scan not completed")
2551
2552 def test_ap_hs20_osen(dev, apdev):
2553     """Hotspot 2.0 OSEN connection"""
2554     params = { 'ssid': "osen",
2555                'osen': "1",
2556                'auth_server_addr': "127.0.0.1",
2557                'auth_server_port': "1812",
2558                'auth_server_shared_secret': "radius" }
2559     hostapd.add_ap(apdev[0], params)
2560
2561     dev[1].connect("osen", key_mgmt="NONE", scan_freq="2412",
2562                    wait_connect=False)
2563     dev[2].connect("osen", key_mgmt="NONE", wep_key0='"hello"',
2564                    scan_freq="2412", wait_connect=False)
2565     dev[0].flush_scan_cache()
2566     dev[0].connect("osen", proto="OSEN", key_mgmt="OSEN", pairwise="CCMP",
2567                    group="GTK_NOT_USED",
2568                    eap="WFA-UNAUTH-TLS", identity="osen@example.com",
2569                    ca_cert="auth_serv/ca.pem",
2570                    scan_freq="2412")
2571     res = dev[0].get_bss(apdev[0]['bssid'])['flags']
2572     if "[OSEN-OSEN-CCMP]" not in res:
2573         raise Exception("OSEN not reported in BSS")
2574     if "[WEP]" in res:
2575         raise Exception("WEP reported in BSS")
2576     res = dev[0].request("SCAN_RESULTS")
2577     if "[OSEN-OSEN-CCMP]" not in res:
2578         raise Exception("OSEN not reported in SCAN_RESULTS")
2579
2580     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
2581     wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
2582     wpas.connect("osen", proto="OSEN", key_mgmt="OSEN", pairwise="CCMP",
2583                  group="GTK_NOT_USED",
2584                  eap="WFA-UNAUTH-TLS", identity="osen@example.com",
2585                  ca_cert="auth_serv/ca.pem",
2586                  scan_freq="2412")
2587     wpas.request("DISCONNECT")
2588
2589 def test_ap_hs20_network_preference(dev, apdev):
2590     """Hotspot 2.0 network selection with preferred home network"""
2591     check_eap_capa(dev[0], "MSCHAPV2")
2592     bssid = apdev[0]['bssid']
2593     params = hs20_ap_params()
2594     hostapd.add_ap(apdev[0], params)
2595
2596     dev[0].hs20_enable()
2597     values = { 'realm': "example.com",
2598                'username': "hs20-test",
2599                'password': "password",
2600                'domain': "example.com" }
2601     dev[0].add_cred_values(values)
2602
2603     id = dev[0].add_network()
2604     dev[0].set_network_quoted(id, "ssid", "home")
2605     dev[0].set_network_quoted(id, "psk", "12345678")
2606     dev[0].set_network(id, "priority", "1")
2607     dev[0].request("ENABLE_NETWORK %s no-connect" % id)
2608
2609     dev[0].scan_for_bss(bssid, freq="2412")
2610     dev[0].request("INTERWORKING_SELECT auto freq=2412")
2611     ev = dev[0].wait_connected(timeout=15)
2612     if bssid not in ev:
2613         raise Exception("Unexpected network selected")
2614
2615     bssid2 = apdev[1]['bssid']
2616     params = hostapd.wpa2_params(ssid="home", passphrase="12345678")
2617     hostapd.add_ap(apdev[1], params)
2618
2619     dev[0].scan_for_bss(bssid2, freq="2412")
2620     dev[0].request("INTERWORKING_SELECT auto freq=2412")
2621     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
2622                             "INTERWORKING-ALREADY-CONNECTED" ], timeout=15)
2623     if ev is None:
2624         raise Exception("Connection timed out")
2625     if "INTERWORKING-ALREADY-CONNECTED" in ev:
2626         raise Exception("No roam to higher priority network")
2627     if bssid2 not in ev:
2628         raise Exception("Unexpected network selected")
2629
2630 def test_ap_hs20_network_preference2(dev, apdev):
2631     """Hotspot 2.0 network selection with preferred credential"""
2632     check_eap_capa(dev[0], "MSCHAPV2")
2633     bssid2 = apdev[1]['bssid']
2634     params = hostapd.wpa2_params(ssid="home", passphrase="12345678")
2635     hostapd.add_ap(apdev[1], params)
2636
2637     dev[0].hs20_enable()
2638     values = { 'realm': "example.com",
2639                'username': "hs20-test",
2640                'password': "password",
2641                'domain': "example.com",
2642                'priority': "1" }
2643     dev[0].add_cred_values(values)
2644
2645     id = dev[0].add_network()
2646     dev[0].set_network_quoted(id, "ssid", "home")
2647     dev[0].set_network_quoted(id, "psk", "12345678")
2648     dev[0].request("ENABLE_NETWORK %s no-connect" % id)
2649
2650     dev[0].scan_for_bss(bssid2, freq="2412")
2651     dev[0].request("INTERWORKING_SELECT auto freq=2412")
2652     ev = dev[0].wait_connected(timeout=15)
2653     if bssid2 not in ev:
2654         raise Exception("Unexpected network selected")
2655
2656     bssid = apdev[0]['bssid']
2657     params = hs20_ap_params()
2658     hostapd.add_ap(apdev[0], params)
2659
2660     dev[0].scan_for_bss(bssid, freq="2412")
2661     dev[0].request("INTERWORKING_SELECT auto freq=2412")
2662     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
2663                             "INTERWORKING-ALREADY-CONNECTED" ], timeout=15)
2664     if ev is None:
2665         raise Exception("Connection timed out")
2666     if "INTERWORKING-ALREADY-CONNECTED" in ev:
2667         raise Exception("No roam to higher priority network")
2668     if bssid not in ev:
2669         raise Exception("Unexpected network selected")
2670
2671 def test_ap_hs20_network_preference3(dev, apdev):
2672     """Hotspot 2.0 network selection with two credential (one preferred)"""
2673     check_eap_capa(dev[0], "MSCHAPV2")
2674     bssid = apdev[0]['bssid']
2675     params = hs20_ap_params()
2676     hostapd.add_ap(apdev[0], params)
2677
2678     bssid2 = apdev[1]['bssid']
2679     params = hs20_ap_params(ssid="test-hs20b")
2680     params['nai_realm'] = "0,example.org,13[5:6],21[2:4][5:7]"
2681     hostapd.add_ap(apdev[1], params)
2682
2683     dev[0].hs20_enable()
2684     values = { 'realm': "example.com",
2685                'username': "hs20-test",
2686                'password': "password",
2687                'priority': "1" }
2688     dev[0].add_cred_values(values)
2689     values = { 'realm': "example.org",
2690                'username': "hs20-test",
2691                'password': "password" }
2692     id = dev[0].add_cred_values(values)
2693
2694     dev[0].scan_for_bss(bssid, freq="2412")
2695     dev[0].scan_for_bss(bssid2, freq="2412")
2696     dev[0].request("INTERWORKING_SELECT auto freq=2412")
2697     ev = dev[0].wait_connected(timeout=15)
2698     if bssid not in ev:
2699         raise Exception("Unexpected network selected")
2700
2701     dev[0].set_cred(id, "priority", "2")
2702     dev[0].request("INTERWORKING_SELECT auto freq=2412")
2703     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
2704                             "INTERWORKING-ALREADY-CONNECTED" ], timeout=15)
2705     if ev is None:
2706         raise Exception("Connection timed out")
2707     if "INTERWORKING-ALREADY-CONNECTED" in ev:
2708         raise Exception("No roam to higher priority network")
2709     if bssid2 not in ev:
2710         raise Exception("Unexpected network selected")
2711
2712 def test_ap_hs20_network_preference4(dev, apdev):
2713     """Hotspot 2.0 network selection with username vs. SIM credential"""
2714     check_eap_capa(dev[0], "MSCHAPV2")
2715     bssid = apdev[0]['bssid']
2716     params = hs20_ap_params()
2717     hostapd.add_ap(apdev[0], params)
2718
2719     bssid2 = apdev[1]['bssid']
2720     params = hs20_ap_params(ssid="test-hs20b")
2721     params['hessid'] = bssid2
2722     params['anqp_3gpp_cell_net'] = "555,444"
2723     params['domain_name'] = "wlan.mnc444.mcc555.3gppnetwork.org"
2724     hostapd.add_ap(apdev[1], params)
2725
2726     dev[0].hs20_enable()
2727     values = { 'realm': "example.com",
2728                'username': "hs20-test",
2729                'password': "password",
2730                'priority': "1" }
2731     dev[0].add_cred_values(values)
2732     values = { 'imsi': "555444-333222111",
2733                'eap': "SIM",
2734                'milenage': "5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123" }
2735     id = dev[0].add_cred_values(values)
2736
2737     dev[0].scan_for_bss(bssid, freq="2412")
2738     dev[0].scan_for_bss(bssid2, freq="2412")
2739     dev[0].request("INTERWORKING_SELECT auto freq=2412")
2740     ev = dev[0].wait_connected(timeout=15)
2741     if bssid not in ev:
2742         raise Exception("Unexpected network selected")
2743
2744     dev[0].set_cred(id, "priority", "2")
2745     dev[0].request("INTERWORKING_SELECT auto freq=2412")
2746     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
2747                             "INTERWORKING-ALREADY-CONNECTED" ], timeout=15)
2748     if ev is None:
2749         raise Exception("Connection timed out")
2750     if "INTERWORKING-ALREADY-CONNECTED" in ev:
2751         raise Exception("No roam to higher priority network")
2752     if bssid2 not in ev:
2753         raise Exception("Unexpected network selected")
2754
2755 def test_ap_hs20_interworking_select_blocking_scan(dev, apdev):
2756     """Ongoing INTERWORKING_SELECT blocking SCAN"""
2757     check_eap_capa(dev[0], "MSCHAPV2")
2758     bssid = apdev[0]['bssid']
2759     params = hs20_ap_params()
2760     hostapd.add_ap(apdev[0], params)
2761
2762     dev[0].hs20_enable()
2763     values = { 'realm': "example.com",
2764                'username': "hs20-test",
2765                'password': "password",
2766                'domain': "example.com" }
2767     dev[0].add_cred_values(values)
2768
2769     dev[0].scan_for_bss(bssid, freq="2412")
2770     dev[0].request("INTERWORKING_SELECT auto freq=2412")
2771     if "FAIL-BUSY" not in dev[0].request("SCAN"):
2772         raise Exception("Unexpected SCAN command result")
2773     dev[0].wait_connected(timeout=15)
2774
2775 def test_ap_hs20_fetch_osu(dev, apdev):
2776     """Hotspot 2.0 OSU provider and icon fetch"""
2777     bssid = apdev[0]['bssid']
2778     params = hs20_ap_params()
2779     params['hs20_icon'] = "128:80:zxx:image/png:w1fi_logo:w1fi_logo.png"
2780     params['osu_ssid'] = '"HS 2.0 OSU open"'
2781     params['osu_method_list'] = "1"
2782     params['osu_friendly_name'] = [ "eng:Test OSU", "fin:Testi-OSU" ]
2783     params['osu_icon'] = "w1fi_logo"
2784     params['osu_service_desc'] = [ "eng:Example services", "fin:Esimerkkipalveluja" ]
2785     params['osu_server_uri'] = "https://example.com/osu/"
2786     hostapd.add_ap(apdev[0], params)
2787
2788     bssid2 = apdev[1]['bssid']
2789     params = hs20_ap_params(ssid="test-hs20b")
2790     params['hessid'] = bssid2
2791     params['hs20_icon'] = "128:80:zxx:image/png:w1fi_logo:w1fi_logo.png"
2792     params['osu_ssid'] = '"HS 2.0 OSU OSEN"'
2793     params['osu_method_list'] = "0"
2794     params['osu_nai'] = "osen@example.com"
2795     params['osu_friendly_name'] = [ "eng:Test2 OSU", "fin:Testi2-OSU" ]
2796     params['osu_icon'] = "w1fi_logo"
2797     params['osu_service_desc'] = [ "eng:Example services2", "fin:Esimerkkipalveluja2" ]
2798     params['osu_server_uri'] = "https://example.org/osu/"
2799     hostapd.add_ap(apdev[1], params)
2800
2801     with open("w1fi_logo.png", "r") as f:
2802         orig_logo = f.read()
2803     dev[0].hs20_enable()
2804     dir = "/tmp/osu-fetch"
2805     if os.path.isdir(dir):
2806        files = [ f for f in os.listdir(dir) if f.startswith("osu-") ]
2807        for f in files:
2808            os.remove(dir + "/" + f)
2809     else:
2810         try:
2811             os.makedirs(dir)
2812         except:
2813             pass
2814     try:
2815         dev[1].scan_for_bss(bssid, freq="2412")
2816         dev[2].scan_for_bss(bssid, freq="2412")
2817         dev[0].request("SET osu_dir " + dir)
2818         dev[0].request("FETCH_OSU")
2819         if "FAIL" not in dev[1].request("HS20_ICON_REQUEST foo w1fi_logo"):
2820             raise Exception("Invalid HS20_ICON_REQUEST accepted")
2821         if "OK" not in dev[1].request("HS20_ICON_REQUEST " + bssid + " w1fi_logo"):
2822             raise Exception("HS20_ICON_REQUEST failed")
2823         if "OK" not in dev[2].request("REQ_HS20_ICON " + bssid + " w1fi_logo"):
2824             raise Exception("REQ_HS20_ICON failed")
2825         icons = 0
2826         while True:
2827             ev = dev[0].wait_event(["OSU provider fetch completed",
2828                                     "RX-HS20-ANQP-ICON"], timeout=15)
2829             if ev is None:
2830                 raise Exception("Timeout on OSU fetch")
2831             if "OSU provider fetch completed" in ev:
2832                 break
2833             if "RX-HS20-ANQP-ICON" in ev:
2834                 with open(ev.split(' ')[1], "r") as f:
2835                     logo = f.read()
2836                     if logo == orig_logo:
2837                         icons += 1
2838
2839         with open(dir + "/osu-providers.txt", "r") as f:
2840             prov = f.read()
2841             logger.debug("osu-providers.txt: " + prov)
2842         if "OSU-PROVIDER " + bssid not in prov:
2843             raise Exception("Missing OSU_PROVIDER(1)")
2844         if "OSU-PROVIDER " + bssid2 not in prov:
2845             raise Exception("Missing OSU_PROVIDER(2)")
2846     finally:
2847         files = [ f for f in os.listdir(dir) if f.startswith("osu-") ]
2848         for f in files:
2849             os.remove(dir + "/" + f)
2850         os.rmdir(dir)
2851
2852     if icons != 2:
2853         raise Exception("Unexpected number of icons fetched")
2854
2855     ev = dev[1].wait_event(["GAS-QUERY-START"], timeout=5)
2856     if ev is None:
2857         raise Exception("Timeout on GAS-QUERY-DONE")
2858     ev = dev[1].wait_event(["GAS-QUERY-DONE"], timeout=5)
2859     if ev is None:
2860         raise Exception("Timeout on GAS-QUERY-DONE")
2861     if "freq=2412 status_code=0 result=SUCCESS" not in ev:
2862         raise Exception("Unexpected GAS-QUERY-DONE: " + ev)
2863     ev = dev[1].wait_event(["RX-HS20-ANQP"], timeout=15)
2864     if ev is None:
2865         raise Exception("Timeout on icon fetch")
2866     if "Icon Binary File" not in ev:
2867         raise Exception("Unexpected ANQP element")
2868
2869     ev = dev[2].wait_event(["RX-HS20-ICON"], timeout=5)
2870     if ev is None:
2871         raise Exception("Timeout on RX-HS20-ICON")
2872     event_icon_len = ev.split(' ')[3]
2873     if " w1fi_logo " not in ev:
2874         raise Exception("RX-HS20-ICON did not have the expected file name")
2875     if bssid not in ev:
2876         raise Exception("RX-HS20-ICON did not have the expected BSSID")
2877     if "FAIL" in dev[2].request("GET_HS20_ICON " + bssid + " w1fi_logo 0 10"):
2878         raise Exception("GET_HS20_ICON 0..10 failed")
2879     if "FAIL" in dev[2].request("GET_HS20_ICON " + bssid + " w1fi_logo 5 10"):
2880         raise Exception("GET_HS20_ICON 5..15 failed")
2881     if "FAIL" not in  dev[2].request("GET_HS20_ICON " + bssid + " w1fi_logo 100000 10"):
2882         raise Exception("Unexpected success of GET_HS20_ICON with too large offset")
2883     icon = ""
2884     pos = 0
2885     while True:
2886         if pos > 100000:
2887             raise Exception("Unexpectedly long icon")
2888         res = dev[2].request("GET_HS20_ICON " + bssid + " w1fi_logo %d 1000" % pos)
2889         if res.startswith("FAIL"):
2890             break
2891         icon += base64.b64decode(res)
2892         pos += 1000
2893     hex = binascii.hexlify(icon)
2894     if not hex.startswith("0009696d6167652f706e677d1d"):
2895         raise Exception("Unexpected beacon binary header: " + hex)
2896     with open('w1fi_logo.png', 'r') as f:
2897         data = f.read()
2898         if icon[13:] != data:
2899             raise Exception("Unexpected icon data")
2900     if len(icon) != int(event_icon_len):
2901         raise Exception("Unexpected RX-HS20-ICON event length: " + event_icon_len)
2902
2903     for i in range(3):
2904         if "OK" not in dev[i].request("REQ_HS20_ICON " + bssid + " w1fi_logo"):
2905             raise Exception("REQ_HS20_ICON failed [2]")
2906     for i in range(3):
2907         ev = dev[i].wait_event(["RX-HS20-ICON"], timeout=5)
2908         if ev is None:
2909             raise Exception("Timeout on RX-HS20-ICON [2]")
2910
2911     if "FAIL" not in dev[2].request("DEL_HS20_ICON foo w1fi_logo"):
2912         raise Exception("Invalid DEL_HS20_ICON accepted")
2913     if "OK" not in dev[2].request("DEL_HS20_ICON " + bssid + " w1fi_logo"):
2914         raise Exception("DEL_HS20_ICON failed")
2915     if "OK" not in dev[1].request("DEL_HS20_ICON " + bssid):
2916         raise Exception("DEL_HS20_ICON failed")
2917     if "OK" not in dev[0].request("DEL_HS20_ICON "):
2918         raise Exception("DEL_HS20_ICON failed")
2919     for i in range(3):
2920         if "FAIL" not in dev[i].request("DEL_HS20_ICON "):
2921             raise Exception("DEL_HS20_ICON accepted when no icons left")
2922
2923 def test_ap_hs20_fetch_osu_no_info(dev, apdev):
2924     """Hotspot 2.0 OSU provider and no AP with info"""
2925     bssid = apdev[0]['bssid']
2926     params = hs20_ap_params()
2927     hostapd.add_ap(apdev[0], params)
2928
2929     dev[0].hs20_enable()
2930     dir = "/tmp/osu-fetch"
2931     if os.path.isdir(dir):
2932        files = [ f for f in os.listdir(dir) if f.startswith("osu-") ]
2933        for f in files:
2934            os.remove(dir + "/" + f)
2935     else:
2936         try:
2937             os.makedirs(dir)
2938         except:
2939             pass
2940     dev[0].scan_for_bss(bssid, freq="2412")
2941     try:
2942         dev[0].request("SET osu_dir " + dir)
2943         dev[0].request("FETCH_OSU")
2944         ev = dev[0].wait_event(["OSU provider fetch completed"], timeout=30)
2945         if ev is None:
2946             raise Exception("Timeout on OSU fetch")
2947     finally:
2948         files = [ f for f in os.listdir(dir) if f.startswith("osu-") ]
2949         for f in files:
2950             os.remove(dir + "/" + f)
2951         os.rmdir(dir)
2952
2953 def get_icon(dev, bssid, iconname):
2954     icon = ""
2955     pos = 0
2956     while True:
2957         if pos > 100000:
2958             raise Exception("Unexpectedly long icon")
2959         res = dev.request("GET_HS20_ICON " + bssid + " " + iconname + " %d 3000" % pos)
2960         if res.startswith("FAIL"):
2961             break
2962         icon += base64.b64decode(res)
2963         pos += 3000
2964     if len(icon) < 13:
2965         raise Exception("Too short GET_HS20_ICON response")
2966     return icon[0:13], icon[13:]
2967
2968 def test_ap_hs20_req_hs20_icon(dev, apdev):
2969     """Hotspot 2.0 OSU provider and multi-icon fetch with REQ_HS20_ICON"""
2970     bssid = apdev[0]['bssid']
2971     params = hs20_ap_params()
2972     params['hs20_icon'] = [ "128:80:zxx:image/png:w1fi_logo:w1fi_logo.png",
2973                             "128:80:zxx:image/png:test_logo:auth_serv/sha512-server.pem" ]
2974     params['osu_ssid'] = '"HS 2.0 OSU open"'
2975     params['osu_method_list'] = "1"
2976     params['osu_friendly_name'] = [ "eng:Test OSU", "fin:Testi-OSU" ]
2977     params['osu_icon'] = [ "w1fi_logo", "w1fi_logo2" ]
2978     params['osu_service_desc'] = [ "eng:Example services", "fin:Esimerkkipalveluja" ]
2979     params['osu_server_uri'] = "https://example.com/osu/"
2980     hostapd.add_ap(apdev[0], params)
2981
2982     dev[0].scan_for_bss(bssid, freq="2412")
2983
2984     # First, fetch two icons from the AP to wpa_supplicant
2985
2986     if "OK" not in dev[0].request("REQ_HS20_ICON " + bssid + " w1fi_logo"):
2987         raise Exception("REQ_HS20_ICON failed")
2988     ev = dev[0].wait_event(["RX-HS20-ICON"], timeout=5)
2989     if ev is None:
2990         raise Exception("Timeout on RX-HS20-ICON (1)")
2991
2992     if "OK" not in dev[0].request("REQ_HS20_ICON " + bssid + " test_logo"):
2993         raise Exception("REQ_HS20_ICON failed")
2994     ev = dev[0].wait_event(["RX-HS20-ICON"], timeout=5)
2995     if ev is None:
2996         raise Exception("Timeout on RX-HS20-ICON (2)")
2997
2998     # Then, fetch the icons from wpa_supplicant for validation
2999
3000     hdr, data1 = get_icon(dev[0], bssid, "w1fi_logo")
3001     hdr, data2 = get_icon(dev[0], bssid, "test_logo")
3002
3003     with open('w1fi_logo.png', 'r') as f:
3004         data = f.read()
3005         if data1 != data:
3006             raise Exception("Unexpected icon data (1)")
3007
3008     with open('auth_serv/sha512-server.pem', 'r') as f:
3009         data = f.read()
3010         if data2 != data:
3011             raise Exception("Unexpected icon data (2)")
3012
3013     # Finally, delete the icons from wpa_supplicant
3014
3015     if "OK" not in dev[0].request("DEL_HS20_ICON " + bssid + " w1fi_logo"):
3016         raise Exception("DEL_HS20_ICON failed")
3017     if "OK" not in dev[0].request("DEL_HS20_ICON " + bssid + " test_logo"):
3018         raise Exception("DEL_HS20_ICON failed")
3019
3020 def test_ap_hs20_req_hs20_icon_oom(dev, apdev):
3021     """Hotspot 2.0 icon fetch OOM with REQ_HS20_ICON"""
3022     bssid = apdev[0]['bssid']
3023     params = hs20_ap_params()
3024     params['hs20_icon'] = [ "128:80:zxx:image/png:w1fi_logo:w1fi_logo.png",
3025                             "128:80:zxx:image/png:test_logo:auth_serv/sha512-server.pem" ]
3026     params['osu_ssid'] = '"HS 2.0 OSU open"'
3027     params['osu_method_list'] = "1"
3028     params['osu_friendly_name'] = [ "eng:Test OSU", "fin:Testi-OSU" ]
3029     params['osu_icon'] = [ "w1fi_logo", "w1fi_logo2" ]
3030     params['osu_service_desc'] = [ "eng:Example services", "fin:Esimerkkipalveluja" ]
3031     params['osu_server_uri'] = "https://example.com/osu/"
3032     hostapd.add_ap(apdev[0], params)
3033
3034     dev[0].scan_for_bss(bssid, freq="2412")
3035
3036     if "FAIL" not in dev[0].request("REQ_HS20_ICON 11:22:33:44:55:66 w1fi_logo"):
3037         raise Exception("REQ_HS20_ICON succeeded with unknown BSSID")
3038
3039     with alloc_fail(dev[0], 1, "hs20_build_anqp_req;hs20_anqp_send_req"):
3040         if "FAIL" not in dev[0].request("REQ_HS20_ICON " + bssid + " w1fi_logo"):
3041             raise Exception("REQ_HS20_ICON succeeded during OOM")
3042
3043     with alloc_fail(dev[0], 1, "gas_query_req;hs20_anqp_send_req"):
3044         if "FAIL" not in dev[0].request("REQ_HS20_ICON " + bssid + " w1fi_logo"):
3045             raise Exception("REQ_HS20_ICON succeeded during OOM")
3046
3047     with alloc_fail(dev[0], 1, "=hs20_anqp_send_req"):
3048         if "FAIL" not in dev[0].request("REQ_HS20_ICON " + bssid + " w1fi_logo"):
3049             raise Exception("REQ_HS20_ICON succeeded during OOM")
3050     with alloc_fail(dev[0], 2, "=hs20_anqp_send_req"):
3051         if "FAIL" not in dev[0].request("REQ_HS20_ICON " + bssid + " w1fi_logo"):
3052             raise Exception("REQ_HS20_ICON succeeded during OOM")
3053
3054     if "OK" not in dev[0].request("REQ_HS20_ICON " + bssid + " w1fi_logo"):
3055         raise Exception("REQ_HS20_ICON failed")
3056     ev = dev[0].wait_event(["RX-HS20-ICON"], timeout=5)
3057     if ev is None:
3058         raise Exception("Timeout on RX-HS20-ICON (1)")
3059
3060     with alloc_fail(dev[0], 1, "hs20_get_icon"):
3061         if "FAIL" not in dev[0].request("GET_HS20_ICON " + bssid + "w1fi_logo 0 100"):
3062             raise Exception("GET_HS20_ICON succeeded during OOM")
3063
3064     if "OK" not in dev[0].request("DEL_HS20_ICON " + bssid + " w1fi_logo"):
3065         raise Exception("DEL_HS20_ICON failed")
3066
3067     with alloc_fail(dev[0], 1, "=hs20_process_icon_binary_file"):
3068         if "OK" not in dev[0].request("REQ_HS20_ICON " + bssid + " w1fi_logo"):
3069             raise Exception("REQ_HS20_ICON failed")
3070         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
3071
3072 def test_ap_hs20_req_hs20_icon_parallel(dev, apdev):
3073     """Hotspot 2.0 OSU provider and multi-icon parallel fetch with REQ_HS20_ICON"""
3074     bssid = apdev[0]['bssid']
3075     params = hs20_ap_params()
3076     params['hs20_icon'] = [ "128:80:zxx:image/png:w1fi_logo:w1fi_logo.png",
3077                             "128:80:zxx:image/png:test_logo:auth_serv/sha512-server.pem" ]
3078     params['osu_ssid'] = '"HS 2.0 OSU open"'
3079     params['osu_method_list'] = "1"
3080     params['osu_friendly_name'] = [ "eng:Test OSU", "fin:Testi-OSU" ]
3081     params['osu_icon'] = [ "w1fi_logo", "w1fi_logo2" ]
3082     params['osu_service_desc'] = [ "eng:Example services", "fin:Esimerkkipalveluja" ]
3083     params['osu_server_uri'] = "https://example.com/osu/"
3084     hostapd.add_ap(apdev[0], params)
3085
3086     dev[0].scan_for_bss(bssid, freq="2412")
3087
3088     # First, fetch two icons from the AP to wpa_supplicant
3089
3090     if "OK" not in dev[0].request("REQ_HS20_ICON " + bssid + " w1fi_logo"):
3091         raise Exception("REQ_HS20_ICON failed")
3092
3093     if "OK" not in dev[0].request("REQ_HS20_ICON " + bssid + " test_logo"):
3094         raise Exception("REQ_HS20_ICON failed")
3095     ev = dev[0].wait_event(["RX-HS20-ICON"], timeout=5)
3096     if ev is None:
3097         raise Exception("Timeout on RX-HS20-ICON (1)")
3098     ev = dev[0].wait_event(["RX-HS20-ICON"], timeout=5)
3099     if ev is None:
3100         raise Exception("Timeout on RX-HS20-ICON (2)")
3101
3102     # Then, fetch the icons from wpa_supplicant for validation
3103
3104     hdr, data1 = get_icon(dev[0], bssid, "w1fi_logo")
3105     hdr, data2 = get_icon(dev[0], bssid, "test_logo")
3106
3107     with open('w1fi_logo.png', 'r') as f:
3108         data = f.read()
3109         if data1 != data:
3110             raise Exception("Unexpected icon data (1)")
3111
3112     with open('auth_serv/sha512-server.pem', 'r') as f:
3113         data = f.read()
3114         if data2 != data:
3115             raise Exception("Unexpected icon data (2)")
3116
3117     # Finally, delete the icons from wpa_supplicant
3118
3119     if "OK" not in dev[0].request("DEL_HS20_ICON " + bssid + " w1fi_logo"):
3120         raise Exception("DEL_HS20_ICON failed")
3121     if "OK" not in dev[0].request("DEL_HS20_ICON " + bssid + " test_logo"):
3122         raise Exception("DEL_HS20_ICON failed")
3123
3124 def test_ap_hs20_fetch_osu_stop(dev, apdev):
3125     """Hotspot 2.0 OSU provider fetch stopped"""
3126     bssid = apdev[0]['bssid']
3127     params = hs20_ap_params()
3128     params['hs20_icon'] = "128:80:zxx:image/png:w1fi_logo:w1fi_logo.png"
3129     params['osu_ssid'] = '"HS 2.0 OSU open"'
3130     params['osu_method_list'] = "1"
3131     params['osu_friendly_name'] = [ "eng:Test OSU", "fin:Testi-OSU" ]
3132     params['osu_icon'] = "w1fi_logo"
3133     params['osu_service_desc'] = [ "eng:Example services", "fin:Esimerkkipalveluja" ]
3134     params['osu_server_uri'] = "https://example.com/osu/"
3135     hapd = hostapd.add_ap(apdev[0], params)
3136
3137     dev[0].hs20_enable()
3138     dir = "/tmp/osu-fetch"
3139     if os.path.isdir(dir):
3140        files = [ f for f in os.listdir(dir) if f.startswith("osu-") ]
3141        for f in files:
3142            os.remove(dir + "/" + f)
3143     else:
3144         try:
3145             os.makedirs(dir)
3146         except:
3147             pass
3148     try:
3149         dev[0].request("SET osu_dir " + dir)
3150         dev[0].request("SCAN freq=2412-2462")
3151         ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], timeout=10)
3152         if ev is None:
3153             raise Exception("Scan did not start")
3154         if "FAIL" not in dev[0].request("FETCH_OSU"):
3155             raise Exception("FETCH_OSU accepted while scanning")
3156         ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 10)
3157         if ev is None:
3158             raise Exception("Scan timed out")
3159         hapd.set("ext_mgmt_frame_handling", "1")
3160         dev[0].request("FETCH_ANQP")
3161         if "FAIL" not in dev[0].request("FETCH_OSU"):
3162             raise Exception("FETCH_OSU accepted while in FETCH_ANQP")
3163         dev[0].request("STOP_FETCH_ANQP")
3164         dev[0].wait_event(["GAS-QUERY-DONE"], timeout=5)
3165         dev[0].dump_monitor()
3166         hapd.dump_monitor()
3167         dev[0].request("INTERWORKING_SELECT freq=2412")
3168         for i in range(5):
3169             msg = hapd.mgmt_rx()
3170             if msg['subtype'] == 13:
3171                 break
3172         if "FAIL" not in dev[0].request("FETCH_OSU"):
3173             raise Exception("FETCH_OSU accepted while in INTERWORKING_SELECT")
3174         ev = dev[0].wait_event(["INTERWORKING-AP", "INTERWORKING-NO-MATCH"],
3175                                timeout=15)
3176         if ev is None:
3177             raise Exception("Network selection timed out")
3178
3179         dev[0].dump_monitor()
3180         if "OK" not in dev[0].request("FETCH_OSU"):
3181             raise Exception("FETCH_OSU failed")
3182         dev[0].request("CANCEL_FETCH_OSU")
3183
3184         for i in range(15):
3185             time.sleep(0.5)
3186             if dev[0].get_driver_status_field("scan_state") == "SCAN_COMPLETED":
3187                 break
3188
3189         dev[0].dump_monitor()
3190         if "OK" not in dev[0].request("FETCH_OSU"):
3191             raise Exception("FETCH_OSU failed")
3192         if "FAIL" not in dev[0].request("FETCH_OSU"):
3193             raise Exception("FETCH_OSU accepted while in FETCH_OSU")
3194         ev = dev[0].wait_event(["GAS-QUERY-START"], 10)
3195         if ev is None:
3196             raise Exception("GAS timed out")
3197         if "FAIL" not in dev[0].request("FETCH_OSU"):
3198             raise Exception("FETCH_OSU accepted while in FETCH_OSU")
3199         dev[0].request("CANCEL_FETCH_OSU")
3200         ev = dev[0].wait_event(["GAS-QUERY-DONE"], 10)
3201         if ev is None:
3202             raise Exception("GAS event timed out after CANCEL_FETCH_OSU")
3203     finally:
3204         files = [ f for f in os.listdir(dir) if f.startswith("osu-") ]
3205         for f in files:
3206             os.remove(dir + "/" + f)
3207         os.rmdir(dir)
3208
3209 def test_ap_hs20_ft(dev, apdev):
3210     """Hotspot 2.0 connection with FT"""
3211     check_eap_capa(dev[0], "MSCHAPV2")
3212     bssid = apdev[0]['bssid']
3213     params = hs20_ap_params()
3214     params['wpa_key_mgmt'] = "FT-EAP"
3215     params['nas_identifier'] = "nas1.w1.fi"
3216     params['r1_key_holder'] = "000102030405"
3217     params["mobility_domain"] = "a1b2"
3218     params["reassociation_deadline"] = "1000"
3219     hostapd.add_ap(apdev[0], params)
3220
3221     dev[0].hs20_enable()
3222     id = dev[0].add_cred_values({ 'realm': "example.com",
3223                                   'username': "hs20-test",
3224                                   'password': "password",
3225                                   'ca_cert': "auth_serv/ca.pem",
3226                                   'domain': "example.com",
3227                                   'update_identifier': "1234" })
3228     interworking_select(dev[0], bssid, "home", freq="2412")
3229     interworking_connect(dev[0], bssid, "TTLS")
3230
3231 def test_ap_hs20_remediation_sql(dev, apdev, params):
3232     """Hotspot 2.0 connection and remediation required using SQLite for user DB"""
3233     check_eap_capa(dev[0], "MSCHAPV2")
3234     try:
3235         import sqlite3
3236     except ImportError:
3237         raise HwsimSkip("No sqlite3 module available")
3238     dbfile = os.path.join(params['logdir'], "eap-user.db")
3239     try:
3240         os.remove(dbfile)
3241     except:
3242         pass
3243     con = sqlite3.connect(dbfile)
3244     with con:
3245         cur = con.cursor()
3246         cur.execute("CREATE TABLE users(identity TEXT PRIMARY KEY, methods TEXT, password TEXT, remediation TEXT, phase2 INTEGER)")
3247         cur.execute("CREATE TABLE wildcards(identity TEXT PRIMARY KEY, methods TEXT)")
3248         cur.execute("INSERT INTO users(identity,methods,password,phase2,remediation) VALUES ('user-mschapv2','TTLS-MSCHAPV2','password',1,'user')")
3249         cur.execute("INSERT INTO wildcards(identity,methods) VALUES ('','TTLS,TLS')")
3250         cur.execute("CREATE TABLE authlog(timestamp TEXT, session TEXT, nas_ip TEXT, username TEXT, note TEXT)")
3251
3252     try:
3253         params = { "ssid": "as", "beacon_int": "2000",
3254                    "radius_server_clients": "auth_serv/radius_clients.conf",
3255                    "radius_server_auth_port": '18128',
3256                    "eap_server": "1",
3257                    "eap_user_file": "sqlite:" + dbfile,
3258                    "ca_cert": "auth_serv/ca.pem",
3259                    "server_cert": "auth_serv/server.pem",
3260                    "private_key": "auth_serv/server.key",
3261                    "subscr_remediation_url": "https://example.org/",
3262                    "subscr_remediation_method": "1" }
3263         hostapd.add_ap(apdev[1], params)
3264
3265         bssid = apdev[0]['bssid']
3266         params = hs20_ap_params()
3267         params['auth_server_port'] = "18128"
3268         hostapd.add_ap(apdev[0], params)
3269
3270         dev[0].request("SET pmf 1")
3271         dev[0].hs20_enable()
3272         id = dev[0].add_cred_values({ 'realm': "example.com",
3273                                       'username': "user-mschapv2",
3274                                       'password': "password",
3275                                       'ca_cert': "auth_serv/ca.pem" })
3276         interworking_select(dev[0], bssid, freq="2412")
3277         interworking_connect(dev[0], bssid, "TTLS")
3278         ev = dev[0].wait_event(["HS20-SUBSCRIPTION-REMEDIATION"], timeout=5)
3279         if ev is None:
3280             raise Exception("Timeout on subscription remediation notice")
3281         if " 1 https://example.org/" not in ev:
3282             raise Exception("Unexpected subscription remediation event contents")
3283
3284         with con:
3285             cur = con.cursor()
3286             cur.execute("SELECT * from authlog")
3287             rows = cur.fetchall()
3288             if len(rows) < 1:
3289                 raise Exception("No authlog entries")
3290
3291     finally:
3292         os.remove(dbfile)
3293         dev[0].request("SET pmf 0")
3294
3295 def test_ap_hs20_external_selection(dev, apdev):
3296     """Hotspot 2.0 connection using external network selection and creation"""
3297     check_eap_capa(dev[0], "MSCHAPV2")
3298     bssid = apdev[0]['bssid']
3299     params = hs20_ap_params()
3300     params['hessid'] = bssid
3301     params['disable_dgaf'] = '1'
3302     hostapd.add_ap(apdev[0], params)
3303
3304     dev[0].hs20_enable()
3305     dev[0].connect("test-hs20", proto="RSN", key_mgmt="WPA-EAP", eap="TTLS",
3306                    identity="hs20-test", password="password",
3307                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3308                    scan_freq="2412", update_identifier="54321")
3309     if dev[0].get_status_field("hs20") != "2":
3310         raise Exception("Unexpected hs20 indication")
3311
3312 def test_ap_hs20_random_mac_addr(dev, apdev):
3313     """Hotspot 2.0 connection with random MAC address"""
3314     check_eap_capa(dev[0], "MSCHAPV2")
3315     bssid = apdev[0]['bssid']
3316     params = hs20_ap_params()
3317     params['hessid'] = bssid
3318     params['disable_dgaf'] = '1'
3319     hapd = hostapd.add_ap(apdev[0], params)
3320
3321     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
3322     wpas.interface_add("wlan5")
3323     addr = wpas.p2p_interface_addr()
3324     wpas.request("SET mac_addr 1")
3325     wpas.request("SET preassoc_mac_addr 1")
3326     wpas.request("SET rand_addr_lifetime 60")
3327     wpas.hs20_enable()
3328     wpas.flush_scan_cache()
3329     id = wpas.add_cred_values({ 'realm': "example.com",
3330                                   'username': "hs20-test",
3331                                   'password': "password",
3332                                   'ca_cert': "auth_serv/ca.pem",
3333                                   'domain': "example.com",
3334                                   'update_identifier': "1234" })
3335     interworking_select(wpas, bssid, "home", freq="2412")
3336     interworking_connect(wpas, bssid, "TTLS")
3337     addr1 = wpas.get_driver_status_field("addr")
3338     if addr == addr1:
3339         raise Exception("Did not use random MAC address")
3340
3341     sta = hapd.get_sta(addr)
3342     if sta['addr'] != "FAIL":
3343         raise Exception("Unexpected STA association with permanent address")
3344     sta = hapd.get_sta(addr1)
3345     if sta['addr'] != addr1:
3346         raise Exception("STA association with random address not found")
3347
3348 def test_ap_hs20_multi_network_and_cred_removal(dev, apdev):
3349     """Multiple networks and cred removal"""
3350     check_eap_capa(dev[0], "MSCHAPV2")
3351     bssid = apdev[0]['bssid']
3352     params = hs20_ap_params()
3353     params['nai_realm'] = [ "0,example.com,25[3:26]"]
3354     hapd = hostapd.add_ap(apdev[0], params)
3355
3356     dev[0].add_network()
3357     dev[0].hs20_enable()
3358     id = dev[0].add_cred_values({ 'realm': "example.com",
3359                                   'username': "user",
3360                                   'password': "password" })
3361     interworking_select(dev[0], bssid, freq="2412")
3362     interworking_connect(dev[0], bssid, "PEAP")
3363     dev[0].add_network()
3364
3365     dev[0].request("DISCONNECT")
3366     dev[0].wait_disconnected(timeout=10)
3367
3368     hapd.disable()
3369     hapd.set("ssid", "another ssid")
3370     hapd.enable()
3371
3372     interworking_select(dev[0], bssid, freq="2412")
3373     interworking_connect(dev[0], bssid, "PEAP")
3374     dev[0].add_network()
3375     if len(dev[0].list_networks()) != 5:
3376         raise Exception("Unexpected number of networks prior to remove_crec")
3377
3378     dev[0].dump_monitor()
3379     dev[0].remove_cred(id)
3380     if len(dev[0].list_networks()) != 3:
3381         raise Exception("Unexpected number of networks after to remove_crec")
3382     dev[0].wait_disconnected(timeout=10)
3383
3384 def test_ap_hs20_interworking_add_network(dev, apdev):
3385     """Hotspot 2.0 connection using INTERWORKING_ADD_NETWORK"""
3386     check_eap_capa(dev[0], "MSCHAPV2")
3387     bssid = apdev[0]['bssid']
3388     params = hs20_ap_params()
3389     params['nai_realm'] = [ "0,example.com,21[3:26][6:7][99:99]" ]
3390     hostapd.add_ap(apdev[0], params)
3391
3392     dev[0].hs20_enable()
3393     dev[0].add_cred_values(default_cred(user="user"))
3394     interworking_select(dev[0], bssid, freq=2412)
3395     id = dev[0].interworking_add_network(bssid)
3396     dev[0].select_network(id, freq=2412)
3397     dev[0].wait_connected()
3398
3399 def _test_ap_hs20_proxyarp(dev, apdev):
3400     bssid = apdev[0]['bssid']
3401     params = hs20_ap_params()
3402     params['hessid'] = bssid
3403     params['disable_dgaf'] = '0'
3404     params['proxy_arp'] = '1'
3405     hapd = hostapd.add_ap(apdev[0], params, no_enable=True)
3406     if "OK" in hapd.request("ENABLE"):
3407         raise Exception("Incomplete hostapd configuration was accepted")
3408     hapd.set("ap_isolate", "1")
3409     if "OK" in hapd.request("ENABLE"):
3410         raise Exception("Incomplete hostapd configuration was accepted")
3411     hapd.set('bridge', 'ap-br0')
3412     hapd.dump_monitor()
3413     try:
3414         hapd.enable()
3415     except:
3416         # For now, do not report failures due to missing kernel support
3417         raise HwsimSkip("Could not start hostapd - assume proxyarp not supported in kernel version")
3418     ev = hapd.wait_event(["AP-ENABLED", "AP-DISABLED"], timeout=10)
3419     if ev is None:
3420         raise Exception("AP startup timed out")
3421     if "AP-ENABLED" not in ev:
3422         raise Exception("AP startup failed")
3423
3424     dev[0].hs20_enable()
3425     subprocess.call(['brctl', 'setfd', 'ap-br0', '0'])
3426     subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'up'])
3427
3428     id = dev[0].add_cred_values({ 'realm': "example.com",
3429                                   'username': "hs20-test",
3430                                   'password': "password",
3431                                   'ca_cert': "auth_serv/ca.pem",
3432                                   'domain': "example.com",
3433                                   'update_identifier': "1234" })
3434     interworking_select(dev[0], bssid, "home", freq="2412")
3435     interworking_connect(dev[0], bssid, "TTLS")
3436
3437     dev[1].connect("test-hs20", key_mgmt="WPA-EAP", eap="TTLS",
3438                    identity="hs20-test", password="password",
3439                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3440                    scan_freq="2412")
3441     time.sleep(0.1)
3442
3443     addr0 = dev[0].p2p_interface_addr()
3444     addr1 = dev[1].p2p_interface_addr()
3445
3446     src_ll_opt0 = "\x01\x01" + binascii.unhexlify(addr0.replace(':',''))
3447     src_ll_opt1 = "\x01\x01" + binascii.unhexlify(addr1.replace(':',''))
3448
3449     pkt = build_ns(src_ll=addr0, ip_src="aaaa:bbbb:cccc::2",
3450                    ip_dst="ff02::1:ff00:2", target="aaaa:bbbb:cccc::2",
3451                    opt=src_ll_opt0)
3452     if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
3453         raise Exception("DATA_TEST_FRAME failed")
3454
3455     pkt = build_ns(src_ll=addr1, ip_src="aaaa:bbbb:dddd::2",
3456                    ip_dst="ff02::1:ff00:2", target="aaaa:bbbb:dddd::2",
3457                    opt=src_ll_opt1)
3458     if "OK" not in dev[1].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
3459         raise Exception("DATA_TEST_FRAME failed")
3460
3461     pkt = build_ns(src_ll=addr1, ip_src="aaaa:bbbb:eeee::2",
3462                    ip_dst="ff02::1:ff00:2", target="aaaa:bbbb:eeee::2",
3463                    opt=src_ll_opt1)
3464     if "OK" not in dev[1].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
3465         raise Exception("DATA_TEST_FRAME failed")
3466
3467     matches = get_permanent_neighbors("ap-br0")
3468     logger.info("After connect: " + str(matches))
3469     if len(matches) != 3:
3470         raise Exception("Unexpected number of neighbor entries after connect")
3471     if 'aaaa:bbbb:cccc::2 dev ap-br0 lladdr 02:00:00:00:00:00 PERMANENT' not in matches:
3472         raise Exception("dev0 addr missing")
3473     if 'aaaa:bbbb:dddd::2 dev ap-br0 lladdr 02:00:00:00:01:00 PERMANENT' not in matches:
3474         raise Exception("dev1 addr(1) missing")
3475     if 'aaaa:bbbb:eeee::2 dev ap-br0 lladdr 02:00:00:00:01:00 PERMANENT' not in matches:
3476         raise Exception("dev1 addr(2) missing")
3477     dev[0].request("DISCONNECT")
3478     dev[1].request("DISCONNECT")
3479     time.sleep(0.5)
3480     matches = get_permanent_neighbors("ap-br0")
3481     logger.info("After disconnect: " + str(matches))
3482     if len(matches) > 0:
3483         raise Exception("Unexpected neighbor entries after disconnect")
3484
3485 def test_ap_hs20_hidden_ssid_in_scan_res(dev, apdev):
3486     """Hotspot 2.0 connection with hidden SSId in scan results"""
3487     check_eap_capa(dev[0], "MSCHAPV2")
3488     bssid = apdev[0]['bssid']
3489
3490     hapd = hostapd.add_ap(apdev[0], { "ssid": 'secret',
3491                                       "ignore_broadcast_ssid": "1" })
3492     dev[0].scan_for_bss(bssid, freq=2412)
3493     hapd.disable()
3494     hapd_global = hostapd.HostapdGlobal(apdev[0])
3495     hapd_global.flush()
3496     hapd_global.remove(apdev[0]['ifname'])
3497
3498     params = hs20_ap_params()
3499     params['hessid'] = bssid
3500     hapd = hostapd.add_ap(apdev[0], params)
3501
3502     dev[0].hs20_enable()
3503     id = dev[0].add_cred_values({ 'realm': "example.com",
3504                                   'username': "hs20-test",
3505                                   'password': "password",
3506                                   'ca_cert': "auth_serv/ca.pem",
3507                                   'domain': "example.com" })
3508     interworking_select(dev[0], bssid, "home", freq="2412")
3509     interworking_connect(dev[0], bssid, "TTLS")
3510
3511     # clear BSS table to avoid issues in following test cases
3512     dev[0].request("DISCONNECT")
3513     dev[0].wait_disconnected()
3514     hapd.disable()
3515     dev[0].flush_scan_cache()
3516     dev[0].flush_scan_cache()
3517
3518 def test_ap_hs20_proxyarp(dev, apdev):
3519     """Hotspot 2.0 and ProxyARP"""
3520     check_eap_capa(dev[0], "MSCHAPV2")
3521     try:
3522         _test_ap_hs20_proxyarp(dev, apdev)
3523     finally:
3524         subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'down'],
3525                         stderr=open('/dev/null', 'w'))
3526         subprocess.call(['brctl', 'delbr', 'ap-br0'],
3527                         stderr=open('/dev/null', 'w'))
3528
3529 def _test_ap_hs20_proxyarp_dgaf(dev, apdev, disabled):
3530     bssid = apdev[0]['bssid']
3531     params = hs20_ap_params()
3532     params['hessid'] = bssid
3533     params['disable_dgaf'] = '1' if disabled else '0'
3534     params['proxy_arp'] = '1'
3535     params['na_mcast_to_ucast'] = '1'
3536     params['ap_isolate'] = '1'
3537     params['bridge'] = 'ap-br0'
3538     hapd = hostapd.add_ap(apdev[0], params, no_enable=True)
3539     try:
3540         hapd.enable()
3541     except:
3542         # For now, do not report failures due to missing kernel support
3543         raise HwsimSkip("Could not start hostapd - assume proxyarp not supported in kernel version")
3544     ev = hapd.wait_event(["AP-ENABLED"], timeout=10)
3545     if ev is None:
3546         raise Exception("AP startup timed out")
3547
3548     dev[0].hs20_enable()
3549     subprocess.call(['brctl', 'setfd', 'ap-br0', '0'])
3550     subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'up'])
3551
3552     id = dev[0].add_cred_values({ 'realm': "example.com",
3553                                   'username': "hs20-test",
3554                                   'password': "password",
3555                                   'ca_cert': "auth_serv/ca.pem",
3556                                   'domain': "example.com",
3557                                   'update_identifier': "1234" })
3558     interworking_select(dev[0], bssid, "home", freq="2412")
3559     interworking_connect(dev[0], bssid, "TTLS")
3560
3561     dev[1].connect("test-hs20", key_mgmt="WPA-EAP", eap="TTLS",
3562                    identity="hs20-test", password="password",
3563                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3564                    scan_freq="2412")
3565     time.sleep(0.1)
3566
3567     addr0 = dev[0].p2p_interface_addr()
3568
3569     src_ll_opt0 = "\x01\x01" + binascii.unhexlify(addr0.replace(':',''))
3570
3571     pkt = build_ns(src_ll=addr0, ip_src="aaaa:bbbb:cccc::2",
3572                    ip_dst="ff02::1:ff00:2", target="aaaa:bbbb:cccc::2",
3573                    opt=src_ll_opt0)
3574     if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
3575         raise Exception("DATA_TEST_FRAME failed")
3576
3577     pkt = build_ra(src_ll=apdev[0]['bssid'], ip_src="aaaa:bbbb:cccc::33",
3578                    ip_dst="ff01::1")
3579     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
3580         raise Exception("DATA_TEST_FRAME failed")
3581
3582     pkt = build_na(src_ll=apdev[0]['bssid'], ip_src="aaaa:bbbb:cccc::44",
3583                    ip_dst="ff01::1", target="aaaa:bbbb:cccc::55")
3584     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
3585         raise Exception("DATA_TEST_FRAME failed")
3586
3587     pkt = build_dhcp_ack(dst_ll="ff:ff:ff:ff:ff:ff", src_ll=bssid,
3588                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
3589                          yiaddr="192.168.1.123", chaddr=addr0)
3590     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
3591         raise Exception("DATA_TEST_FRAME failed")
3592     # another copy for additional code coverage
3593     pkt = build_dhcp_ack(dst_ll=addr0, src_ll=bssid,
3594                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
3595                          yiaddr="192.168.1.123", chaddr=addr0)
3596     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
3597         raise Exception("DATA_TEST_FRAME failed")
3598
3599     matches = get_permanent_neighbors("ap-br0")
3600     logger.info("After connect: " + str(matches))
3601     if len(matches) != 2:
3602         raise Exception("Unexpected number of neighbor entries after connect")
3603     if 'aaaa:bbbb:cccc::2 dev ap-br0 lladdr 02:00:00:00:00:00 PERMANENT' not in matches:
3604         raise Exception("dev0 addr missing")
3605     if '192.168.1.123 dev ap-br0 lladdr 02:00:00:00:00:00 PERMANENT' not in matches:
3606         raise Exception("dev0 IPv4 addr missing")
3607     dev[0].request("DISCONNECT")
3608     dev[1].request("DISCONNECT")
3609     time.sleep(0.5)
3610     matches = get_permanent_neighbors("ap-br0")
3611     logger.info("After disconnect: " + str(matches))
3612     if len(matches) > 0:
3613         raise Exception("Unexpected neighbor entries after disconnect")
3614
3615 def test_ap_hs20_proxyarp_disable_dgaf(dev, apdev):
3616     """Hotspot 2.0 and ProxyARP with DGAF disabled"""
3617     check_eap_capa(dev[0], "MSCHAPV2")
3618     try:
3619         _test_ap_hs20_proxyarp_dgaf(dev, apdev, True)
3620     finally:
3621         subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'down'],
3622                         stderr=open('/dev/null', 'w'))
3623         subprocess.call(['brctl', 'delbr', 'ap-br0'],
3624                         stderr=open('/dev/null', 'w'))
3625
3626 def test_ap_hs20_proxyarp_enable_dgaf(dev, apdev):
3627     """Hotspot 2.0 and ProxyARP with DGAF enabled"""
3628     check_eap_capa(dev[0], "MSCHAPV2")
3629     try:
3630         _test_ap_hs20_proxyarp_dgaf(dev, apdev, False)
3631     finally:
3632         subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'down'],
3633                         stderr=open('/dev/null', 'w'))
3634         subprocess.call(['brctl', 'delbr', 'ap-br0'],
3635                         stderr=open('/dev/null', 'w'))
3636
3637 def ip_checksum(buf):
3638     sum = 0
3639     if len(buf) & 0x01:
3640         buf += '\0x00'
3641     for i in range(0, len(buf), 2):
3642         val, = struct.unpack('H', buf[i:i+2])
3643         sum += val
3644     while (sum >> 16):
3645         sum = (sum & 0xffff) + (sum >> 16)
3646     return struct.pack('H', ~sum & 0xffff)
3647
3648 def ipv6_solicited_node_mcaddr(target):
3649     prefix = socket.inet_pton(socket.AF_INET6, "ff02::1:ff00:0")
3650     mask = socket.inet_pton(socket.AF_INET6, "::ff:ffff")
3651     _target = socket.inet_pton(socket.AF_INET6, target)
3652     p = struct.unpack('4I', prefix)
3653     m = struct.unpack('4I', mask)
3654     t = struct.unpack('4I', _target)
3655     res = (p[0] | (t[0] & m[0]),
3656            p[1] | (t[1] & m[1]),
3657            p[2] | (t[2] & m[2]),
3658            p[3] | (t[3] & m[3]))
3659     return socket.inet_ntop(socket.AF_INET6, struct.pack('4I', *res))
3660
3661 def build_icmpv6(ipv6_addrs, type, code, payload):
3662     start = struct.pack("BB", type, code)
3663     end = payload
3664     icmp = start + '\x00\x00' + end
3665     pseudo = ipv6_addrs + struct.pack(">LBBBB", len(icmp), 0, 0, 0, 58)
3666     csum = ip_checksum(pseudo + icmp)
3667     return start + csum + end
3668
3669 def build_ra(src_ll, ip_src, ip_dst, cur_hop_limit=0, router_lifetime=0,
3670              reachable_time=0, retrans_timer=0, opt=None):
3671     link_mc = binascii.unhexlify("3333ff000002")
3672     _src_ll = binascii.unhexlify(src_ll.replace(':',''))
3673     proto = '\x86\xdd'
3674     ehdr = link_mc + _src_ll + proto
3675     _ip_src = socket.inet_pton(socket.AF_INET6, ip_src)
3676     _ip_dst = socket.inet_pton(socket.AF_INET6, ip_dst)
3677
3678     adv = struct.pack('>BBHLL', cur_hop_limit, 0, router_lifetime,
3679                       reachable_time, retrans_timer)
3680     if opt:
3681         payload = adv + opt
3682     else:
3683         payload = adv
3684     icmp = build_icmpv6(_ip_src + _ip_dst, 134, 0, payload)
3685
3686     ipv6 = struct.pack('>BBBBHBB', 0x60, 0, 0, 0, len(icmp), 58, 255)
3687     ipv6 += _ip_src + _ip_dst
3688
3689     return ehdr + ipv6 + icmp
3690
3691 def build_ns(src_ll, ip_src, ip_dst, target, opt=None):
3692     link_mc = binascii.unhexlify("3333ff000002")
3693     _src_ll = binascii.unhexlify(src_ll.replace(':',''))
3694     proto = '\x86\xdd'
3695     ehdr = link_mc + _src_ll + proto
3696     _ip_src = socket.inet_pton(socket.AF_INET6, ip_src)
3697     if ip_dst is None:
3698         ip_dst = ipv6_solicited_node_mcaddr(target)
3699     _ip_dst = socket.inet_pton(socket.AF_INET6, ip_dst)
3700
3701     reserved = '\x00\x00\x00\x00'
3702     _target = socket.inet_pton(socket.AF_INET6, target)
3703     if opt:
3704         payload = reserved + _target + opt
3705     else:
3706         payload = reserved + _target
3707     icmp = build_icmpv6(_ip_src + _ip_dst, 135, 0, payload)
3708
3709     ipv6 = struct.pack('>BBBBHBB', 0x60, 0, 0, 0, len(icmp), 58, 255)
3710     ipv6 += _ip_src + _ip_dst
3711
3712     return ehdr + ipv6 + icmp
3713
3714 def send_ns(dev, src_ll=None, target=None, ip_src=None, ip_dst=None, opt=None,
3715             hapd_bssid=None):
3716     if hapd_bssid:
3717         if src_ll is None:
3718             src_ll = hapd_bssid
3719         cmd = "DATA_TEST_FRAME ifname=ap-br0 "
3720     else:
3721         if src_ll is None:
3722             src_ll = dev.p2p_interface_addr()
3723         cmd = "DATA_TEST_FRAME "
3724
3725     if opt is None:
3726         opt = "\x01\x01" + binascii.unhexlify(src_ll.replace(':',''))
3727
3728     pkt = build_ns(src_ll=src_ll, ip_src=ip_src, ip_dst=ip_dst, target=target,
3729                    opt=opt)
3730     if "OK" not in dev.request(cmd + binascii.hexlify(pkt)):
3731         raise Exception("DATA_TEST_FRAME failed")
3732
3733 def build_na(src_ll, ip_src, ip_dst, target, opt=None, flags=0):
3734     link_mc = binascii.unhexlify("3333ff000002")
3735     _src_ll = binascii.unhexlify(src_ll.replace(':',''))
3736     proto = '\x86\xdd'
3737     ehdr = link_mc + _src_ll + proto
3738     _ip_src = socket.inet_pton(socket.AF_INET6, ip_src)
3739     _ip_dst = socket.inet_pton(socket.AF_INET6, ip_dst)
3740
3741     _target = socket.inet_pton(socket.AF_INET6, target)
3742     if opt:
3743         payload = struct.pack('>Bxxx', flags) + _target + opt
3744     else:
3745         payload = struct.pack('>Bxxx', flags) + _target
3746     icmp = build_icmpv6(_ip_src + _ip_dst, 136, 0, payload)
3747
3748     ipv6 = struct.pack('>BBBBHBB', 0x60, 0, 0, 0, len(icmp), 58, 255)
3749     ipv6 += _ip_src + _ip_dst
3750
3751     return ehdr + ipv6 + icmp
3752
3753 def send_na(dev, src_ll=None, target=None, ip_src=None, ip_dst=None, opt=None,
3754             hapd_bssid=None):
3755     if hapd_bssid:
3756         if src_ll is None:
3757             src_ll = hapd_bssid
3758         cmd = "DATA_TEST_FRAME ifname=ap-br0 "
3759     else:
3760         if src_ll is None:
3761             src_ll = dev.p2p_interface_addr()
3762         cmd = "DATA_TEST_FRAME "
3763
3764     pkt = build_na(src_ll=src_ll, ip_src=ip_src, ip_dst=ip_dst, target=target,
3765                    opt=opt)
3766     if "OK" not in dev.request(cmd + binascii.hexlify(pkt)):
3767         raise Exception("DATA_TEST_FRAME failed")
3768
3769 def build_dhcp_ack(dst_ll, src_ll, ip_src, ip_dst, yiaddr, chaddr,
3770                    subnet_mask="255.255.255.0", truncated_opt=False,
3771                    wrong_magic=False, force_tot_len=None, no_dhcp=False):
3772     _dst_ll = binascii.unhexlify(dst_ll.replace(':',''))
3773     _src_ll = binascii.unhexlify(src_ll.replace(':',''))
3774     proto = '\x08\x00'
3775     ehdr = _dst_ll + _src_ll + proto
3776     _ip_src = socket.inet_pton(socket.AF_INET, ip_src)
3777     _ip_dst = socket.inet_pton(socket.AF_INET, ip_dst)
3778     _subnet_mask = socket.inet_pton(socket.AF_INET, subnet_mask)
3779
3780     _ciaddr = '\x00\x00\x00\x00'
3781     _yiaddr = socket.inet_pton(socket.AF_INET, yiaddr)
3782     _siaddr = '\x00\x00\x00\x00'
3783     _giaddr = '\x00\x00\x00\x00'
3784     _chaddr = binascii.unhexlify(chaddr.replace(':','') + "00000000000000000000")
3785     payload = struct.pack('>BBBBL3BB', 2, 1, 6, 0, 12345, 0, 0, 0, 0)
3786     payload += _ciaddr + _yiaddr + _siaddr + _giaddr + _chaddr + 192*'\x00'
3787     # magic
3788     if wrong_magic:
3789         payload += '\x63\x82\x53\x00'
3790     else:
3791         payload += '\x63\x82\x53\x63'
3792     if truncated_opt:
3793         payload += '\x22\xff\x00'
3794     # Option: DHCP Message Type = ACK
3795     payload += '\x35\x01\x05'
3796     # Pad Option
3797     payload += '\x00'
3798     # Option: Subnet Mask
3799     payload += '\x01\x04' + _subnet_mask
3800     # Option: Time Offset
3801     payload += struct.pack('>BBL', 2, 4, 0)
3802     # End Option
3803     payload += '\xff'
3804     # Pad Option
3805     payload += '\x00\x00\x00\x00'
3806
3807     if no_dhcp:
3808         payload = struct.pack('>BBBBL3BB', 2, 1, 6, 0, 12345, 0, 0, 0, 0)
3809         payload += _ciaddr + _yiaddr + _siaddr + _giaddr + _chaddr + 192*'\x00'
3810
3811     udp = struct.pack('>HHHH', 67, 68, 8 + len(payload), 0) + payload
3812
3813     if force_tot_len:
3814         tot_len = force_tot_len
3815     else:
3816         tot_len = 20 + len(udp)
3817     start = struct.pack('>BBHHBBBB', 0x45, 0, tot_len, 0, 0, 0, 128, 17)
3818     ipv4 = start + '\x00\x00' + _ip_src + _ip_dst
3819     csum = ip_checksum(ipv4)
3820     ipv4 = start + csum + _ip_src + _ip_dst
3821
3822     return ehdr + ipv4 + udp
3823
3824 def build_arp(dst_ll, src_ll, opcode, sender_mac, sender_ip,
3825               target_mac, target_ip):
3826     _dst_ll = binascii.unhexlify(dst_ll.replace(':',''))
3827     _src_ll = binascii.unhexlify(src_ll.replace(':',''))
3828     proto = '\x08\x06'
3829     ehdr = _dst_ll + _src_ll + proto
3830
3831     _sender_mac = binascii.unhexlify(sender_mac.replace(':',''))
3832     _sender_ip = socket.inet_pton(socket.AF_INET, sender_ip)
3833     _target_mac = binascii.unhexlify(target_mac.replace(':',''))
3834     _target_ip = socket.inet_pton(socket.AF_INET, target_ip)
3835
3836     arp = struct.pack('>HHBBH', 1, 0x0800, 6, 4, opcode)
3837     arp += _sender_mac + _sender_ip
3838     arp += _target_mac + _target_ip
3839
3840     return ehdr + arp
3841
3842 def send_arp(dev, dst_ll="ff:ff:ff:ff:ff:ff", src_ll=None, opcode=1,
3843              sender_mac=None, sender_ip="0.0.0.0",
3844              target_mac="00:00:00:00:00:00", target_ip="0.0.0.0",
3845              hapd_bssid=None):
3846     if hapd_bssid:
3847         if src_ll is None:
3848             src_ll = hapd_bssid
3849         if sender_mac is None:
3850             sender_mac = hapd_bssid
3851         cmd = "DATA_TEST_FRAME ifname=ap-br0 "
3852     else:
3853         if src_ll is None:
3854             src_ll = dev.p2p_interface_addr()
3855         if sender_mac is None:
3856             sender_mac = dev.p2p_interface_addr()
3857         cmd = "DATA_TEST_FRAME "
3858
3859     pkt = build_arp(dst_ll=dst_ll, src_ll=src_ll, opcode=opcode,
3860                     sender_mac=sender_mac, sender_ip=sender_ip,
3861                     target_mac=target_mac, target_ip=target_ip)
3862     if "OK" not in dev.request(cmd + binascii.hexlify(pkt)):
3863         raise Exception("DATA_TEST_FRAME failed")
3864
3865 def get_permanent_neighbors(ifname):
3866     cmd = subprocess.Popen(['ip', 'nei'], stdout=subprocess.PIPE)
3867     res = cmd.stdout.read()
3868     cmd.stdout.close()
3869     return [ line for line in res.splitlines() if "PERMANENT" in line and ifname in line ]
3870
3871 def get_bridge_macs(ifname):
3872     cmd = subprocess.Popen(['brctl', 'showmacs', ifname],
3873                            stdout=subprocess.PIPE)
3874     res = cmd.stdout.read()
3875     cmd.stdout.close()
3876     return res
3877
3878 def tshark_get_arp(cap, filter):
3879     res = run_tshark(cap, filter,
3880                      [ "eth.dst", "eth.src",
3881                        "arp.src.hw_mac", "arp.src.proto_ipv4",
3882                        "arp.dst.hw_mac", "arp.dst.proto_ipv4" ],
3883                      wait=False)
3884     frames = []
3885     for l in res.splitlines():
3886         frames.append(l.split('\t'))
3887     return frames
3888
3889 def tshark_get_ns(cap):
3890     res = run_tshark(cap, "icmpv6.type == 135",
3891                      [ "eth.dst", "eth.src",
3892                        "ipv6.src", "ipv6.dst",
3893                        "icmpv6.nd.ns.target_address",
3894                        "icmpv6.opt.linkaddr" ],
3895                      wait=False)
3896     frames = []
3897     for l in res.splitlines():
3898         frames.append(l.split('\t'))
3899     return frames
3900
3901 def tshark_get_na(cap):
3902     res = run_tshark(cap, "icmpv6.type == 136",
3903                      [ "eth.dst", "eth.src",
3904                        "ipv6.src", "ipv6.dst",
3905                        "icmpv6.nd.na.target_address",
3906                        "icmpv6.opt.linkaddr" ],
3907                      wait=False)
3908     frames = []
3909     for l in res.splitlines():
3910         frames.append(l.split('\t'))
3911     return frames
3912
3913 def _test_proxyarp_open(dev, apdev, params, ebtables=False):
3914     prefix = "proxyarp_open"
3915     if ebtables:
3916         prefix += "_ebtables"
3917     cap_br = os.path.join(params['logdir'], prefix + ".ap-br0.pcap")
3918     cap_dev0 = os.path.join(params['logdir'],
3919                             prefix + ".%s.pcap" % dev[0].ifname)
3920     cap_dev1 = os.path.join(params['logdir'],
3921                             prefix + ".%s.pcap" % dev[1].ifname)
3922     cap_dev2 = os.path.join(params['logdir'],
3923                             prefix + ".%s.pcap" % dev[2].ifname)
3924
3925     bssid = apdev[0]['bssid']
3926     params = { 'ssid': 'open' }
3927     params['proxy_arp'] = '1'
3928     hapd = hostapd.add_ap(apdev[0], params, no_enable=True)
3929     hapd.set("ap_isolate", "1")
3930     hapd.set('bridge', 'ap-br0')
3931     hapd.dump_monitor()
3932     try:
3933         hapd.enable()
3934     except:
3935         # For now, do not report failures due to missing kernel support
3936         raise HwsimSkip("Could not start hostapd - assume proxyarp not supported in kernel version")
3937     ev = hapd.wait_event(["AP-ENABLED", "AP-DISABLED"], timeout=10)
3938     if ev is None:
3939         raise Exception("AP startup timed out")
3940     if "AP-ENABLED" not in ev:
3941         raise Exception("AP startup failed")
3942
3943     params2 = { 'ssid': 'another' }
3944     hapd2 = hostapd.add_ap(apdev[1], params2, no_enable=True)
3945     hapd2.set('bridge', 'ap-br0')
3946     hapd2.enable()
3947
3948     subprocess.call(['brctl', 'setfd', 'ap-br0', '0'])
3949     subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'up'])
3950
3951     if ebtables:
3952         for chain in [ 'FORWARD', 'OUTPUT' ]:
3953             subprocess.call(['ebtables', '-A', chain, '-p', 'ARP',
3954                              '-d', 'Broadcast', '-o', apdev[0]['ifname'],
3955                              '-j', 'DROP'])
3956             subprocess.call(['ebtables', '-A', chain, '-d', 'Multicast',
3957                              '-p', 'IPv6', '--ip6-protocol', 'ipv6-icmp',
3958                              '--ip6-icmp-type', 'neighbor-solicitation',
3959                              '-o', apdev[0]['ifname'], '-j', 'DROP'])
3960             subprocess.call(['ebtables', '-A', chain, '-d', 'Multicast',
3961                              '-p', 'IPv6', '--ip6-protocol', 'ipv6-icmp',
3962                              '--ip6-icmp-type', 'neighbor-advertisement',
3963                              '-o', apdev[0]['ifname'], '-j', 'DROP'])
3964             subprocess.call(['ebtables', '-A', chain,
3965                              '-p', 'IPv6', '--ip6-protocol', 'ipv6-icmp',
3966                              '--ip6-icmp-type', 'router-solicitation',
3967                              '-o', apdev[0]['ifname'], '-j', 'DROP'])
3968             # Multicast Listener Report Message
3969             subprocess.call(['ebtables', '-A', chain, '-d', 'Multicast',
3970                              '-p', 'IPv6', '--ip6-protocol', 'ipv6-icmp',
3971                              '--ip6-icmp-type', '143',
3972                              '-o', apdev[0]['ifname'], '-j', 'DROP'])
3973
3974     time.sleep(0.5)
3975     cmd = {}
3976     cmd[0] = subprocess.Popen(['tcpdump', '-p', '-U', '-i', 'ap-br0',
3977                                '-w', cap_br, '-s', '2000'],
3978                               stderr=open('/dev/null', 'w'))
3979     cmd[1] = subprocess.Popen(['tcpdump', '-p', '-U', '-i', dev[0].ifname,
3980                                '-w', cap_dev0, '-s', '2000'],
3981                               stderr=open('/dev/null', 'w'))
3982     cmd[2] = subprocess.Popen(['tcpdump', '-p', '-U', '-i', dev[1].ifname,
3983                                '-w', cap_dev1, '-s', '2000'],
3984                               stderr=open('/dev/null', 'w'))
3985     cmd[3] = subprocess.Popen(['tcpdump', '-p', '-U', '-i', dev[2].ifname,
3986                                '-w', cap_dev2, '-s', '2000'],
3987                               stderr=open('/dev/null', 'w'))
3988
3989     dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3990     dev[1].connect("open", key_mgmt="NONE", scan_freq="2412")
3991     dev[2].connect("another", key_mgmt="NONE", scan_freq="2412")
3992     time.sleep(0.1)
3993
3994     brcmd = subprocess.Popen(['brctl', 'show'], stdout=subprocess.PIPE)
3995     res = brcmd.stdout.read()
3996     brcmd.stdout.close()
3997     logger.info("Bridge setup: " + res)
3998
3999     brcmd = subprocess.Popen(['brctl', 'showstp', 'ap-br0'],
4000                              stdout=subprocess.PIPE)
4001     res = brcmd.stdout.read()
4002     brcmd.stdout.close()
4003     logger.info("Bridge showstp: " + res)
4004
4005     addr0 = dev[0].p2p_interface_addr()
4006     addr1 = dev[1].p2p_interface_addr()
4007     addr2 = dev[2].p2p_interface_addr()
4008
4009     src_ll_opt0 = "\x01\x01" + binascii.unhexlify(addr0.replace(':',''))
4010     src_ll_opt1 = "\x01\x01" + binascii.unhexlify(addr1.replace(':',''))
4011
4012     # DAD NS
4013     send_ns(dev[0], ip_src="::", target="aaaa:bbbb:cccc::2")
4014
4015     send_ns(dev[0], ip_src="aaaa:bbbb:cccc::2", target="aaaa:bbbb:cccc::2")
4016     # test frame without source link-layer address option
4017     send_ns(dev[0], ip_src="aaaa:bbbb:cccc::2", target="aaaa:bbbb:cccc::2",
4018             opt='')
4019     # test frame with bogus option
4020     send_ns(dev[0], ip_src="aaaa:bbbb:cccc::2", target="aaaa:bbbb:cccc::2",
4021             opt="\x70\x01\x01\x02\x03\x04\x05\x05")
4022     # test frame with truncated source link-layer address option
4023     send_ns(dev[0], ip_src="aaaa:bbbb:cccc::2", target="aaaa:bbbb:cccc::2",
4024             opt="\x01\x01\x01\x02\x03\x04")
4025     # test frame with foreign source link-layer address option
4026     send_ns(dev[0], ip_src="aaaa:bbbb:cccc::2", target="aaaa:bbbb:cccc::2",
4027             opt="\x01\x01\x01\x02\x03\x04\x05\x06")
4028
4029     send_ns(dev[1], ip_src="aaaa:bbbb:dddd::2", target="aaaa:bbbb:dddd::2")
4030
4031     send_ns(dev[1], ip_src="aaaa:bbbb:eeee::2", target="aaaa:bbbb:eeee::2")
4032     # another copy for additional code coverage
4033     send_ns(dev[1], ip_src="aaaa:bbbb:eeee::2", target="aaaa:bbbb:eeee::2")
4034
4035     pkt = build_dhcp_ack(dst_ll="ff:ff:ff:ff:ff:ff", src_ll=bssid,
4036                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
4037                          yiaddr="192.168.1.124", chaddr=addr0)
4038     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
4039         raise Exception("DATA_TEST_FRAME failed")
4040     # Change address and verify unicast
4041     pkt = build_dhcp_ack(dst_ll=addr0, src_ll=bssid,
4042                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
4043                          yiaddr="192.168.1.123", chaddr=addr0)
4044     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
4045         raise Exception("DATA_TEST_FRAME failed")
4046
4047     # Not-associated client MAC address
4048     pkt = build_dhcp_ack(dst_ll="ff:ff:ff:ff:ff:ff", src_ll=bssid,
4049                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
4050                          yiaddr="192.168.1.125", chaddr="22:33:44:55:66:77")
4051     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
4052         raise Exception("DATA_TEST_FRAME failed")
4053
4054     # No IP address
4055     pkt = build_dhcp_ack(dst_ll=addr1, src_ll=bssid,
4056                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
4057                          yiaddr="0.0.0.0", chaddr=addr1)
4058     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
4059         raise Exception("DATA_TEST_FRAME failed")
4060
4061     # Zero subnet mask
4062     pkt = build_dhcp_ack(dst_ll=addr1, src_ll=bssid,
4063                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
4064                          yiaddr="192.168.1.126", chaddr=addr1,
4065                          subnet_mask="0.0.0.0")
4066     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
4067         raise Exception("DATA_TEST_FRAME failed")
4068
4069     # Truncated option
4070     pkt = build_dhcp_ack(dst_ll=addr1, src_ll=bssid,
4071                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
4072                          yiaddr="192.168.1.127", chaddr=addr1,
4073                          truncated_opt=True)
4074     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
4075         raise Exception("DATA_TEST_FRAME failed")
4076
4077     # Wrong magic
4078     pkt = build_dhcp_ack(dst_ll=addr1, src_ll=bssid,
4079                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
4080                          yiaddr="192.168.1.128", chaddr=addr1,
4081                          wrong_magic=True)
4082     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
4083         raise Exception("DATA_TEST_FRAME failed")
4084
4085     # Wrong IPv4 total length
4086     pkt = build_dhcp_ack(dst_ll=addr1, src_ll=bssid,
4087                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
4088                          yiaddr="192.168.1.129", chaddr=addr1,
4089                          force_tot_len=1000)
4090     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
4091         raise Exception("DATA_TEST_FRAME failed")
4092
4093     # BOOTP
4094     pkt = build_dhcp_ack(dst_ll=addr1, src_ll=bssid,
4095                          ip_src="192.168.1.1", ip_dst="255.255.255.255",
4096                          yiaddr="192.168.1.129", chaddr=addr1,
4097                          no_dhcp=True)
4098     if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
4099         raise Exception("DATA_TEST_FRAME failed")
4100
4101     macs = get_bridge_macs("ap-br0")
4102     logger.info("After connect (showmacs): " + str(macs))
4103
4104     matches = get_permanent_neighbors("ap-br0")
4105     logger.info("After connect: " + str(matches))
4106     if len(matches) != 4:
4107         raise Exception("Unexpected number of neighbor entries after connect")
4108     if 'aaaa:bbbb:cccc::2 dev ap-br0 lladdr 02:00:00:00:00:00 PERMANENT' not in matches:
4109         raise Exception("dev0 addr missing")
4110     if 'aaaa:bbbb:dddd::2 dev ap-br0 lladdr 02:00:00:00:01:00 PERMANENT' not in matches:
4111         raise Exception("dev1 addr(1) missing")
4112     if 'aaaa:bbbb:eeee::2 dev ap-br0 lladdr 02:00:00:00:01:00 PERMANENT' not in matches:
4113         raise Exception("dev1 addr(2) missing")
4114     if '192.168.1.123 dev ap-br0 lladdr 02:00:00:00:00:00 PERMANENT' not in matches:
4115         raise Exception("dev0 IPv4 addr missing")
4116
4117     targets = [ "192.168.1.123", "192.168.1.124", "192.168.1.125",
4118                 "192.168.1.126" ]
4119     for target in targets:
4120         send_arp(dev[1], sender_ip="192.168.1.100", target_ip=target)
4121
4122     for target in targets:
4123         send_arp(hapd, hapd_bssid=bssid, sender_ip="192.168.1.101",
4124                  target_ip=target)
4125
4126     for target in targets:
4127         send_arp(dev[2], sender_ip="192.168.1.103", target_ip=target)
4128
4129     # ARP Probe from wireless STA
4130     send_arp(dev[1], target_ip="192.168.1.127")
4131     # ARP Announcement from wireless STA
4132     send_arp(dev[1], sender_ip="192.168.1.127", target_ip="192.168.1.127")
4133     send_arp(dev[1], sender_ip="192.168.1.127", target_ip="192.168.1.127",
4134              opcode=2)
4135
4136     macs = get_bridge_macs("ap-br0")
4137     logger.info("After ARP Probe + Announcement (showmacs): " + str(macs))
4138
4139     matches = get_permanent_neighbors("ap-br0")
4140     logger.info("After ARP Probe + Announcement: " + str(matches))
4141
4142     # ARP Request for the newly introduced IP address from wireless STA
4143     send_arp(dev[0], sender_ip="192.168.1.123", target_ip="192.168.1.127")
4144
4145     # ARP Request for the newly introduced IP address from bridge
4146     send_arp(hapd, hapd_bssid=bssid, sender_ip="192.168.1.102",
4147              target_ip="192.168.1.127")
4148     send_arp(dev[2], sender_ip="192.168.1.103", target_ip="192.168.1.127")
4149
4150     # ARP Probe from bridge
4151     send_arp(hapd, hapd_bssid=bssid, target_ip="192.168.1.130")
4152     send_arp(dev[2], target_ip="192.168.1.131")
4153     # ARP Announcement from bridge (not to be learned by AP for proxyarp)
4154     send_arp(hapd, hapd_bssid=bssid, sender_ip="192.168.1.130",
4155              target_ip="192.168.1.130")
4156     send_arp(hapd, hapd_bssid=bssid, sender_ip="192.168.1.130",
4157              target_ip="192.168.1.130", opcode=2)
4158     send_arp(dev[2], sender_ip="192.168.1.131", target_ip="192.168.1.131")
4159     send_arp(dev[2], sender_ip="192.168.1.131", target_ip="192.168.1.131",
4160              opcode=2)
4161
4162     macs = get_bridge_macs("ap-br0")
4163     logger.info("After ARP Probe + Announcement (showmacs): " + str(macs))
4164
4165     matches = get_permanent_neighbors("ap-br0")
4166     logger.info("After ARP Probe + Announcement: " + str(matches))
4167
4168     # ARP Request for the newly introduced IP address from wireless STA
4169     send_arp(dev[0], sender_ip="192.168.1.123", target_ip="192.168.1.130")
4170     # ARP Response from bridge (AP does not proxy for non-wireless devices)
4171     send_arp(hapd, hapd_bssid=bssid, dst_ll=addr0, sender_ip="192.168.1.130",
4172              target_ip="192.168.1.123", opcode=2)
4173
4174     # ARP Request for the newly introduced IP address from wireless STA
4175     send_arp(dev[0], sender_ip="192.168.1.123", target_ip="192.168.1.131")
4176     # ARP Response from bridge (AP does not proxy for non-wireless devices)
4177     send_arp(dev[2], dst_ll=addr0, sender_ip="192.168.1.131",
4178              target_ip="192.168.1.123", opcode=2)
4179
4180     # ARP Request for the newly introduced IP address from bridge
4181     send_arp(hapd, hapd_bssid=bssid, sender_ip="192.168.1.102",
4182              target_ip="192.168.1.130")
4183     send_arp(dev[2], sender_ip="192.168.1.104", target_ip="192.168.1.131")
4184
4185     # ARP Probe from wireless STA (duplicate address; learned through DHCP)
4186     send_arp(dev[1], target_ip="192.168.1.123")
4187     # ARP Probe from wireless STA (duplicate address; learned through ARP)
4188     send_arp(dev[0], target_ip="192.168.1.127")
4189
4190     # Gratuitous ARP Reply for another STA's IP address
4191     send_arp(dev[0], opcode=2, sender_mac=addr0, sender_ip="192.168.1.127",
4192              target_mac=addr1, target_ip="192.168.1.127")
4193     send_arp(dev[1], opcode=2, sender_mac=addr1, sender_ip="192.168.1.123",
4194              target_mac=addr0, target_ip="192.168.1.123")
4195     # ARP Request to verify previous mapping
4196     send_arp(dev[1], sender_ip="192.168.1.127", target_ip="192.168.1.123")
4197     send_arp(dev[0], sender_ip="192.168.1.123", target_ip="192.168.1.127")
4198
4199     time.sleep(0.1)
4200
4201     send_ns(dev[0], target="aaaa:bbbb:dddd::2", ip_src="aaaa:bbbb:cccc::2")
4202     time.sleep(0.1)
4203     send_ns(dev[1], target="aaaa:bbbb:cccc::2", ip_src="aaaa:bbbb:dddd::2")
4204     time.sleep(0.1)
4205     send_ns(hapd, hapd_bssid=bssid, target="aaaa:bbbb:dddd::2",
4206             ip_src="aaaa:bbbb:ffff::2")
4207     time.sleep(0.1)
4208     send_ns(dev[2], target="aaaa:bbbb:cccc::2", ip_src="aaaa:bbbb:ff00::2")
4209     time.sleep(0.1)
4210     send_ns(dev[2], target="aaaa:bbbb:dddd::2", ip_src="aaaa:bbbb:ff00::2")
4211     time.sleep(0.1)
4212     send_ns(dev[2], target="aaaa:bbbb:eeee::2", ip_src="aaaa:bbbb:ff00::2")
4213     time.sleep(0.1)
4214
4215     # Try to probe for an already assigned address
4216     send_ns(dev[1], target="aaaa:bbbb:cccc::2", ip_src="::")
4217     time.sleep(0.1)
4218     send_ns(hapd, hapd_bssid=bssid, target="aaaa:bbbb:cccc::2", ip_src="::")
4219     time.sleep(0.1)
4220     send_ns(dev[2], target="aaaa:bbbb:cccc::2", ip_src="::")
4221     time.sleep(0.1)
4222
4223     # Unsolicited NA
4224     send_na(dev[1], target="aaaa:bbbb:cccc:aeae::3",
4225             ip_src="aaaa:bbbb:cccc:aeae::3", ip_dst="ff02::1")
4226     send_na(hapd, hapd_bssid=bssid, target="aaaa:bbbb:cccc:aeae::4",
4227             ip_src="aaaa:bbbb:cccc:aeae::4", ip_dst="ff02::1")
4228     send_na(dev[2], target="aaaa:bbbb:cccc:aeae::5",
4229             ip_src="aaaa:bbbb:cccc:aeae::5", ip_dst="ff02::1")
4230
4231     try:
4232         hwsim_utils.test_connectivity_iface(dev[0], hapd, "ap-br0")
4233     except Exception, e:
4234         logger.info("test_connectibity_iface failed: " + str(e))
4235         raise HwsimSkip("Assume kernel did not have the required patches for proxyarp")
4236     hwsim_utils.test_connectivity_iface(dev[1], hapd, "ap-br0")
4237     hwsim_utils.test_connectivity(dev[0], dev[1])
4238
4239     dev[0].request("DISCONNECT")
4240     dev[1].request("DISCONNECT")
4241     time.sleep(0.5)
4242     for i in range(len(cmd)):
4243         cmd[i].terminate()
4244     macs = get_bridge_macs("ap-br0")
4245     logger.info("After disconnect (showmacs): " + str(macs))
4246     matches = get_permanent_neighbors("ap-br0")
4247     logger.info("After disconnect: " + str(matches))
4248     if len(matches) > 0:
4249         raise Exception("Unexpected neighbor entries after disconnect")
4250     if ebtables:
4251         cmd = subprocess.Popen(['ebtables', '-L', '--Lc'],
4252                                stdout=subprocess.PIPE)
4253         res = cmd.stdout.read()
4254         cmd.stdout.close()
4255         logger.info("ebtables results:\n" + res)
4256
4257     # Verify that expected ARP messages were seen and no unexpected
4258     # ARP messages were seen.
4259
4260     arp_req = tshark_get_arp(cap_dev0, "arp.opcode == 1")
4261     arp_reply = tshark_get_arp(cap_dev0, "arp.opcode == 2")
4262     logger.info("dev0 seen ARP requests:\n" + str(arp_req))
4263     logger.info("dev0 seen ARP replies:\n" + str(arp_reply))
4264
4265     if [ 'ff:ff:ff:ff:ff:ff', addr1,
4266          addr1, '192.168.1.100',
4267          '00:00:00:00:00:00', '192.168.1.123' ] in arp_req:
4268         raise Exception("dev0 saw ARP request from dev1")
4269     if [ 'ff:ff:ff:ff:ff:ff', addr2,
4270          addr2, '192.168.1.103',
4271          '00:00:00:00:00:00', '192.168.1.123' ] in arp_req:
4272         raise Exception("dev0 saw ARP request from dev2")
4273     # TODO: Uncomment once fixed in kernel
4274     #if [ 'ff:ff:ff:ff:ff:ff', bssid,
4275     #     bssid, '192.168.1.101',
4276     #     '00:00:00:00:00:00', '192.168.1.123' ] in arp_req:
4277     #    raise Exception("dev0 saw ARP request from br")
4278
4279     if ebtables:
4280         for req in arp_req:
4281             if req[1] != addr0:
4282                 raise Exception("Unexpected foreign ARP request on dev0")
4283
4284     arp_req = tshark_get_arp(cap_dev1, "arp.opcode == 1")
4285     arp_reply = tshark_get_arp(cap_dev1, "arp.opcode == 2")
4286     logger.info("dev1 seen ARP requests:\n" + str(arp_req))
4287     logger.info("dev1 seen ARP replies:\n" + str(arp_reply))
4288
4289     if [ 'ff:ff:ff:ff:ff:ff', addr2,
4290          addr2, '192.168.1.103',
4291          '00:00:00:00:00:00', '192.168.1.123' ] in arp_req:
4292         raise Exception("dev1 saw ARP request from dev2")
4293     if [addr1, addr0, addr0, '192.168.1.123', addr1, '192.168.1.100'] not in arp_reply:
4294         raise Exception("dev1 did not get ARP response for 192.168.1.123")
4295
4296     if ebtables:
4297         for req in arp_req:
4298             if req[1] != addr1:
4299                 raise Exception("Unexpected foreign ARP request on dev1")
4300
4301     arp_req = tshark_get_arp(cap_dev2, "arp.opcode == 1")
4302     arp_reply = tshark_get_arp(cap_dev2, "arp.opcode == 2")
4303     logger.info("dev2 seen ARP requests:\n" + str(arp_req))
4304     logger.info("dev2 seen ARP replies:\n" + str(arp_reply))
4305
4306     if [ addr2, addr0,
4307          addr0, '192.168.1.123',
4308          addr2, '192.168.1.103' ] not in arp_reply:
4309         raise Exception("dev2 did not get ARP response for 192.168.1.123")
4310
4311     arp_req = tshark_get_arp(cap_br, "arp.opcode == 1")
4312     arp_reply = tshark_get_arp(cap_br, "arp.opcode == 2")
4313     logger.info("br seen ARP requests:\n" + str(arp_req))
4314     logger.info("br seen ARP replies:\n" + str(arp_reply))
4315
4316     # TODO: Uncomment once fixed in kernel
4317     #if [ bssid, addr0,
4318     #     addr0, '192.168.1.123',
4319     #     bssid, '192.168.1.101' ] not in arp_reply:
4320     #    raise Exception("br did not get ARP response for 192.168.1.123")
4321
4322     ns = tshark_get_ns(cap_dev0)
4323     logger.info("dev0 seen NS: " + str(ns))
4324     na = tshark_get_na(cap_dev0)
4325     logger.info("dev0 seen NA: " + str(na))
4326
4327     if [ addr0, addr1, 'aaaa:bbbb:dddd::2', 'aaaa:bbbb:cccc::2',
4328          'aaaa:bbbb:dddd::2', addr1 ] not in na:
4329         raise Exception("dev0 did not get NA for aaaa:bbbb:dddd::2")
4330
4331     if ebtables:
4332         for req in ns:
4333             if req[1] != addr0:
4334                 raise Exception("Unexpected foreign NS on dev0: " + str(req))
4335
4336     ns = tshark_get_ns(cap_dev1)
4337     logger.info("dev1 seen NS: " + str(ns))
4338     na = tshark_get_na(cap_dev1)
4339     logger.info("dev1 seen NA: " + str(na))
4340
4341     if [ addr1, addr0, 'aaaa:bbbb:cccc::2', 'aaaa:bbbb:dddd::2',
4342          'aaaa:bbbb:cccc::2', addr0 ] not in na:
4343         raise Exception("dev1 did not get NA for aaaa:bbbb:cccc::2")
4344
4345     if ebtables:
4346         for req in ns:
4347             if req[1] != addr1:
4348                 raise Exception("Unexpected foreign NS on dev1: " + str(req))
4349
4350     ns = tshark_get_ns(cap_dev2)
4351     logger.info("dev2 seen NS: " + str(ns))
4352     na = tshark_get_na(cap_dev2)
4353     logger.info("dev2 seen NA: " + str(na))
4354
4355     # FIX: enable once kernel implementation for proxyarp IPv6 is fixed
4356     #if [ addr2, addr0, 'aaaa:bbbb:cccc::2', 'aaaa:bbbb:ff00::2',
4357     #     'aaaa:bbbb:cccc::2', addr0 ] not in na:
4358     #    raise Exception("dev2 did not get NA for aaaa:bbbb:cccc::2")
4359     #if [ addr2, addr1, 'aaaa:bbbb:dddd::2', 'aaaa:bbbb:ff00::2',
4360     #     'aaaa:bbbb:dddd::2', addr1 ] not in na:
4361     #    raise Exception("dev2 did not get NA for aaaa:bbbb:dddd::2")
4362     #if [ addr2, addr1, 'aaaa:bbbb:eeee::2', 'aaaa:bbbb:ff00::2',
4363     #     'aaaa:bbbb:eeee::2', addr1 ] not in na:
4364     #    raise Exception("dev2 did not get NA for aaaa:bbbb:eeee::2")
4365
4366 def test_proxyarp_open(dev, apdev, params):
4367     """ProxyARP with open network"""
4368     try:
4369         _test_proxyarp_open(dev, apdev, params)
4370     finally:
4371         subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'down'],
4372                         stderr=open('/dev/null', 'w'))
4373         subprocess.call(['brctl', 'delbr', 'ap-br0'],
4374                         stderr=open('/dev/null', 'w'))
4375
4376 def test_proxyarp_open_ebtables(dev, apdev, params):
4377     """ProxyARP with open network"""
4378     try:
4379         _test_proxyarp_open(dev, apdev, params, ebtables=True)
4380     finally:
4381         try:
4382             subprocess.call(['ebtables', '-F', 'FORWARD'])
4383             subprocess.call(['ebtables', '-F', 'OUTPUT'])
4384         except:
4385             pass
4386         subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'down'],
4387                         stderr=open('/dev/null', 'w'))
4388         subprocess.call(['brctl', 'delbr', 'ap-br0'],
4389                         stderr=open('/dev/null', 'w'))
4390
4391 def test_ap_hs20_connect_deinit(dev, apdev):
4392     """Hotspot 2.0 connection interrupted with deinit"""
4393     check_eap_capa(dev[0], "MSCHAPV2")
4394     bssid = apdev[0]['bssid']
4395     params = hs20_ap_params()
4396     params['hessid'] = bssid
4397     hapd = hostapd.add_ap(apdev[0], params)
4398
4399     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
4400     wpas.interface_add("wlan5", drv_params="")
4401     wpas.hs20_enable()
4402     wpas.flush_scan_cache()
4403     wpas.add_cred_values({ 'realm': "example.com",
4404                            'username': "hs20-test",
4405                            'password': "password",
4406                            'ca_cert': "auth_serv/ca.pem",
4407                            'domain': "example.com" })
4408
4409     wpas.scan_for_bss(bssid, freq=2412)
4410     hapd.disable()
4411
4412     wpas.request("INTERWORKING_SELECT freq=2412")
4413
4414     id = wpas.request("RADIO_WORK add block-work")
4415     ev = wpas.wait_event(["GAS-QUERY-START", "EXT-RADIO-WORK-START"], timeout=5)
4416     if ev is None:
4417         raise Exception("Timeout while waiting radio work to start")
4418     ev = wpas.wait_event(["GAS-QUERY-START", "EXT-RADIO-WORK-START"], timeout=5)
4419     if ev is None:
4420         raise Exception("Timeout while waiting radio work to start (2)")
4421
4422     # Remove the interface while the gas-query radio work is still pending and
4423     # GAS query has not yet been started.
4424     wpas.interface_remove("wlan5")
4425
4426 def test_ap_hs20_anqp_format_errors(dev, apdev):
4427     """Interworking network selection and ANQP format errors"""
4428     bssid = apdev[0]['bssid']
4429     params = hs20_ap_params()
4430     params['hessid'] = bssid
4431     hapd = hostapd.add_ap(apdev[0], params)
4432
4433     dev[0].hs20_enable()
4434     values = { 'realm': "example.com",
4435                'ca_cert': "auth_serv/ca.pem",
4436                'username': "hs20-test",
4437                'password': "password",
4438                'domain': "example.com" }
4439     id = dev[0].add_cred_values(values)
4440
4441     dev[0].scan_for_bss(bssid, freq="2412")
4442
4443     tests = [ "00", "ffff", "010011223344", "020008000005112233445500",
4444               "01000400000000", "01000000000000",
4445               "01000300000200", "0100040000ff0000", "01000300000100",
4446               "01000300000001",
4447               "01000600000056112233",
4448               "01000900000002050001000111",
4449               "01000600000001000000", "01000600000001ff0000",
4450               "01000600000001020001",
4451               "010008000000010400010001", "0100080000000104000100ff",
4452               "010011000000010d00050200020100030005000600",
4453               "0000" ]
4454     for t in tests:
4455         hapd.set("anqp_elem", "263:" + t)
4456         dev[0].request("INTERWORKING_SELECT freq=2412")
4457         ev = dev[0].wait_event(["INTERWORKING-NO-MATCH"], timeout=5)
4458         if ev is None:
4459             raise Exception("Network selection timed out")
4460         dev[0].dump_monitor()
4461
4462     dev[0].remove_cred(id)
4463     id = dev[0].add_cred_values({ 'imsi': "555444-333222111", 'eap': "AKA",
4464                                   'milenage': "5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123"})
4465
4466     tests = [ "00", "0100", "0001", "00ff", "000200ff", "0003000101",
4467               "00020100" ]
4468     for t in tests:
4469         hapd.set("anqp_elem", "264:" + t)
4470         dev[0].request("INTERWORKING_SELECT freq=2412")
4471         ev = dev[0].wait_event(["INTERWORKING-NO-MATCH"], timeout=5)
4472         if ev is None:
4473             raise Exception("Network selection timed out")
4474         dev[0].dump_monitor()
4475
4476 def test_ap_hs20_cred_with_nai_realm(dev, apdev):
4477     """Hotspot 2.0 network selection and cred_with_nai_realm cred->realm"""
4478     bssid = apdev[0]['bssid']
4479     params = hs20_ap_params()
4480     params['hessid'] = bssid
4481     hostapd.add_ap(apdev[0], params)
4482
4483     dev[0].hs20_enable()
4484
4485     id = dev[0].add_cred_values({ 'realm': "example.com",
4486                                   'username': "test",
4487                                   'password': "secret",
4488                                   'domain': "example.com",
4489                                   'eap': 'TTLS' })
4490     interworking_select(dev[0], bssid, "home", freq=2412)
4491     dev[0].remove_cred(id)
4492
4493     id = dev[0].add_cred_values({ 'realm': "foo.com",
4494                                   'username': "test",
4495                                   'password': "secret",
4496                                   'domain': "example.com",
4497                                   'roaming_consortium': "112234",
4498                                   'eap': 'TTLS' })
4499     interworking_select(dev[0], bssid, "home", freq=2412, no_match=True)
4500     dev[0].remove_cred(id)
4501
4502 def test_ap_hs20_cred_and_no_roaming_consortium(dev, apdev):
4503     """Hotspot 2.0 network selection and no roaming consortium"""
4504     bssid = apdev[0]['bssid']
4505     params = hs20_ap_params()
4506     params['hessid'] = bssid
4507     del params['roaming_consortium']
4508     hostapd.add_ap(apdev[0], params)
4509
4510     dev[0].hs20_enable()
4511
4512     id = dev[0].add_cred_values({ 'realm': "example.com",
4513                                   'username': "test",
4514                                   'password': "secret",
4515                                   'domain': "example.com",
4516                                   'roaming_consortium': "112234",
4517                                   'eap': 'TTLS' })
4518     interworking_select(dev[0], bssid, "home", freq=2412, no_match=True)
4519
4520 def test_ap_hs20_interworking_oom(dev, apdev):
4521     """Hotspot 2.0 network selection and OOM"""
4522     bssid = apdev[0]['bssid']
4523     params = hs20_ap_params()
4524     params['hessid'] = bssid
4525     params['nai_realm'] = [ "0,no.match.here;example.com;no.match.here.either,21[2:1][5:7]",
4526                             "0,example.com,13[5:6],21[2:4][5:7]",
4527                             "0,another.example.com" ]
4528     hostapd.add_ap(apdev[0], params)
4529
4530     dev[0].hs20_enable()
4531
4532     id = dev[0].add_cred_values({ 'realm': "example.com",
4533                                   'username': "test",
4534                                   'password': "secret",
4535                                   'domain': "example.com",
4536                                   'eap': 'TTLS' })
4537
4538     dev[0].scan_for_bss(bssid, freq="2412")
4539
4540     funcs = [ "wpabuf_alloc;interworking_anqp_send_req",
4541               "anqp_build_req;interworking_anqp_send_req",
4542               "gas_query_req;interworking_anqp_send_req",
4543               "dup_binstr;nai_realm_parse_realm",
4544               "=nai_realm_parse_realm",
4545               "=nai_realm_parse",
4546               "=nai_realm_match" ]
4547     for func in funcs:
4548         with alloc_fail(dev[0], 1, func):
4549             dev[0].request("INTERWORKING_SELECT auto freq=2412")
4550             ev = dev[0].wait_event(["Starting ANQP"], timeout=5)
4551             if ev is None:
4552                 raise Exception("ANQP did not start")
4553             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4554
4555 def test_ap_hs20_no_cred_connect(dev, apdev):
4556     """Hotspot 2.0 and connect attempt without credential"""
4557     bssid = apdev[0]['bssid']
4558     params = hs20_ap_params()
4559     params['hessid'] = bssid
4560     hapd = hostapd.add_ap(apdev[0], params)
4561
4562     dev[0].hs20_enable()
4563     dev[0].scan_for_bss(bssid, freq="2412")
4564     if "FAIL" not in dev[0].request("INTERWORKING_CONNECT " + bssid):
4565         raise Exception("Unexpected INTERWORKING_CONNECT success")
4566
4567 def test_ap_hs20_no_rsn_connect(dev, apdev):
4568     """Hotspot 2.0 and connect attempt without RSN"""
4569     bssid = apdev[0]['bssid']
4570     params = hostapd.wpa_params(ssid="test-hs20")
4571     params['wpa_key_mgmt'] = "WPA-EAP"
4572     params['ieee80211w'] = "1"
4573     params['ieee8021x'] = "1"
4574     params['auth_server_addr'] = "127.0.0.1"
4575     params['auth_server_port'] = "1812"
4576     params['auth_server_shared_secret'] = "radius"
4577     params['interworking'] = "1"
4578     params['roaming_consortium'] = [ "112233", "1020304050", "010203040506",
4579                                      "fedcba" ]
4580     params['nai_realm'] = [ "0,example.com,13[5:6],21[2:4][5:7]",
4581                             "0,another.example.com" ]
4582     hapd = hostapd.add_ap(apdev[0], params)
4583
4584     dev[0].hs20_enable()
4585     dev[0].scan_for_bss(bssid, freq="2412")
4586
4587     id = dev[0].add_cred_values({ 'realm': "example.com",
4588                                   'username': "test",
4589                                   'password': "secret",
4590                                   'domain': "example.com",
4591                                   'roaming_consortium': "112233",
4592                                   'eap': 'TTLS' })
4593
4594     interworking_select(dev[0], bssid, freq=2412, no_match=True)
4595     if "FAIL" not in dev[0].request("INTERWORKING_CONNECT " + bssid):
4596         raise Exception("Unexpected INTERWORKING_CONNECT success")
4597
4598 def test_ap_hs20_no_match_connect(dev, apdev):
4599     """Hotspot 2.0 and connect attempt without matching cred"""
4600     bssid = apdev[0]['bssid']
4601     params = hs20_ap_params()
4602     hapd = hostapd.add_ap(apdev[0], params)
4603
4604     dev[0].hs20_enable()
4605     dev[0].scan_for_bss(bssid, freq="2412")
4606
4607     id = dev[0].add_cred_values({ 'realm': "example.org",
4608                                   'username': "test",
4609                                   'password': "secret",
4610                                   'domain': "example.org",
4611                                   'roaming_consortium': "112234",
4612                                   'eap': 'TTLS' })
4613
4614     interworking_select(dev[0], bssid, freq=2412, no_match=True)
4615     if "FAIL" not in dev[0].request("INTERWORKING_CONNECT " + bssid):
4616         raise Exception("Unexpected INTERWORKING_CONNECT success")
4617
4618 def test_ap_hs20_multiple_home_cred(dev, apdev):
4619     """Hotspot 2.0 and select with multiple matching home credentials"""
4620     bssid = apdev[0]['bssid']
4621     params = hs20_ap_params()
4622     params['hessid'] = bssid
4623     params['nai_realm'] = [ "0,example.com,13[5:6],21[2:4][5:7]" ]
4624     params['domain_name'] = "example.com"
4625     hapd = hostapd.add_ap(apdev[0], params)
4626
4627     bssid2 = apdev[1]['bssid']
4628     params = hs20_ap_params(ssid="test-hs20-other")
4629     params['hessid'] = bssid2
4630     params['nai_realm'] = [ "0,example.org,13[5:6],21[2:4][5:7]" ]
4631     params['domain_name'] = "example.org"
4632     hapd2 = hostapd.add_ap(apdev[1], params)
4633
4634     dev[0].hs20_enable()
4635     dev[0].scan_for_bss(bssid2, freq="2412")
4636     dev[0].scan_for_bss(bssid, freq="2412")
4637     id = dev[0].add_cred_values({ 'realm': "example.com",
4638                                   'priority': '2',
4639                                   'username': "hs20-test",
4640                                   'password': "password",
4641                                   'domain': "example.com" })
4642     id2 = dev[0].add_cred_values({ 'realm': "example.org",
4643                                    'priority': '3',
4644                                    'username': "hs20-test",
4645                                    'password': "password",
4646                                    'domain': "example.org" })
4647     dev[0].request("INTERWORKING_SELECT auto freq=2412")
4648     ev = dev[0].wait_connected(timeout=15)
4649     if bssid2 not in ev:
4650         raise Exception("Connected to incorrect network")
4651
4652 def test_ap_hs20_anqp_invalid_gas_response(dev, apdev):
4653     """Hotspot 2.0 network selection and invalid GAS response"""
4654     bssid = apdev[0]['bssid']
4655     params = hs20_ap_params()
4656     params['hessid'] = bssid
4657     hapd = hostapd.add_ap(apdev[0], params)
4658
4659     dev[0].scan_for_bss(bssid, freq="2412")
4660     hapd.set("ext_mgmt_frame_handling", "1")
4661
4662     dev[0].hs20_enable()
4663
4664     id = dev[0].add_cred_values({ 'realm': "example.com",
4665                                   'username': "test",
4666                                   'password': "secret",
4667                                   'domain': "example.com",
4668                                   'roaming_consortium': "112234",
4669                                   'eap': 'TTLS' })
4670     dev[0].request("INTERWORKING_SELECT freq=2412")
4671
4672     query = gas_rx(hapd)
4673     gas = parse_gas(query['payload'])
4674
4675     logger.info("ANQP: Unexpected Advertisement Protocol in response")
4676     resp = action_response(query)
4677     adv_proto = struct.pack('8B', 108, 6, 127, 0xdd, 0x00, 0x11, 0x22, 0x33)
4678     data = struct.pack('<H', 0)
4679     resp['payload'] = struct.pack('<BBBHH', ACTION_CATEG_PUBLIC,
4680                                   GAS_INITIAL_RESPONSE,
4681                                   gas['dialog_token'], 0, 0) + adv_proto + data
4682     send_gas_resp(hapd, resp)
4683
4684     ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=5)
4685     if ev is None:
4686         raise Exception("No ANQP-QUERY-DONE seen")
4687     if "result=INVALID_FRAME" not in ev:
4688         raise Exception("Unexpected result: " + ev)
4689
4690     dev[0].request("INTERWORKING_SELECT freq=2412")
4691
4692     query = gas_rx(hapd)
4693     gas = parse_gas(query['payload'])
4694
4695     logger.info("ANQP: Invalid element length for Info ID 1234")
4696     resp = action_response(query)
4697     adv_proto = struct.pack('BBBB', 108, 2, 127, 0)
4698     elements = struct.pack('<HH', 1234, 1)
4699     data = struct.pack('<H', len(elements)) + elements
4700     resp['payload'] = struct.pack('<BBBHH', ACTION_CATEG_PUBLIC,
4701                                   GAS_INITIAL_RESPONSE,
4702                                   gas['dialog_token'], 0, 0) + adv_proto + data
4703     send_gas_resp(hapd, resp)
4704
4705     ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=5)
4706     if ev is None:
4707         raise Exception("No ANQP-QUERY-DONE seen")
4708     if "result=INVALID_FRAME" not in ev:
4709         raise Exception("Unexpected result: " + ev)
4710
4711     with alloc_fail(dev[0], 1, "=anqp_add_extra"):
4712         dev[0].request("INTERWORKING_SELECT freq=2412")
4713
4714         query = gas_rx(hapd)
4715         gas = parse_gas(query['payload'])
4716
4717         resp = action_response(query)
4718         elements = struct.pack('<HHHH', 1, 0, 1, 0)
4719         data = struct.pack('<H', len(elements)) + elements
4720         resp['payload'] = struct.pack('<BBBHH', ACTION_CATEG_PUBLIC,
4721                                       GAS_INITIAL_RESPONSE,
4722                                       gas['dialog_token'], 0, 0) + adv_proto + data
4723         send_gas_resp(hapd, resp)
4724
4725         ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=5)
4726         if ev is None:
4727             raise Exception("No ANQP-QUERY-DONE seen")
4728         if "result=SUCCESS" not in ev:
4729             raise Exception("Unexpected result: " + ev)
4730
4731     with alloc_fail(dev[0], 1, "wpabuf_alloc_copy;anqp_add_extra"):
4732         dev[0].request("INTERWORKING_SELECT freq=2412")
4733
4734         query = gas_rx(hapd)
4735         gas = parse_gas(query['payload'])
4736
4737         resp = action_response(query)
4738         elements = struct.pack('<HHHH', 1, 0, 1, 0)
4739         data = struct.pack('<H', len(elements)) + elements
4740         resp['payload'] = struct.pack('<BBBHH', ACTION_CATEG_PUBLIC,
4741                                       GAS_INITIAL_RESPONSE,
4742                                       gas['dialog_token'], 0, 0) + adv_proto + data
4743         send_gas_resp(hapd, resp)
4744
4745         ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=5)
4746         if ev is None:
4747             raise Exception("No ANQP-QUERY-DONE seen")
4748         if "result=SUCCESS" not in ev:
4749             raise Exception("Unexpected result: " + ev)
4750
4751     tests = [ struct.pack('<HH', 0xdddd, 0),
4752               struct.pack('<HH3B', 0xdddd, 3, 0x50, 0x6f, 0x9a),
4753               struct.pack('<HH4B', 0xdddd, 4, 0x50, 0x6f, 0x9a, 0),
4754               struct.pack('<HH4B', 0xdddd, 4, 0x11, 0x22, 0x33, 0),
4755               struct.pack('<HHHH', 1, 0, 1, 0) ]
4756     for elements in tests:
4757         dev[0].request("INTERWORKING_SELECT freq=2412")
4758
4759         query = gas_rx(hapd)
4760         gas = parse_gas(query['payload'])
4761
4762         resp = action_response(query)
4763         data = struct.pack('<H', len(elements)) + elements
4764         resp['payload'] = struct.pack('<BBBHH', ACTION_CATEG_PUBLIC,
4765                                       GAS_INITIAL_RESPONSE,
4766                                       gas['dialog_token'], 0, 0) + adv_proto + data
4767         send_gas_resp(hapd, resp)
4768
4769         ev = dev[0].wait_event(["ANQP-QUERY-DONE"], timeout=5)
4770         if ev is None:
4771             raise Exception("No ANQP-QUERY-DONE seen")
4772         if "result=SUCCESS" not in ev:
4773             raise Exception("Unexpected result: " + ev)
4774
4775 def test_ap_hs20_set_profile_failures(dev, apdev):
4776     """Hotspot 2.0 and failures during profile configuration"""
4777     bssid = apdev[0]['bssid']
4778     params = hs20_ap_params()
4779     params['hessid'] = bssid
4780     params['anqp_3gpp_cell_net'] = "555,444"
4781     hapd = hostapd.add_ap(apdev[0], params)
4782
4783     dev[0].hs20_enable()
4784     dev[0].scan_for_bss(bssid, freq="2412")
4785
4786     id = dev[0].add_cred_values({ 'realm': "example.com",
4787                                   'domain': "example.com",
4788                                   'username': "test",
4789                                   'password': "secret",
4790                                   'eap': 'TTLS' })
4791     interworking_select(dev[0], bssid, "home", freq=2412)
4792     dev[0].dump_monitor()
4793     dev[0].request("NOTE ssid->eap.eap_methods = os_malloc()")
4794     with alloc_fail(dev[0], 1, "interworking_set_eap_params"):
4795         dev[0].request("INTERWORKING_CONNECT " + bssid)
4796         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4797     dev[0].remove_cred(id)
4798
4799     id = dev[0].add_cred_values({ 'realm': "example.com",
4800                                   'domain': "example.com",
4801                                   'username': "hs20-test-with-domain@example.com",
4802                                   'password': "password" })
4803     interworking_select(dev[0], bssid, "home", freq=2412)
4804     dev[0].dump_monitor()
4805     dev[0].request("NOTE anon = os_malloc()")
4806     with alloc_fail(dev[0], 1, "interworking_set_eap_params"):
4807         dev[0].request("INTERWORKING_CONNECT " + bssid)
4808         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4809     dev[0].request("NOTE Successful connection with cred->username including realm")
4810     dev[0].request("INTERWORKING_CONNECT " + bssid)
4811     dev[0].wait_connected()
4812     dev[0].remove_cred(id)
4813     dev[0].wait_disconnected()
4814
4815     id = dev[0].add_cred_values({ 'realm': "example.com",
4816                                   'domain': "example.com",
4817                                   'username': "hs20-test",
4818                                   'password': "password" })
4819     interworking_select(dev[0], bssid, "home", freq=2412)
4820     dev[0].dump_monitor()
4821     dev[0].request("NOTE anon = os_malloc() (second)")
4822     with alloc_fail(dev[0], 1, "interworking_set_eap_params"):
4823         dev[0].request("INTERWORKING_CONNECT " + bssid)
4824         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4825     with alloc_fail(dev[0], 1, "wpa_config_add_network;interworking_connect"):
4826         dev[0].request("INTERWORKING_CONNECT " + bssid)
4827         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4828     with alloc_fail(dev[0], 1, "=interworking_connect"):
4829         dev[0].request("INTERWORKING_CONNECT " + bssid)
4830         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4831     dev[0].request("NOTE wpa_config_set(eap)")
4832     with alloc_fail(dev[0], 1, "wpa_config_parse_eap;wpa_config_set;interworking_connect"):
4833         dev[0].request("INTERWORKING_CONNECT " + bssid)
4834         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4835     dev[0].request("NOTE wpa_config_set(TTLS-NON_EAP_MSCHAPV2-phase2)")
4836     with alloc_fail(dev[0], 1, "wpa_config_parse_str;wpa_config_set;interworking_connect"):
4837         dev[0].request("INTERWORKING_CONNECT " + bssid)
4838         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4839     dev[0].remove_cred(id)
4840
4841     id = dev[0].add_cred_values({ 'roaming_consortium': "112233",
4842                                   'domain': "example.com",
4843                                   'username': "hs20-test",
4844                                   'password': "password",
4845                                   'eap': 'TTLS',
4846                                   'phase2': "auth=MSCHAPV2" })
4847     interworking_select(dev[0], bssid, "home", freq=2412)
4848     dev[0].dump_monitor()
4849     dev[0].request("NOTE anon = os_strdup()")
4850     with alloc_fail(dev[0], 2, "interworking_set_eap_params"):
4851         dev[0].request("INTERWORKING_CONNECT " + bssid)
4852         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4853     dev[0].request("NOTE wpa_config_set_quoted(anonymous_identity)")
4854     with alloc_fail(dev[0], 1, "=wpa_config_set_quoted;interworking_set_eap_params"):
4855         dev[0].request("INTERWORKING_CONNECT " + bssid)
4856         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4857     dev[0].request("NOTE Successful connection with cred->realm not included")
4858     dev[0].request("INTERWORKING_CONNECT " + bssid)
4859     dev[0].wait_connected()
4860     dev[0].remove_cred(id)
4861     dev[0].wait_disconnected()
4862
4863     id = dev[0].add_cred_values({ 'roaming_consortium': "112233",
4864                                   'domain': "example.com",
4865                                   'realm': "example.com",
4866                                   'username': "user",
4867                                   'password': "password",
4868                                   'eap': 'PEAP' })
4869     interworking_select(dev[0], bssid, "home", freq=2412)
4870     dev[0].dump_monitor()
4871     dev[0].request("NOTE id = os_strdup()")
4872     with alloc_fail(dev[0], 2, "interworking_set_eap_params"):
4873         dev[0].request("INTERWORKING_CONNECT " + bssid)
4874         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4875     dev[0].request("NOTE wpa_config_set_quoted(identity)")
4876     with alloc_fail(dev[0], 1, "=wpa_config_set_quoted;interworking_set_eap_params"):
4877         dev[0].request("INTERWORKING_CONNECT " + bssid)
4878         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4879     dev[0].remove_cred(id)
4880
4881     id = dev[0].add_cred_values({ 'roaming_consortium': "112233",
4882                                   'domain': "example.com",
4883                                   'realm': "example.com",
4884                                   'username': "user",
4885                                   'password': "password",
4886                                   'eap': "TTLS" })
4887     interworking_select(dev[0], bssid, "home", freq=2412)
4888     dev[0].dump_monitor()
4889     dev[0].request("NOTE wpa_config_set_quoted(identity) (second)")
4890     with alloc_fail(dev[0], 2, "=wpa_config_set_quoted;interworking_set_eap_params"):
4891         dev[0].request("INTERWORKING_CONNECT " + bssid)
4892         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4893     dev[0].request("NOTE wpa_config_set_quoted(password)")
4894     with alloc_fail(dev[0], 3, "=wpa_config_set_quoted;interworking_set_eap_params"):
4895         dev[0].request("INTERWORKING_CONNECT " + bssid)
4896         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4897     with alloc_fail(dev[0], 1, "wpa_config_add_network;interworking_connect_roaming_consortium"):
4898         dev[0].request("INTERWORKING_CONNECT " + bssid)
4899         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4900     with alloc_fail(dev[0], 1, "=interworking_connect_roaming_consortium"):
4901         dev[0].request("INTERWORKING_CONNECT " + bssid)
4902         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4903     dev[0].remove_cred(id)
4904
4905     id = dev[0].add_cred_values({ 'roaming_consortium': "112233",
4906                                   'domain': "example.com",
4907                                   'realm': "example.com",
4908                                   'username': "user",
4909                                   'eap': "PEAP" })
4910     dev[0].set_cred(id, "password", "ext:password");
4911     interworking_select(dev[0], bssid, "home", freq=2412)
4912     dev[0].dump_monitor()
4913     dev[0].request("NOTE wpa_config_set(password)")
4914     with alloc_fail(dev[0], 3, "wpa_config_set;interworking_set_eap_params"):
4915         dev[0].request("INTERWORKING_CONNECT " + bssid)
4916         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4917     with alloc_fail(dev[0], 1, "interworking_set_hs20_params"):
4918         dev[0].request("INTERWORKING_CONNECT " + bssid)
4919         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4920     dev[0].remove_cred(id)
4921
4922     id = dev[0].add_cred_values({ 'realm': "example.com",
4923                                   'domain': "example.com",
4924                                   'username': "certificate-user",
4925                                   'phase1': "include_tls_length=0",
4926                                   'domain_suffix_match': "example.com",
4927                                   'ca_cert': "auth_serv/ca.pem",
4928                                   'client_cert': "auth_serv/user.pem",
4929                                   'private_key': "auth_serv/user.key",
4930                                   'private_key_passwd': "secret" })
4931     interworking_select(dev[0], bssid, "home", freq=2412)
4932     dev[0].dump_monitor()
4933     dev[0].request("NOTE wpa_config_set_quoted(client_cert)")
4934     with alloc_fail(dev[0], 2, "=wpa_config_set_quoted;interworking_set_eap_params"):
4935         dev[0].request("INTERWORKING_CONNECT " + bssid)
4936         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4937     dev[0].request("NOTE wpa_config_set_quoted(private_key)")
4938     with alloc_fail(dev[0], 3, "=wpa_config_set_quoted;interworking_set_eap_params"):
4939         dev[0].request("INTERWORKING_CONNECT " + bssid)
4940         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4941     dev[0].request("NOTE wpa_config_set_quoted(private_key_passwd)")
4942     with alloc_fail(dev[0], 4, "=wpa_config_set_quoted;interworking_set_eap_params"):
4943         dev[0].request("INTERWORKING_CONNECT " + bssid)
4944         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4945     dev[0].request("NOTE wpa_config_set_quoted(ca_cert)")
4946     with alloc_fail(dev[0], 5, "=wpa_config_set_quoted;interworking_set_eap_params"):
4947         dev[0].request("INTERWORKING_CONNECT " + bssid)
4948         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4949     dev[0].request("NOTE wpa_config_set_quoted(domain_suffix_match)")
4950     with alloc_fail(dev[0], 6, "=wpa_config_set_quoted;interworking_set_eap_params"):
4951         dev[0].request("INTERWORKING_CONNECT " + bssid)
4952         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4953     with alloc_fail(dev[0], 1, "interworking_set_hs20_params"):
4954         dev[0].request("INTERWORKING_CONNECT " + bssid)
4955         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4956     dev[0].remove_cred(id)
4957
4958     id = dev[0].add_cred_values({ 'imsi': "555444-333222111", 'eap': "SIM",
4959                                   'milenage': "5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123"})
4960     interworking_select(dev[0], bssid, freq=2412)
4961     dev[0].dump_monitor()
4962     with alloc_fail(dev[0], 1, "interworking_set_hs20_params"):
4963         dev[0].request("INTERWORKING_CONNECT " + bssid)
4964         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4965     dev[0].request("NOTE wpa_config_set_quoted(password;milenage)")
4966     with alloc_fail(dev[0], 2, "=wpa_config_set_quoted;interworking_connect_3gpp"):
4967         dev[0].request("INTERWORKING_CONNECT " + bssid)
4968         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4969     dev[0].request("NOTE wpa_config_set(eap)")
4970     with alloc_fail(dev[0], 1, "wpa_config_parse_eap;wpa_config_set;interworking_connect_3gpp"):
4971         dev[0].request("INTERWORKING_CONNECT " + bssid)
4972         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4973     dev[0].request("NOTE set_root_nai:wpa_config_set(identity)")
4974     with alloc_fail(dev[0], 1, "wpa_config_parse_str;interworking_connect_3gpp"):
4975             dev[0].request("INTERWORKING_CONNECT " + bssid)
4976             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4977     dev[0].remove_cred(id)
4978
4979     id = dev[0].add_cred_values({ 'roaming_consortium': "112233",
4980                                   'username': "user@example.com",
4981                                   'password': "password" })
4982     interworking_select(dev[0], bssid, freq=2412)
4983     dev[0].dump_monitor()
4984     dev[0].request("NOTE Interworking: No EAP method set for credential using roaming consortium")
4985     dev[0].request("INTERWORKING_CONNECT " + bssid)
4986     dev[0].remove_cred(id)
4987
4988     hapd.disable()
4989     params = hs20_ap_params()
4990     params['nai_realm'] = "0,example.com,25[3:26]"
4991     hapd = hostapd.add_ap(apdev[0], params)
4992     id = dev[0].add_cred_values({ 'realm': "example.com",
4993                                   'domain': "example.com",
4994                                   'username': "hs20-test",
4995                                   'password': "password" })
4996     interworking_select(dev[0], bssid, freq=2412)
4997     dev[0].dump_monitor()
4998     dev[0].request("NOTE wpa_config_set(PEAP/FAST-phase1)")
4999     with alloc_fail(dev[0], 1, "wpa_config_parse_str;wpa_config_set;interworking_connect"):
5000         dev[0].request("INTERWORKING_CONNECT " + bssid)
5001         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5002     dev[0].request("NOTE wpa_config_set(PEAP/FAST-pac_interworking)")
5003     with alloc_fail(dev[0], 2, "wpa_config_parse_str;wpa_config_set;interworking_connect"):
5004         dev[0].request("INTERWORKING_CONNECT " + bssid)
5005         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5006     dev[0].request("NOTE wpa_config_set(PEAP/FAST-phase2)")
5007     with alloc_fail(dev[0], 3, "wpa_config_parse_str;wpa_config_set;interworking_connect"):
5008         dev[0].request("INTERWORKING_CONNECT " + bssid)
5009         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5010
5011     hapd.disable()
5012     params = hs20_ap_params()
5013     params['nai_realm'] = "0,example.com,21"
5014     hapd = hostapd.add_ap(apdev[0], params)
5015     interworking_select(dev[0], bssid, freq=2412)
5016     dev[0].request("NOTE wpa_config_set(TTLS-defaults-phase2)")
5017     with alloc_fail(dev[0], 1, "wpa_config_parse_str;wpa_config_set;interworking_connect"):
5018         dev[0].request("INTERWORKING_CONNECT " + bssid)
5019         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5020
5021     hapd.disable()
5022     params = hs20_ap_params()
5023     params['nai_realm'] = "0,example.com,21[2:3]"
5024     hapd = hostapd.add_ap(apdev[0], params)
5025     interworking_select(dev[0], bssid, freq=2412)
5026     dev[0].request("NOTE wpa_config_set(TTLS-NON_EAP_MSCHAP-phase2)")
5027     with alloc_fail(dev[0], 1, "wpa_config_parse_str;wpa_config_set;interworking_connect"):
5028         dev[0].request("INTERWORKING_CONNECT " + bssid)
5029         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5030
5031     hapd.disable()
5032     params = hs20_ap_params()
5033     params['nai_realm'] = "0,example.com,21[2:2]"
5034     hapd = hostapd.add_ap(apdev[0], params)
5035     interworking_select(dev[0], bssid, freq=2412)
5036     dev[0].request("NOTE wpa_config_set(TTLS-NON_EAP_CHAP-phase2)")
5037     with alloc_fail(dev[0], 1, "wpa_config_parse_str;wpa_config_set;interworking_connect"):
5038         dev[0].request("INTERWORKING_CONNECT " + bssid)
5039         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5040
5041     hapd.disable()
5042     params = hs20_ap_params()
5043     params['nai_realm'] = "0,example.com,21[2:1]"
5044     hapd = hostapd.add_ap(apdev[0], params)
5045     interworking_select(dev[0], bssid, freq=2412)
5046     dev[0].request("NOTE wpa_config_set(TTLS-NON_EAP_PAP-phase2)")
5047     with alloc_fail(dev[0], 1, "wpa_config_parse_str;wpa_config_set;interworking_connect"):
5048         dev[0].request("INTERWORKING_CONNECT " + bssid)
5049         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5050
5051     hapd.disable()
5052     params = hs20_ap_params()
5053     params['nai_realm'] = "0,example.com,21[3:26]"
5054     hapd = hostapd.add_ap(apdev[0], params)
5055     interworking_select(dev[0], bssid, freq=2412)
5056     dev[0].request("NOTE wpa_config_set(TTLS-EAP-MSCHAPV2-phase2)")
5057     with alloc_fail(dev[0], 1, "wpa_config_parse_str;wpa_config_set;interworking_connect"):
5058         dev[0].request("INTERWORKING_CONNECT " + bssid)
5059         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5060
5061     dev[0].remove_cred(id)