tests: Use hapd from hostapd.add_ap() in eap_connect()
[mech_eap.git] / tests / hwsim / test_pmksa_cache.py
1 # WPA2-Enterprise PMKSA caching tests
2 # Copyright (c) 2013-2014, 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 import logging
8 logger = logging.getLogger()
9 import subprocess
10 import time
11
12 import hostapd
13 import hwsim_utils
14 from wpasupplicant import WpaSupplicant
15 from utils import alloc_fail
16 from test_ap_eap import eap_connect
17
18 def test_pmksa_cache_on_roam_back(dev, apdev):
19     """PMKSA cache to skip EAP on reassociation back to same AP"""
20     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
21     hostapd.add_ap(apdev[0], params)
22     bssid = apdev[0]['bssid']
23     dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
24                    eap="GPSK", identity="gpsk user",
25                    password="abcdefghijklmnop0123456789abcdef",
26                    scan_freq="2412")
27     pmksa = dev[0].get_pmksa(bssid)
28     if pmksa is None:
29         raise Exception("No PMKSA cache entry created")
30     if pmksa['opportunistic'] != '0':
31         raise Exception("Unexpected opportunistic PMKSA cache entry")
32
33     hostapd.add_ap(apdev[1], params)
34     bssid2 = apdev[1]['bssid']
35
36     dev[0].dump_monitor()
37     logger.info("Roam to AP2")
38     # It can take some time for the second AP to become ready to reply to Probe
39     # Request frames especially under heavy CPU load, so allow couple of rounds
40     # of scanning to avoid reporting errors incorrectly just because of scans
41     # not having seen the target AP.
42     for i in range(0, 10):
43         dev[0].scan(freq="2412")
44         if dev[0].get_bss(bssid2) is not None:
45             break
46         logger.info("Scan again to find target AP")
47     dev[0].request("ROAM " + bssid2)
48     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
49     if ev is None:
50         raise Exception("EAP success timed out")
51     dev[0].wait_connected(timeout=10, error="Roaming timed out")
52     pmksa2 = dev[0].get_pmksa(bssid2)
53     if pmksa2 is None:
54         raise Exception("No PMKSA cache entry found")
55     if pmksa2['opportunistic'] != '0':
56         raise Exception("Unexpected opportunistic PMKSA cache entry")
57
58     dev[0].dump_monitor()
59     logger.info("Roam back to AP1")
60     dev[0].scan(freq="2412")
61     dev[0].request("ROAM " + bssid)
62     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED",
63                             "CTRL-EVENT-CONNECTED"], timeout=10)
64     if ev is None:
65         raise Exception("Roaming with the AP timed out")
66     if "CTRL-EVENT-EAP-STARTED" in ev:
67         raise Exception("Unexpected EAP exchange")
68     pmksa1b = dev[0].get_pmksa(bssid)
69     if pmksa1b is None:
70         raise Exception("No PMKSA cache entry found")
71     if pmksa['pmkid'] != pmksa1b['pmkid']:
72         raise Exception("Unexpected PMKID change for AP1")
73
74     dev[0].dump_monitor()
75     if "FAIL" in dev[0].request("PMKSA_FLUSH"):
76         raise Exception("PMKSA_FLUSH failed")
77     if dev[0].get_pmksa(bssid) is not None or dev[0].get_pmksa(bssid2) is not None:
78         raise Exception("PMKSA_FLUSH did not remove PMKSA entries")
79     dev[0].wait_disconnected(timeout=5)
80     dev[0].wait_connected(timeout=15, error="Reconnection timed out")
81
82 def test_pmksa_cache_and_reauth(dev, apdev):
83     """PMKSA caching and EAPOL reauthentication"""
84     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
85     hapd = hostapd.add_ap(apdev[0], params)
86     bssid = apdev[0]['bssid']
87     dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
88                    eap="GPSK", identity="gpsk user",
89                    password="abcdefghijklmnop0123456789abcdef",
90                    scan_freq="2412")
91
92     hostapd.add_ap(apdev[1], params)
93     bssid2 = apdev[1]['bssid']
94
95     dev[0].dump_monitor()
96     logger.info("Roam to AP2")
97     # It can take some time for the second AP to become ready to reply to Probe
98     # Request frames especially under heavy CPU load, so allow couple of rounds
99     # of scanning to avoid reporting errors incorrectly just because of scans
100     # not having seen the target AP.
101     for i in range(0, 10):
102         dev[0].scan(freq="2412")
103         if dev[0].get_bss(bssid2) is not None:
104             break
105         logger.info("Scan again to find target AP")
106     dev[0].request("ROAM " + bssid2)
107     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
108     if ev is None:
109         raise Exception("EAP success timed out")
110     dev[0].wait_connected(timeout=10, error="Roaming timed out")
111
112     dev[0].dump_monitor()
113     logger.info("Roam back to AP1")
114     dev[0].scan(freq="2412")
115     dev[0].request("ROAM " + bssid)
116     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED",
117                             "CTRL-EVENT-CONNECTED"], timeout=10)
118     if ev is None:
119         raise Exception("Roaming with the AP timed out")
120     if "CTRL-EVENT-EAP-STARTED" in ev:
121         raise Exception("Unexpected EAP exchange")
122
123     # Verify EAPOL reauthentication after PMKSA caching
124     hapd.request("EAPOL_REAUTH " + dev[0].own_addr())
125     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=5)
126     if ev is None:
127         raise Exception("EAP authentication did not start")
128     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=5)
129     if ev is None:
130         raise Exception("EAP authentication did not succeed")
131
132 def test_pmksa_cache_opportunistic_only_on_sta(dev, apdev):
133     """Opportunistic PMKSA caching enabled only on station"""
134     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
135     hostapd.add_ap(apdev[0], params)
136     bssid = apdev[0]['bssid']
137     dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
138                    eap="GPSK", identity="gpsk user",
139                    password="abcdefghijklmnop0123456789abcdef", okc=True,
140                    scan_freq="2412")
141     pmksa = dev[0].get_pmksa(bssid)
142     if pmksa is None:
143         raise Exception("No PMKSA cache entry created")
144     if pmksa['opportunistic'] != '0':
145         raise Exception("Unexpected opportunistic PMKSA cache entry")
146
147     hostapd.add_ap(apdev[1], params)
148     bssid2 = apdev[1]['bssid']
149
150     dev[0].dump_monitor()
151     logger.info("Roam to AP2")
152     dev[0].scan(freq="2412")
153     dev[0].request("ROAM " + bssid2)
154     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
155     if ev is None:
156         raise Exception("EAP success timed out")
157     dev[0].wait_connected(timeout=10, error="Roaming timed out")
158     pmksa2 = dev[0].get_pmksa(bssid2)
159     if pmksa2 is None:
160         raise Exception("No PMKSA cache entry found")
161     if pmksa2['opportunistic'] != '0':
162         raise Exception("Unexpected opportunistic PMKSA cache entry")
163
164     dev[0].dump_monitor()
165     logger.info("Roam back to AP1")
166     dev[0].scan(freq="2412")
167     dev[0].request("ROAM " + bssid)
168     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED",
169                             "CTRL-EVENT-CONNECTED"], timeout=10)
170     if ev is None:
171         raise Exception("Roaming with the AP timed out")
172     if "CTRL-EVENT-EAP-STARTED" in ev:
173         raise Exception("Unexpected EAP exchange")
174     pmksa1b = dev[0].get_pmksa(bssid)
175     if pmksa1b is None:
176         raise Exception("No PMKSA cache entry found")
177     if pmksa['pmkid'] != pmksa1b['pmkid']:
178         raise Exception("Unexpected PMKID change for AP1")
179
180 def test_pmksa_cache_opportunistic(dev, apdev):
181     """Opportunistic PMKSA caching"""
182     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
183     params['okc'] = "1"
184     hostapd.add_ap(apdev[0], params)
185     bssid = apdev[0]['bssid']
186     dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
187                    eap="GPSK", identity="gpsk user",
188                    password="abcdefghijklmnop0123456789abcdef", okc=True,
189                    scan_freq="2412")
190     pmksa = dev[0].get_pmksa(bssid)
191     if pmksa is None:
192         raise Exception("No PMKSA cache entry created")
193     if pmksa['opportunistic'] != '0':
194         raise Exception("Unexpected opportunistic PMKSA cache entry")
195
196     hostapd.add_ap(apdev[1], params)
197     bssid2 = apdev[1]['bssid']
198
199     dev[0].dump_monitor()
200     logger.info("Roam to AP2")
201     dev[0].scan(freq="2412")
202     dev[0].request("ROAM " + bssid2)
203     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED",
204                             "CTRL-EVENT-CONNECTED"], timeout=10)
205     if ev is None:
206         raise Exception("Roaming with the AP timed out")
207     if "CTRL-EVENT-EAP-STARTED" in ev:
208         raise Exception("Unexpected EAP exchange")
209     pmksa2 = dev[0].get_pmksa(bssid2)
210     if pmksa2 is None:
211         raise Exception("No PMKSA cache entry created")
212
213     dev[0].dump_monitor()
214     logger.info("Roam back to AP1")
215     dev[0].scan(freq="2412")
216     dev[0].request("ROAM " + bssid)
217     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED",
218                             "CTRL-EVENT-CONNECTED"], timeout=10)
219     if ev is None:
220         raise Exception("Roaming with the AP timed out")
221     if "CTRL-EVENT-EAP-STARTED" in ev:
222         raise Exception("Unexpected EAP exchange")
223
224     pmksa1b = dev[0].get_pmksa(bssid)
225     if pmksa1b is None:
226         raise Exception("No PMKSA cache entry found")
227     if pmksa['pmkid'] != pmksa1b['pmkid']:
228         raise Exception("Unexpected PMKID change for AP1")
229
230 def test_pmksa_cache_opportunistic_connect(dev, apdev):
231     """Opportunistic PMKSA caching with connect API"""
232     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
233     params['okc'] = "1"
234     hostapd.add_ap(apdev[0], params)
235     bssid = apdev[0]['bssid']
236     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
237     wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
238     wpas.connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
239                  eap="GPSK", identity="gpsk user",
240                  password="abcdefghijklmnop0123456789abcdef", okc=True,
241                  scan_freq="2412")
242     pmksa = wpas.get_pmksa(bssid)
243     if pmksa is None:
244         raise Exception("No PMKSA cache entry created")
245     if pmksa['opportunistic'] != '0':
246         raise Exception("Unexpected opportunistic PMKSA cache entry")
247
248     hostapd.add_ap(apdev[1], params)
249     bssid2 = apdev[1]['bssid']
250
251     wpas.dump_monitor()
252     logger.info("Roam to AP2")
253     wpas.scan_for_bss(bssid2, freq="2412", force_scan=True)
254     wpas.request("ROAM " + bssid2)
255     ev = wpas.wait_event(["CTRL-EVENT-EAP-STARTED",
256                             "CTRL-EVENT-CONNECTED"], timeout=10)
257     if ev is None:
258         raise Exception("Roaming with the AP timed out")
259     if "CTRL-EVENT-EAP-STARTED" in ev:
260         raise Exception("Unexpected EAP exchange")
261     pmksa2 = wpas.get_pmksa(bssid2)
262     if pmksa2 is None:
263         raise Exception("No PMKSA cache entry created")
264
265     wpas.dump_monitor()
266     logger.info("Roam back to AP1")
267     wpas.scan(freq="2412")
268     wpas.request("ROAM " + bssid)
269     ev = wpas.wait_event(["CTRL-EVENT-EAP-STARTED",
270                             "CTRL-EVENT-CONNECTED"], timeout=10)
271     if ev is None:
272         raise Exception("Roaming with the AP timed out")
273     if "CTRL-EVENT-EAP-STARTED" in ev:
274         raise Exception("Unexpected EAP exchange")
275
276     pmksa1b = wpas.get_pmksa(bssid)
277     if pmksa1b is None:
278         raise Exception("No PMKSA cache entry found")
279     if pmksa['pmkid'] != pmksa1b['pmkid']:
280         raise Exception("Unexpected PMKID change for AP1")
281
282 def test_pmksa_cache_expiration(dev, apdev):
283     """PMKSA cache entry expiration"""
284     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
285     hostapd.add_ap(apdev[0], params)
286     bssid = apdev[0]['bssid']
287     dev[0].request("SET dot11RSNAConfigPMKLifetime 10")
288     dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
289                    eap="GPSK", identity="gpsk user",
290                    password="abcdefghijklmnop0123456789abcdef",
291                    scan_freq="2412")
292     pmksa = dev[0].get_pmksa(bssid)
293     if pmksa is None:
294         raise Exception("No PMKSA cache entry created")
295     logger.info("Wait for PMKSA cache entry to expire")
296     ev = dev[0].wait_event(["WPA: Key negotiation completed",
297                             "CTRL-EVENT-DISCONNECTED"], timeout=15)
298     if ev is None:
299         raise Exception("No EAP reauthentication seen")
300     if "CTRL-EVENT-DISCONNECTED" in ev:
301         raise Exception("Unexpected disconnection")
302     pmksa2 = dev[0].get_pmksa(bssid)
303     if pmksa['pmkid'] == pmksa2['pmkid']:
304         raise Exception("PMKID did not change")
305
306 def test_pmksa_cache_expiration_disconnect(dev, apdev):
307     """PMKSA cache entry expiration (disconnect)"""
308     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
309     hapd = hostapd.add_ap(apdev[0], params)
310     bssid = apdev[0]['bssid']
311     dev[0].request("SET dot11RSNAConfigPMKLifetime 2")
312     dev[0].request("SET dot11RSNAConfigPMKReauthThreshold 100")
313     dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
314                    eap="GPSK", identity="gpsk user",
315                    password="abcdefghijklmnop0123456789abcdef",
316                    scan_freq="2412")
317     pmksa = dev[0].get_pmksa(bssid)
318     if pmksa is None:
319         raise Exception("No PMKSA cache entry created")
320     hapd.request("SET auth_server_shared_secret incorrect")
321     logger.info("Wait for PMKSA cache entry to expire")
322     ev = dev[0].wait_event(["WPA: Key negotiation completed",
323                             "CTRL-EVENT-DISCONNECTED"], timeout=15)
324     if ev is None:
325         raise Exception("No EAP reauthentication seen")
326     if "CTRL-EVENT-DISCONNECTED" not in ev:
327         raise Exception("Missing disconnection")
328     hapd.request("SET auth_server_shared_secret radius")
329     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=15)
330     if ev is None:
331         raise Exception("No EAP reauthentication seen")
332     pmksa2 = dev[0].get_pmksa(bssid)
333     if pmksa['pmkid'] == pmksa2['pmkid']:
334         raise Exception("PMKID did not change")
335
336 def test_pmksa_cache_and_cui(dev, apdev):
337     """PMKSA cache and Chargeable-User-Identity"""
338     params = hostapd.wpa2_eap_params(ssid="cui")
339     params['radius_request_cui'] = '1'
340     params['acct_server_addr'] = "127.0.0.1"
341     params['acct_server_port'] = "1813"
342     params['acct_server_shared_secret'] = "radius"
343     hapd = hostapd.add_ap(apdev[0], params)
344     bssid = apdev[0]['bssid']
345     dev[0].connect("cui", proto="RSN", key_mgmt="WPA-EAP",
346                    eap="GPSK", identity="gpsk-cui",
347                    password="abcdefghijklmnop0123456789abcdef",
348                    scan_freq="2412")
349     pmksa = dev[0].get_pmksa(bssid)
350     if pmksa is None:
351         raise Exception("No PMKSA cache entry created")
352     ev = hapd.wait_event([ "AP-STA-CONNECTED" ], timeout=5)
353     if ev is None:
354         raise Exception("No connection event received from hostapd")
355
356     dev[0].dump_monitor()
357     logger.info("Disconnect and reconnect to the same AP")
358     dev[0].request("DISCONNECT")
359     dev[0].wait_disconnected()
360     dev[0].request("RECONNECT")
361     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED",
362                             "CTRL-EVENT-CONNECTED"], timeout=10)
363     if ev is None:
364         raise Exception("Reconnect timed out")
365     if "CTRL-EVENT-EAP-STARTED" in ev:
366         raise Exception("Unexpected EAP exchange")
367     pmksa1b = dev[0].get_pmksa(bssid)
368     if pmksa1b is None:
369         raise Exception("No PMKSA cache entry found")
370     if pmksa['pmkid'] != pmksa1b['pmkid']:
371         raise Exception("Unexpected PMKID change for AP1")
372
373     dev[0].request("REAUTHENTICATE")
374     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
375     if ev is None:
376         raise Exception("EAP success timed out")
377     for i in range(0, 20):
378         state = dev[0].get_status_field("wpa_state")
379         if state == "COMPLETED":
380             break
381         time.sleep(0.1)
382     if state != "COMPLETED":
383         raise Exception("Reauthentication did not complete")
384
385 def generic_pmksa_cache_preauth(dev, apdev, extraparams, identity, databridge,
386                                 force_disconnect=False):
387     if not extraparams:
388         extraparams = [{}, {}]
389     try:
390         params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
391         params['bridge'] = 'ap-br0'
392         for key, value in extraparams[0].iteritems():
393             params[key] = value
394
395         hapd = hostapd.add_ap(apdev[0], params)
396         subprocess.call(['brctl', 'setfd', 'ap-br0', '0'])
397         subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'up'])
398         eap_connect(dev[0], hapd, "PAX", identity,
399                     password_hex="0123456789abcdef0123456789abcdef")
400
401         # Verify connectivity in the correct VLAN
402         hwsim_utils.test_connectivity_iface(dev[0], hapd, databridge)
403
404         params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
405         params['bridge'] = 'ap-br0'
406         params['rsn_preauth'] = '1'
407         params['rsn_preauth_interfaces'] = databridge
408         for key, value in extraparams[1].iteritems():
409             params[key] = value
410         hostapd.add_ap(apdev[1], params)
411         bssid1 = apdev[1]['bssid']
412         dev[0].scan(freq="2412")
413         success = False
414         status_seen = False
415         for i in range(0, 50):
416             if not status_seen:
417                 status = dev[0].request("STATUS")
418                 if "Pre-authentication EAPOL state machines:" in status:
419                     status_seen = True
420             time.sleep(0.1)
421             pmksa = dev[0].get_pmksa(bssid1)
422             if pmksa:
423                 success = True
424                 break
425         if not success:
426             raise Exception("No PMKSA cache entry created from pre-authentication")
427         if not status_seen:
428             raise Exception("Pre-authentication EAPOL status was not available")
429
430         dev[0].scan(freq="2412")
431         if "[WPA2-EAP-CCMP-preauth]" not in dev[0].request("SCAN_RESULTS"):
432             raise Exception("Scan results missing RSN element info")
433         dev[0].request("ROAM " + bssid1)
434         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED",
435                                 "CTRL-EVENT-CONNECTED"], timeout=10)
436         if ev is None:
437             raise Exception("Roaming with the AP timed out")
438         if "CTRL-EVENT-EAP-STARTED" in ev:
439             raise Exception("Unexpected EAP exchange")
440         pmksa2 = dev[0].get_pmksa(bssid1)
441         if pmksa2 is None:
442             raise Exception("No PMKSA cache entry")
443         if pmksa['pmkid'] != pmksa2['pmkid']:
444             raise Exception("Unexpected PMKID change")
445
446         # Verify connectivity in the correct VLAN
447         hwsim_utils.test_connectivity_iface(dev[0], hapd, databridge)
448
449         if not force_disconnect:
450             return
451
452         # Disconnect the STA from both APs to avoid forceful ifdown by the
453         # test script on a VLAN that this has an associated STA. That used to
454         # trigger a mac80211 warning.
455         dev[0].request("DISCONNECT")
456         hapd.request("DISABLE")
457
458     finally:
459         subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'down'],
460                         stderr=open('/dev/null', 'w'))
461         subprocess.call(['brctl', 'delbr', 'ap-br0'],
462                         stderr=open('/dev/null', 'w'))
463
464 def test_pmksa_cache_preauth(dev, apdev):
465     """RSN pre-authentication to generate PMKSA cache entry"""
466     generic_pmksa_cache_preauth(dev, apdev, None,
467                                 "pax.user@example.com", "ap-br0")
468
469 def test_pmksa_cache_preauth_per_sta_vif(dev, apdev):
470     """RSN pre-authentication to generate PMKSA cache entry with per_sta_vif"""
471     extraparams = [{}, {}]
472     extraparams[0]['per_sta_vif'] = "1"
473     extraparams[1]['per_sta_vif'] = "1"
474     generic_pmksa_cache_preauth(dev, apdev, extraparams,
475                                 "pax.user@example.com", "ap-br0")
476
477 def test_pmksa_cache_preauth_vlan_enabled(dev, apdev):
478     """RSN pre-authentication to generate PMKSA cache entry (dynamic_vlan optional but station without VLAN set)"""
479     extraparams = [{}, {}]
480     extraparams[0]['dynamic_vlan'] = '1'
481     extraparams[1]['dynamic_vlan'] = '1'
482     generic_pmksa_cache_preauth(dev, apdev, extraparams,
483                                 "pax.user@example.com", "ap-br0")
484
485 def test_pmksa_cache_preauth_vlan_enabled_per_sta_vif(dev, apdev):
486     """RSN pre-authentication to generate PMKSA cache entry (dynamic_vlan optional but station without VLAN set, with per_sta_vif enabled)"""
487     extraparams = [{}, {}]
488     extraparams[0]['per_sta_vif'] = "1"
489     extraparams[1]['per_sta_vif'] = "1"
490     extraparams[0]['dynamic_vlan'] = '1'
491     extraparams[1]['dynamic_vlan'] = '1'
492     generic_pmksa_cache_preauth(dev, apdev, extraparams,
493                                 "pax.user@example.com", "ap-br0")
494
495 def test_pmksa_cache_preauth_vlan_used(dev, apdev):
496     """RSN pre-authentication to generate PMKSA cache entry (station with VLAN set)"""
497     run_pmksa_cache_preauth_vlan_used(dev, apdev, None, force_disconnect=True)
498
499 def run_pmksa_cache_preauth_vlan_used(dev, apdev, extraparams=None,
500                                       force_disconnect=False):
501     try:
502         subprocess.call(['brctl', 'addbr', 'brvlan1'])
503         subprocess.call(['brctl', 'setfd', 'brvlan1', '0'])
504         if not extraparams:
505             extraparams = [{}, {}]
506         extraparams[0]['dynamic_vlan'] = '1'
507         extraparams[0]['vlan_file'] = 'hostapd.wlan3.vlan'
508         extraparams[1]['dynamic_vlan'] = '1'
509         extraparams[1]['vlan_file'] = 'hostapd.wlan4.vlan'
510         generic_pmksa_cache_preauth(dev, apdev, extraparams,
511                                     "vlan1", "brvlan1",
512                                     force_disconnect=force_disconnect)
513     finally:
514         subprocess.call(['ip', 'link', 'set', 'dev', 'brvlan1', 'down'])
515         subprocess.call(['ip', 'link', 'set', 'dev', 'wlan3.1', 'down'],
516                         stderr=open('/dev/null', 'w'))
517         subprocess.call(['ip', 'link', 'set', 'dev', 'wlan4.1', 'down'],
518                         stderr=open('/dev/null', 'w'))
519         subprocess.call(['brctl', 'delif', 'brvlan1', 'wlan3.1'],
520                         stderr=open('/dev/null', 'w'))
521         subprocess.call(['brctl', 'delif', 'brvlan1', 'wlan4.1'],
522                         stderr=open('/dev/null', 'w'))
523         subprocess.call(['brctl', 'delbr', 'brvlan1'])
524
525 def test_pmksa_cache_preauth_vlan_used_per_sta_vif(dev, apdev):
526     """RSN pre-authentication to generate PMKSA cache entry (station with VLAN set, per_sta_vif=1)"""
527     extraparams = [{}, {}]
528     extraparams[0]['per_sta_vif'] = "1"
529     extraparams[1]['per_sta_vif'] = "1"
530     run_pmksa_cache_preauth_vlan_used(dev, apdev, extraparams)
531
532 def test_pmksa_cache_disabled(dev, apdev):
533     """PMKSA cache disabling on AP"""
534     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
535     params['disable_pmksa_caching'] = '1'
536     hostapd.add_ap(apdev[0], params)
537     bssid = apdev[0]['bssid']
538     dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
539                    eap="GPSK", identity="gpsk user",
540                    password="abcdefghijklmnop0123456789abcdef",
541                    scan_freq="2412")
542
543     hostapd.add_ap(apdev[1], params)
544     bssid2 = apdev[1]['bssid']
545
546     dev[0].dump_monitor()
547     logger.info("Roam to AP2")
548     dev[0].scan_for_bss(bssid2, freq="2412")
549     dev[0].request("ROAM " + bssid2)
550     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
551     if ev is None:
552         raise Exception("EAP success timed out")
553     dev[0].wait_connected(timeout=10, error="Roaming timed out")
554
555     dev[0].dump_monitor()
556     logger.info("Roam back to AP1")
557     dev[0].scan(freq="2412")
558     dev[0].request("ROAM " + bssid)
559     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED",
560                             "CTRL-EVENT-CONNECTED"], timeout=20)
561     if ev is None:
562         raise Exception("Roaming with the AP timed out")
563     if "CTRL-EVENT-CONNECTED" in ev:
564         raise Exception("EAP exchange missing")
565     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=20)
566     if ev is None:
567         raise Exception("Roaming with the AP timed out")
568
569 def test_pmksa_cache_ap_expiration(dev, apdev):
570     """PMKSA cache entry expiring on AP"""
571     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
572     hapd = hostapd.add_ap(apdev[0], params)
573     bssid = apdev[0]['bssid']
574     dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
575                    eap="GPSK", identity="gpsk-user-session-timeout",
576                    password="abcdefghijklmnop0123456789abcdef",
577                    scan_freq="2412")
578     ev = hapd.wait_event([ "AP-STA-CONNECTED" ], timeout=5)
579     if ev is None:
580         raise Exception("No connection event received from hostapd")
581     dev[0].request("DISCONNECT")
582     time.sleep(5)
583     dev[0].dump_monitor()
584     dev[0].request("RECONNECT")
585     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED",
586                             "CTRL-EVENT-CONNECTED"], timeout=20)
587     if ev is None:
588         raise Exception("Roaming with the AP timed out")
589     if "CTRL-EVENT-CONNECTED" in ev:
590         raise Exception("EAP exchange missing")
591     dev[0].wait_connected(timeout=20, error="Reconnect timed out")
592     dev[0].dump_monitor()
593     dev[0].wait_disconnected(timeout=20)
594     dev[0].wait_connected(timeout=20, error="Reassociation timed out")
595
596 def test_pmksa_cache_multiple_sta(dev, apdev):
597     """PMKSA cache with multiple stations"""
598     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
599     hostapd.add_ap(apdev[0], params)
600     bssid = apdev[0]['bssid']
601     dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
602                    eap="GPSK", identity="gpsk-user-session-timeout",
603                    password="abcdefghijklmnop0123456789abcdef",
604                    scan_freq="2412")
605     dev[1].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
606                    eap="GPSK", identity="gpsk user",
607                    password="abcdefghijklmnop0123456789abcdef",
608                    scan_freq="2412")
609     dev[2].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
610                    eap="GPSK", identity="gpsk-user-session-timeout",
611                    password="abcdefghijklmnop0123456789abcdef",
612                    scan_freq="2412")
613
614     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
615     wpas.interface_add("wlan5")
616     wpas.connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
617                  eap="GPSK", identity="gpsk user",
618                  password="abcdefghijklmnop0123456789abcdef",
619                  scan_freq="2412")
620
621     hostapd.add_ap(apdev[1], params)
622     bssid2 = apdev[1]['bssid']
623
624     logger.info("Roam to AP2")
625     for sta in [ dev[1], dev[0], dev[2], wpas ]:
626         sta.dump_monitor()
627         sta.scan_for_bss(bssid2, freq="2412")
628         sta.request("ROAM " + bssid2)
629         ev = sta.wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
630         if ev is None:
631             raise Exception("EAP success timed out")
632         sta.wait_connected(timeout=10, error="Roaming timed out")
633
634     logger.info("Roam back to AP1")
635     for sta in [ dev[1], wpas, dev[0], dev[2] ]:
636         sta.dump_monitor()
637         sta.scan(freq="2412")
638         sta.dump_monitor()
639         sta.request("ROAM " + bssid)
640         sta.wait_connected(timeout=10, error="Roaming timed out")
641         sta.dump_monitor()
642
643     time.sleep(4)
644
645     logger.info("Roam back to AP2")
646     for sta in [ dev[1], wpas, dev[0], dev[2] ]:
647         sta.dump_monitor()
648         sta.scan(freq="2412")
649         sta.dump_monitor()
650         sta.request("ROAM " + bssid2)
651         sta.wait_connected(timeout=10, error="Roaming timed out")
652         sta.dump_monitor()
653
654 def test_pmksa_cache_opportunistic_multiple_sta(dev, apdev):
655     """Opportunistic PMKSA caching with multiple stations"""
656     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
657     params['okc'] = "1"
658     hostapd.add_ap(apdev[0], params)
659     bssid = apdev[0]['bssid']
660     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
661     wpas.interface_add("wlan5")
662     for sta in [ dev[0], dev[1], dev[2], wpas ]:
663         sta.connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
664                     eap="GPSK", identity="gpsk user",
665                     password="abcdefghijklmnop0123456789abcdef", okc=True,
666                     scan_freq="2412")
667
668     hostapd.add_ap(apdev[1], params)
669     bssid2 = apdev[1]['bssid']
670
671     logger.info("Roam to AP2")
672     for sta in [ dev[2], dev[0], wpas, dev[1] ]:
673         sta.dump_monitor()
674         sta.scan_for_bss(bssid2, freq="2412")
675         if "OK" not in sta.request("ROAM " + bssid2):
676             raise Exception("ROAM command failed")
677         ev = sta.wait_event(["CTRL-EVENT-EAP-STARTED",
678                              "CTRL-EVENT-CONNECTED"], timeout=10)
679         if ev is None:
680             raise Exception("Roaming with the AP timed out")
681         if "CTRL-EVENT-EAP-STARTED" in ev:
682             raise Exception("Unexpected EAP exchange")
683         pmksa2 = sta.get_pmksa(bssid2)
684         if pmksa2 is None:
685             raise Exception("No PMKSA cache entry created")
686
687     logger.info("Roam back to AP1")
688     for sta in [ dev[0], dev[1], dev[2], wpas ]:
689         sta.dump_monitor()
690         sta.scan_for_bss(bssid, freq="2412")
691         sta.request("ROAM " + bssid)
692         ev = sta.wait_event(["CTRL-EVENT-EAP-STARTED",
693                              "CTRL-EVENT-CONNECTED"], timeout=10)
694         if ev is None:
695             raise Exception("Roaming with the AP timed out")
696         if "CTRL-EVENT-EAP-STARTED" in ev:
697             raise Exception("Unexpected EAP exchange")
698
699 def test_pmksa_cache_preauth_oom(dev, apdev):
700     """RSN pre-authentication to generate PMKSA cache entry and OOM"""
701     try:
702         _test_pmksa_cache_preauth_oom(dev, apdev)
703     finally:
704         subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'down'])
705         subprocess.call(['brctl', 'delbr', 'ap-br0'])
706
707 def _test_pmksa_cache_preauth_oom(dev, apdev):
708     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
709     params['bridge'] = 'ap-br0'
710     hapd = hostapd.add_ap(apdev[0], params)
711     subprocess.call(['brctl', 'setfd', 'ap-br0', '0'])
712     subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'up'])
713     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
714                 password_hex="0123456789abcdef0123456789abcdef",
715                 bssid=apdev[0]['bssid'])
716
717     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
718     params['bridge'] = 'ap-br0'
719     params['rsn_preauth'] = '1'
720     params['rsn_preauth_interfaces'] = 'ap-br0'
721     hapd = hostapd.add_ap(apdev[1], params)
722     bssid1 = apdev[1]['bssid']
723
724     tests = [ (1, "rsn_preauth_receive"),
725               (2, "rsn_preauth_receive"),
726               (1, "rsn_preauth_send") ]
727     for test in tests:
728         with alloc_fail(hapd, test[0], test[1]):
729             dev[0].scan_for_bss(bssid1, freq="2412")
730             if "OK" not in dev[0].request("PREAUTH " + bssid1):
731                 raise Exception("PREAUTH failed")
732
733             success = False
734             count = 0
735             for i in range(50):
736                 time.sleep(0.1)
737                 pmksa = dev[0].get_pmksa(bssid1)
738                 if pmksa:
739                     success = True
740                     break
741                 state = hapd.request('GET_ALLOC_FAIL')
742                 if state.startswith('0:'):
743                     count += 1
744                     if count > 2:
745                         break
746             logger.info("PMKSA cache success: " + str(success))
747
748             dev[0].request("PMKSA_FLUSH")
749             dev[0].wait_disconnected()
750             dev[0].wait_connected()
751             dev[0].dump_monitor()
752
753 def test_pmksa_cache_size_limit(dev, apdev):
754     """PMKSA cache size limit in wpa_supplicant"""
755     try:
756         _test_pmksa_cache_size_limit(dev, apdev)
757     finally:
758         try:
759             hapd = hostapd.HostapdGlobal(apdev[0])
760             hapd.flush()
761             hapd.remove(apdev[0]['ifname'])
762         except:
763             pass
764         params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
765         bssid = apdev[0]['bssid']
766         params['bssid'] = bssid
767         hostapd.add_ap(apdev[0], params)
768
769 def _test_pmksa_cache_size_limit(dev, apdev):
770     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
771     id = dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
772                         eap="GPSK", identity="gpsk user",
773                         password="abcdefghijklmnop0123456789abcdef",
774                         scan_freq="2412", only_add_network=True)
775     for i in range(33):
776         bssid = apdev[0]['bssid'][0:15] + "%02x" % i
777         logger.info("Iteration with BSSID " + bssid)
778         params['bssid'] = bssid
779         hostapd.add_ap(apdev[0], params)
780         dev[0].request("BSS_FLUSH 0")
781         dev[0].scan_for_bss(bssid, freq=2412, only_new=True)
782         dev[0].select_network(id)
783         dev[0].wait_connected()
784         dev[0].request("DISCONNECT")
785         dev[0].wait_disconnected()
786         dev[0].dump_monitor()
787         entries = len(dev[0].request("PMKSA").splitlines()) - 1
788         if i == 32:
789             if entries != 32:
790                 raise Exception("Unexpected number of PMKSA entries after expected removal of the oldest entry")
791         elif i + 1 != entries:
792             raise Exception("Unexpected number of PMKSA entries")
793
794         hapd = hostapd.HostapdGlobal(apdev[0])
795         hapd.flush()
796         hapd.remove(apdev[0]['ifname'])
797
798 def test_pmksa_cache_preauth_timeout(dev, apdev):
799     """RSN pre-authentication timing out"""
800     try:
801         _test_pmksa_cache_preauth_timeout(dev, apdev)
802     finally:
803         dev[0].request("SET dot11RSNAConfigSATimeout 60")
804
805 def _test_pmksa_cache_preauth_timeout(dev, apdev):
806     dev[0].request("SET dot11RSNAConfigSATimeout 1")
807     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
808     hapd = hostapd.add_ap(apdev[0], params)
809     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
810                 password_hex="0123456789abcdef0123456789abcdef",
811                 bssid=apdev[0]['bssid'])
812     if "OK" not in dev[0].request("PREAUTH f2:11:22:33:44:55"):
813         raise Exception("PREAUTH failed")
814     ev = dev[0].wait_event(["RSN: pre-authentication with"], timeout=5)
815     if ev is None:
816         raise Exception("No timeout event seen")
817     if "timed out" not in ev:
818         raise Exception("Unexpected event: " + ev)
819
820 def test_pmksa_cache_preauth_wpas_oom(dev, apdev):
821     """RSN pre-authentication OOM in wpa_supplicant"""
822     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
823     hapd = hostapd.add_ap(apdev[0], params)
824     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
825                 password_hex="0123456789abcdef0123456789abcdef",
826                 bssid=apdev[0]['bssid'])
827     for i in range(1, 11):
828         with alloc_fail(dev[0], i, "rsn_preauth_init"):
829             res = dev[0].request("PREAUTH f2:11:22:33:44:55").strip()
830             logger.info("Iteration %d - PREAUTH command results: %s" % (i, res))
831             for j in range(10):
832                 state = dev[0].request('GET_ALLOC_FAIL')
833                 if state.startswith('0:'):
834                     break
835                 time.sleep(0.05)
836
837 def test_pmksa_cache_ctrl(dev, apdev):
838     """PMKSA cache control interface operations"""
839     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
840     hapd = hostapd.add_ap(apdev[0], params)
841     bssid = apdev[0]['bssid']
842     addr = dev[0].own_addr()
843
844     dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
845                    eap="GPSK", identity="gpsk user",
846                    password="abcdefghijklmnop0123456789abcdef",
847                    scan_freq="2412")
848
849     pmksa_sta = dev[0].get_pmksa(bssid)
850     if pmksa_sta is None:
851         raise Exception("No PMKSA cache entry created on STA")
852     pmksa_ap = hapd.get_pmksa(addr)
853     if pmksa_ap is None:
854         raise Exception("No PMKSA cache entry created on AP")
855     if pmksa_sta['pmkid'] != pmksa_ap['pmkid']:
856         raise Exception("PMKID mismatch in PMKSA cache entries")
857
858     if "OK" not in hapd.request("PMKSA_FLUSH"):
859         raise Exception("PMKSA_FLUSH failed")
860     pmksa_ap = hapd.get_pmksa(addr)
861     if pmksa_ap is not None:
862         raise Exception("PMKSA cache entry was not removed on AP")
863
864     dev[0].request("DISCONNECT")
865     dev[0].wait_disconnected()
866     dev[0].request("RECONNECT")
867     dev[0].wait_connected()
868
869     pmksa_sta2 = dev[0].get_pmksa(bssid)
870     if pmksa_sta2 is None:
871         raise Exception("No PMKSA cache entry created on STA after reconnect")
872     pmksa_ap2 = hapd.get_pmksa(addr)
873     if pmksa_ap2 is None:
874         raise Exception("No PMKSA cache entry created on AP after reconnect")
875     if pmksa_sta2['pmkid'] != pmksa_ap2['pmkid']:
876         raise Exception("PMKID mismatch in PMKSA cache entries after reconnect")
877     if pmksa_sta2['pmkid'] == pmksa_sta['pmkid']:
878         raise Exception("PMKID did not change after reconnect")