tests: Make pmksa_cache_{,opportunistic_}multiple_sta more robust
[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         hapd.cmd_execute(['brctl', 'setfd', 'ap-br0', '0'])
397         hapd.cmd_execute(['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         hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev',
460                                        'ap-br0', 'down', '2>', '/dev/null'],
461                             shell=True)
462         hostapd.cmd_execute(apdev[0], ['brctl', 'delbr', 'ap-br0',
463                                        '2>', '/dev/null'], shell=True)
464
465 def test_pmksa_cache_preauth(dev, apdev):
466     """RSN pre-authentication to generate PMKSA cache entry"""
467     generic_pmksa_cache_preauth(dev, apdev, None,
468                                 "pax.user@example.com", "ap-br0")
469
470 def test_pmksa_cache_preauth_per_sta_vif(dev, apdev):
471     """RSN pre-authentication to generate PMKSA cache entry with per_sta_vif"""
472     extraparams = [{}, {}]
473     extraparams[0]['per_sta_vif'] = "1"
474     extraparams[1]['per_sta_vif'] = "1"
475     generic_pmksa_cache_preauth(dev, apdev, extraparams,
476                                 "pax.user@example.com", "ap-br0")
477
478 def test_pmksa_cache_preauth_vlan_enabled(dev, apdev):
479     """RSN pre-authentication to generate PMKSA cache entry (dynamic_vlan optional but station without VLAN set)"""
480     extraparams = [{}, {}]
481     extraparams[0]['dynamic_vlan'] = '1'
482     extraparams[1]['dynamic_vlan'] = '1'
483     generic_pmksa_cache_preauth(dev, apdev, extraparams,
484                                 "pax.user@example.com", "ap-br0")
485
486 def test_pmksa_cache_preauth_vlan_enabled_per_sta_vif(dev, apdev):
487     """RSN pre-authentication to generate PMKSA cache entry (dynamic_vlan optional but station without VLAN set, with per_sta_vif enabled)"""
488     extraparams = [{}, {}]
489     extraparams[0]['per_sta_vif'] = "1"
490     extraparams[1]['per_sta_vif'] = "1"
491     extraparams[0]['dynamic_vlan'] = '1'
492     extraparams[1]['dynamic_vlan'] = '1'
493     generic_pmksa_cache_preauth(dev, apdev, extraparams,
494                                 "pax.user@example.com", "ap-br0")
495
496 def test_pmksa_cache_preauth_vlan_used(dev, apdev):
497     """RSN pre-authentication to generate PMKSA cache entry (station with VLAN set)"""
498     run_pmksa_cache_preauth_vlan_used(dev, apdev, None, force_disconnect=True)
499
500 def run_pmksa_cache_preauth_vlan_used(dev, apdev, extraparams=None,
501                                       force_disconnect=False):
502     try:
503         subprocess.call(['brctl', 'addbr', 'brvlan1'])
504         subprocess.call(['brctl', 'setfd', 'brvlan1', '0'])
505         if not extraparams:
506             extraparams = [{}, {}]
507         extraparams[0]['dynamic_vlan'] = '1'
508         extraparams[0]['vlan_file'] = 'hostapd.wlan3.vlan'
509         extraparams[1]['dynamic_vlan'] = '1'
510         extraparams[1]['vlan_file'] = 'hostapd.wlan4.vlan'
511         generic_pmksa_cache_preauth(dev, apdev, extraparams,
512                                     "vlan1", "brvlan1",
513                                     force_disconnect=force_disconnect)
514     finally:
515         subprocess.call(['ip', 'link', 'set', 'dev', 'brvlan1', 'down'])
516         subprocess.call(['ip', 'link', 'set', 'dev', 'wlan3.1', 'down'],
517                         stderr=open('/dev/null', 'w'))
518         subprocess.call(['ip', 'link', 'set', 'dev', 'wlan4.1', 'down'],
519                         stderr=open('/dev/null', 'w'))
520         subprocess.call(['brctl', 'delif', 'brvlan1', 'wlan3.1'],
521                         stderr=open('/dev/null', 'w'))
522         subprocess.call(['brctl', 'delif', 'brvlan1', 'wlan4.1'],
523                         stderr=open('/dev/null', 'w'))
524         subprocess.call(['brctl', 'delbr', 'brvlan1'])
525
526 def test_pmksa_cache_preauth_vlan_used_per_sta_vif(dev, apdev):
527     """RSN pre-authentication to generate PMKSA cache entry (station with VLAN set, per_sta_vif=1)"""
528     extraparams = [{}, {}]
529     extraparams[0]['per_sta_vif'] = "1"
530     extraparams[1]['per_sta_vif'] = "1"
531     run_pmksa_cache_preauth_vlan_used(dev, apdev, extraparams)
532
533 def test_pmksa_cache_disabled(dev, apdev):
534     """PMKSA cache disabling on AP"""
535     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
536     params['disable_pmksa_caching'] = '1'
537     hostapd.add_ap(apdev[0], params)
538     bssid = apdev[0]['bssid']
539     dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
540                    eap="GPSK", identity="gpsk user",
541                    password="abcdefghijklmnop0123456789abcdef",
542                    scan_freq="2412")
543
544     hostapd.add_ap(apdev[1], params)
545     bssid2 = apdev[1]['bssid']
546
547     dev[0].dump_monitor()
548     logger.info("Roam to AP2")
549     dev[0].scan_for_bss(bssid2, freq="2412")
550     dev[0].request("ROAM " + bssid2)
551     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
552     if ev is None:
553         raise Exception("EAP success timed out")
554     dev[0].wait_connected(timeout=10, error="Roaming timed out")
555
556     dev[0].dump_monitor()
557     logger.info("Roam back to AP1")
558     dev[0].scan(freq="2412")
559     dev[0].request("ROAM " + bssid)
560     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED",
561                             "CTRL-EVENT-CONNECTED"], timeout=20)
562     if ev is None:
563         raise Exception("Roaming with the AP timed out")
564     if "CTRL-EVENT-CONNECTED" in ev:
565         raise Exception("EAP exchange missing")
566     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=20)
567     if ev is None:
568         raise Exception("Roaming with the AP timed out")
569
570 def test_pmksa_cache_ap_expiration(dev, apdev):
571     """PMKSA cache entry expiring on AP"""
572     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
573     hapd = hostapd.add_ap(apdev[0], params)
574     bssid = apdev[0]['bssid']
575     dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
576                    eap="GPSK", identity="gpsk-user-session-timeout",
577                    password="abcdefghijklmnop0123456789abcdef",
578                    scan_freq="2412")
579     ev = hapd.wait_event([ "AP-STA-CONNECTED" ], timeout=5)
580     if ev is None:
581         raise Exception("No connection event received from hostapd")
582     dev[0].request("DISCONNECT")
583     time.sleep(5)
584     dev[0].dump_monitor()
585     dev[0].request("RECONNECT")
586     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED",
587                             "CTRL-EVENT-CONNECTED"], timeout=20)
588     if ev is None:
589         raise Exception("Roaming with the AP timed out")
590     if "CTRL-EVENT-CONNECTED" in ev:
591         raise Exception("EAP exchange missing")
592     dev[0].wait_connected(timeout=20, error="Reconnect timed out")
593     dev[0].dump_monitor()
594     dev[0].wait_disconnected(timeout=20)
595     dev[0].wait_connected(timeout=20, error="Reassociation timed out")
596
597 def test_pmksa_cache_multiple_sta(dev, apdev):
598     """PMKSA cache with multiple stations"""
599     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
600     hostapd.add_ap(apdev[0], params)
601     bssid = apdev[0]['bssid']
602     for d in dev:
603         d.flush_scan_cache()
604     dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
605                    eap="GPSK", identity="gpsk-user-session-timeout",
606                    password="abcdefghijklmnop0123456789abcdef",
607                    scan_freq="2412")
608     dev[1].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
609                    eap="GPSK", identity="gpsk user",
610                    password="abcdefghijklmnop0123456789abcdef",
611                    scan_freq="2412")
612     dev[2].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
613                    eap="GPSK", identity="gpsk-user-session-timeout",
614                    password="abcdefghijklmnop0123456789abcdef",
615                    scan_freq="2412")
616
617     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
618     wpas.interface_add("wlan5")
619     wpas.flush_scan_cache()
620     wpas.connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
621                  eap="GPSK", identity="gpsk user",
622                  password="abcdefghijklmnop0123456789abcdef",
623                  scan_freq="2412")
624
625     hostapd.add_ap(apdev[1], params)
626     bssid2 = apdev[1]['bssid']
627
628     logger.info("Roam to AP2")
629     for sta in [ dev[1], dev[0], dev[2], wpas ]:
630         sta.dump_monitor()
631         sta.scan_for_bss(bssid2, freq="2412")
632         if "OK" not in sta.request("ROAM " + bssid2):
633             raise Exception("ROAM command failed (" + sta.ifname + ")")
634         ev = sta.wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
635         if ev is None:
636             raise Exception("EAP success timed out")
637         sta.wait_connected(timeout=10, error="Roaming timed out")
638         sta.dump_monitor()
639
640     logger.info("Roam back to AP1")
641     for sta in [ dev[1], wpas, dev[0], dev[2] ]:
642         sta.dump_monitor()
643         sta.scan(freq="2412")
644         sta.dump_monitor()
645         sta.request("ROAM " + bssid)
646         sta.wait_connected(timeout=10, error="Roaming timed out")
647         sta.dump_monitor()
648
649     time.sleep(4)
650
651     logger.info("Roam back to AP2")
652     for sta in [ dev[1], wpas, dev[0], dev[2] ]:
653         sta.dump_monitor()
654         sta.scan(freq="2412")
655         sta.dump_monitor()
656         sta.request("ROAM " + bssid2)
657         sta.wait_connected(timeout=10, error="Roaming timed out")
658         sta.dump_monitor()
659
660 def test_pmksa_cache_opportunistic_multiple_sta(dev, apdev):
661     """Opportunistic PMKSA caching with multiple stations"""
662     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
663     params['okc'] = "1"
664     hostapd.add_ap(apdev[0], params)
665     bssid = apdev[0]['bssid']
666     for d in dev:
667         d.flush_scan_cache()
668     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
669     wpas.interface_add("wlan5")
670     wpas.flush_scan_cache()
671     for sta in [ dev[0], dev[1], dev[2], wpas ]:
672         sta.connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
673                     eap="GPSK", identity="gpsk user",
674                     password="abcdefghijklmnop0123456789abcdef", okc=True,
675                     scan_freq="2412")
676
677     hostapd.add_ap(apdev[1], params)
678     bssid2 = apdev[1]['bssid']
679
680     logger.info("Roam to AP2")
681     for sta in [ dev[2], dev[0], wpas, dev[1] ]:
682         sta.dump_monitor()
683         sta.scan_for_bss(bssid2, freq="2412")
684         if "OK" not in sta.request("ROAM " + bssid2):
685             raise Exception("ROAM command failed")
686         ev = sta.wait_event(["CTRL-EVENT-EAP-STARTED",
687                              "CTRL-EVENT-CONNECTED"], timeout=10)
688         if ev is None:
689             raise Exception("Roaming with the AP timed out")
690         if "CTRL-EVENT-EAP-STARTED" in ev:
691             raise Exception("Unexpected EAP exchange")
692         pmksa2 = sta.get_pmksa(bssid2)
693         if pmksa2 is None:
694             raise Exception("No PMKSA cache entry created")
695         sta.dump_monitor()
696
697     logger.info("Roam back to AP1")
698     for sta in [ dev[0], dev[1], dev[2], wpas ]:
699         sta.dump_monitor()
700         sta.scan_for_bss(bssid, freq="2412")
701         sta.request("ROAM " + bssid)
702         ev = sta.wait_event(["CTRL-EVENT-EAP-STARTED",
703                              "CTRL-EVENT-CONNECTED"], timeout=10)
704         if ev is None:
705             raise Exception("Roaming with the AP timed out")
706         if "CTRL-EVENT-EAP-STARTED" in ev:
707             raise Exception("Unexpected EAP exchange")
708
709 def test_pmksa_cache_preauth_oom(dev, apdev):
710     """RSN pre-authentication to generate PMKSA cache entry and OOM"""
711     try:
712         _test_pmksa_cache_preauth_oom(dev, apdev)
713     finally:
714         hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', 'ap-br0',
715                                        'down'])
716         hostapd.cmd_execute(apdev[0], ['brctl', 'delbr', 'ap-br0'])
717
718 def _test_pmksa_cache_preauth_oom(dev, apdev):
719     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
720     params['bridge'] = 'ap-br0'
721     hapd = hostapd.add_ap(apdev[0], params)
722     hostapd.cmd_execute(apdev[0], ['brctl', 'setfd', 'ap-br0', '0'])
723     hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', 'ap-br0', 'up'])
724     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
725                 password_hex="0123456789abcdef0123456789abcdef",
726                 bssid=apdev[0]['bssid'])
727
728     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
729     params['bridge'] = 'ap-br0'
730     params['rsn_preauth'] = '1'
731     params['rsn_preauth_interfaces'] = 'ap-br0'
732     hapd = hostapd.add_ap(apdev[1], params)
733     bssid1 = apdev[1]['bssid']
734
735     tests = [ (1, "rsn_preauth_receive"),
736               (2, "rsn_preauth_receive"),
737               (1, "rsn_preauth_send") ]
738     for test in tests:
739         with alloc_fail(hapd, test[0], test[1]):
740             dev[0].scan_for_bss(bssid1, freq="2412")
741             if "OK" not in dev[0].request("PREAUTH " + bssid1):
742                 raise Exception("PREAUTH failed")
743
744             success = False
745             count = 0
746             for i in range(50):
747                 time.sleep(0.1)
748                 pmksa = dev[0].get_pmksa(bssid1)
749                 if pmksa:
750                     success = True
751                     break
752                 state = hapd.request('GET_ALLOC_FAIL')
753                 if state.startswith('0:'):
754                     count += 1
755                     if count > 2:
756                         break
757             logger.info("PMKSA cache success: " + str(success))
758
759             dev[0].request("PMKSA_FLUSH")
760             dev[0].wait_disconnected()
761             dev[0].wait_connected()
762             dev[0].dump_monitor()
763
764 def test_pmksa_cache_size_limit(dev, apdev):
765     """PMKSA cache size limit in wpa_supplicant"""
766     try:
767         _test_pmksa_cache_size_limit(dev, apdev)
768     finally:
769         try:
770             hapd = hostapd.HostapdGlobal(apdev[0])
771             hapd.flush()
772             hapd.remove(apdev[0]['ifname'])
773         except:
774             pass
775         params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
776         bssid = apdev[0]['bssid']
777         params['bssid'] = bssid
778         hostapd.add_ap(apdev[0], params)
779
780 def _test_pmksa_cache_size_limit(dev, apdev):
781     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
782     id = dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
783                         eap="GPSK", identity="gpsk user",
784                         password="abcdefghijklmnop0123456789abcdef",
785                         scan_freq="2412", only_add_network=True)
786     for i in range(33):
787         bssid = apdev[0]['bssid'][0:15] + "%02x" % i
788         logger.info("Iteration with BSSID " + bssid)
789         params['bssid'] = bssid
790         hostapd.add_ap(apdev[0], params)
791         dev[0].request("BSS_FLUSH 0")
792         dev[0].scan_for_bss(bssid, freq=2412, only_new=True)
793         dev[0].select_network(id)
794         dev[0].wait_connected()
795         dev[0].request("DISCONNECT")
796         dev[0].wait_disconnected()
797         dev[0].dump_monitor()
798         entries = len(dev[0].request("PMKSA").splitlines()) - 1
799         if i == 32:
800             if entries != 32:
801                 raise Exception("Unexpected number of PMKSA entries after expected removal of the oldest entry")
802         elif i + 1 != entries:
803             raise Exception("Unexpected number of PMKSA entries")
804
805         hapd = hostapd.HostapdGlobal(apdev[0])
806         hapd.flush()
807         hapd.remove(apdev[0]['ifname'])
808
809 def test_pmksa_cache_preauth_timeout(dev, apdev):
810     """RSN pre-authentication timing out"""
811     try:
812         _test_pmksa_cache_preauth_timeout(dev, apdev)
813     finally:
814         dev[0].request("SET dot11RSNAConfigSATimeout 60")
815
816 def _test_pmksa_cache_preauth_timeout(dev, apdev):
817     dev[0].request("SET dot11RSNAConfigSATimeout 1")
818     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
819     hapd = hostapd.add_ap(apdev[0], params)
820     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
821                 password_hex="0123456789abcdef0123456789abcdef",
822                 bssid=apdev[0]['bssid'])
823     if "OK" not in dev[0].request("PREAUTH f2:11:22:33:44:55"):
824         raise Exception("PREAUTH failed")
825     ev = dev[0].wait_event(["RSN: pre-authentication with"], timeout=5)
826     if ev is None:
827         raise Exception("No timeout event seen")
828     if "timed out" not in ev:
829         raise Exception("Unexpected event: " + ev)
830
831 def test_pmksa_cache_preauth_wpas_oom(dev, apdev):
832     """RSN pre-authentication OOM in wpa_supplicant"""
833     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
834     hapd = hostapd.add_ap(apdev[0], params)
835     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
836                 password_hex="0123456789abcdef0123456789abcdef",
837                 bssid=apdev[0]['bssid'])
838     for i in range(1, 11):
839         with alloc_fail(dev[0], i, "rsn_preauth_init"):
840             res = dev[0].request("PREAUTH f2:11:22:33:44:55").strip()
841             logger.info("Iteration %d - PREAUTH command results: %s" % (i, res))
842             for j in range(10):
843                 state = dev[0].request('GET_ALLOC_FAIL')
844                 if state.startswith('0:'):
845                     break
846                 time.sleep(0.05)
847
848 def test_pmksa_cache_ctrl(dev, apdev):
849     """PMKSA cache control interface operations"""
850     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
851     hapd = hostapd.add_ap(apdev[0], params)
852     bssid = apdev[0]['bssid']
853     addr = dev[0].own_addr()
854
855     dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
856                    eap="GPSK", identity="gpsk user",
857                    password="abcdefghijklmnop0123456789abcdef",
858                    scan_freq="2412")
859
860     pmksa_sta = dev[0].get_pmksa(bssid)
861     if pmksa_sta is None:
862         raise Exception("No PMKSA cache entry created on STA")
863     pmksa_ap = hapd.get_pmksa(addr)
864     if pmksa_ap is None:
865         raise Exception("No PMKSA cache entry created on AP")
866     if pmksa_sta['pmkid'] != pmksa_ap['pmkid']:
867         raise Exception("PMKID mismatch in PMKSA cache entries")
868
869     if "OK" not in hapd.request("PMKSA_FLUSH"):
870         raise Exception("PMKSA_FLUSH failed")
871     pmksa_ap = hapd.get_pmksa(addr)
872     if pmksa_ap is not None:
873         raise Exception("PMKSA cache entry was not removed on AP")
874
875     dev[0].request("DISCONNECT")
876     dev[0].wait_disconnected()
877     dev[0].request("RECONNECT")
878     dev[0].wait_connected()
879
880     pmksa_sta2 = dev[0].get_pmksa(bssid)
881     if pmksa_sta2 is None:
882         raise Exception("No PMKSA cache entry created on STA after reconnect")
883     pmksa_ap2 = hapd.get_pmksa(addr)
884     if pmksa_ap2 is None:
885         raise Exception("No PMKSA cache entry created on AP after reconnect")
886     if pmksa_sta2['pmkid'] != pmksa_ap2['pmkid']:
887         raise Exception("PMKID mismatch in PMKSA cache entries after reconnect")
888     if pmksa_sta2['pmkid'] == pmksa_sta['pmkid']:
889         raise Exception("PMKID did not change after reconnect")