4fb7457bf4d8cbe892d888eb7f536843bbf1b645
[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     dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
603                    eap="GPSK", identity="gpsk-user-session-timeout",
604                    password="abcdefghijklmnop0123456789abcdef",
605                    scan_freq="2412")
606     dev[1].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
607                    eap="GPSK", identity="gpsk user",
608                    password="abcdefghijklmnop0123456789abcdef",
609                    scan_freq="2412")
610     dev[2].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
611                    eap="GPSK", identity="gpsk-user-session-timeout",
612                    password="abcdefghijklmnop0123456789abcdef",
613                    scan_freq="2412")
614
615     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
616     wpas.interface_add("wlan5")
617     wpas.connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
618                  eap="GPSK", identity="gpsk user",
619                  password="abcdefghijklmnop0123456789abcdef",
620                  scan_freq="2412")
621
622     hostapd.add_ap(apdev[1], params)
623     bssid2 = apdev[1]['bssid']
624
625     logger.info("Roam to AP2")
626     for sta in [ dev[1], dev[0], dev[2], wpas ]:
627         sta.dump_monitor()
628         sta.scan_for_bss(bssid2, freq="2412")
629         sta.request("ROAM " + bssid2)
630         ev = sta.wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
631         if ev is None:
632             raise Exception("EAP success timed out")
633         sta.wait_connected(timeout=10, error="Roaming timed out")
634
635     logger.info("Roam back to AP1")
636     for sta in [ dev[1], wpas, dev[0], dev[2] ]:
637         sta.dump_monitor()
638         sta.scan(freq="2412")
639         sta.dump_monitor()
640         sta.request("ROAM " + bssid)
641         sta.wait_connected(timeout=10, error="Roaming timed out")
642         sta.dump_monitor()
643
644     time.sleep(4)
645
646     logger.info("Roam back to AP2")
647     for sta in [ dev[1], wpas, dev[0], dev[2] ]:
648         sta.dump_monitor()
649         sta.scan(freq="2412")
650         sta.dump_monitor()
651         sta.request("ROAM " + bssid2)
652         sta.wait_connected(timeout=10, error="Roaming timed out")
653         sta.dump_monitor()
654
655 def test_pmksa_cache_opportunistic_multiple_sta(dev, apdev):
656     """Opportunistic PMKSA caching with multiple stations"""
657     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
658     params['okc'] = "1"
659     hostapd.add_ap(apdev[0], params)
660     bssid = apdev[0]['bssid']
661     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
662     wpas.interface_add("wlan5")
663     for sta in [ dev[0], dev[1], dev[2], wpas ]:
664         sta.connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
665                     eap="GPSK", identity="gpsk user",
666                     password="abcdefghijklmnop0123456789abcdef", okc=True,
667                     scan_freq="2412")
668
669     hostapd.add_ap(apdev[1], params)
670     bssid2 = apdev[1]['bssid']
671
672     logger.info("Roam to AP2")
673     for sta in [ dev[2], dev[0], wpas, dev[1] ]:
674         sta.dump_monitor()
675         sta.scan_for_bss(bssid2, freq="2412")
676         if "OK" not in sta.request("ROAM " + bssid2):
677             raise Exception("ROAM command failed")
678         ev = sta.wait_event(["CTRL-EVENT-EAP-STARTED",
679                              "CTRL-EVENT-CONNECTED"], timeout=10)
680         if ev is None:
681             raise Exception("Roaming with the AP timed out")
682         if "CTRL-EVENT-EAP-STARTED" in ev:
683             raise Exception("Unexpected EAP exchange")
684         pmksa2 = sta.get_pmksa(bssid2)
685         if pmksa2 is None:
686             raise Exception("No PMKSA cache entry created")
687
688     logger.info("Roam back to AP1")
689     for sta in [ dev[0], dev[1], dev[2], wpas ]:
690         sta.dump_monitor()
691         sta.scan_for_bss(bssid, freq="2412")
692         sta.request("ROAM " + bssid)
693         ev = sta.wait_event(["CTRL-EVENT-EAP-STARTED",
694                              "CTRL-EVENT-CONNECTED"], timeout=10)
695         if ev is None:
696             raise Exception("Roaming with the AP timed out")
697         if "CTRL-EVENT-EAP-STARTED" in ev:
698             raise Exception("Unexpected EAP exchange")
699
700 def test_pmksa_cache_preauth_oom(dev, apdev):
701     """RSN pre-authentication to generate PMKSA cache entry and OOM"""
702     try:
703         _test_pmksa_cache_preauth_oom(dev, apdev)
704     finally:
705         hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', 'ap-br0',
706                                        'down'])
707         hostapd.cmd_execute(apdev[0], ['brctl', 'delbr', 'ap-br0'])
708
709 def _test_pmksa_cache_preauth_oom(dev, apdev):
710     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
711     params['bridge'] = 'ap-br0'
712     hapd = hostapd.add_ap(apdev[0], params)
713     hostapd.cmd_execute(apdev[0], ['brctl', 'setfd', 'ap-br0', '0'])
714     hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', 'ap-br0', 'up'])
715     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
716                 password_hex="0123456789abcdef0123456789abcdef",
717                 bssid=apdev[0]['bssid'])
718
719     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
720     params['bridge'] = 'ap-br0'
721     params['rsn_preauth'] = '1'
722     params['rsn_preauth_interfaces'] = 'ap-br0'
723     hapd = hostapd.add_ap(apdev[1], params)
724     bssid1 = apdev[1]['bssid']
725
726     tests = [ (1, "rsn_preauth_receive"),
727               (2, "rsn_preauth_receive"),
728               (1, "rsn_preauth_send") ]
729     for test in tests:
730         with alloc_fail(hapd, test[0], test[1]):
731             dev[0].scan_for_bss(bssid1, freq="2412")
732             if "OK" not in dev[0].request("PREAUTH " + bssid1):
733                 raise Exception("PREAUTH failed")
734
735             success = False
736             count = 0
737             for i in range(50):
738                 time.sleep(0.1)
739                 pmksa = dev[0].get_pmksa(bssid1)
740                 if pmksa:
741                     success = True
742                     break
743                 state = hapd.request('GET_ALLOC_FAIL')
744                 if state.startswith('0:'):
745                     count += 1
746                     if count > 2:
747                         break
748             logger.info("PMKSA cache success: " + str(success))
749
750             dev[0].request("PMKSA_FLUSH")
751             dev[0].wait_disconnected()
752             dev[0].wait_connected()
753             dev[0].dump_monitor()
754
755 def test_pmksa_cache_size_limit(dev, apdev):
756     """PMKSA cache size limit in wpa_supplicant"""
757     try:
758         _test_pmksa_cache_size_limit(dev, apdev)
759     finally:
760         try:
761             hapd = hostapd.HostapdGlobal(apdev[0])
762             hapd.flush()
763             hapd.remove(apdev[0]['ifname'])
764         except:
765             pass
766         params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
767         bssid = apdev[0]['bssid']
768         params['bssid'] = bssid
769         hostapd.add_ap(apdev[0], params)
770
771 def _test_pmksa_cache_size_limit(dev, apdev):
772     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
773     id = dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
774                         eap="GPSK", identity="gpsk user",
775                         password="abcdefghijklmnop0123456789abcdef",
776                         scan_freq="2412", only_add_network=True)
777     for i in range(33):
778         bssid = apdev[0]['bssid'][0:15] + "%02x" % i
779         logger.info("Iteration with BSSID " + bssid)
780         params['bssid'] = bssid
781         hostapd.add_ap(apdev[0], params)
782         dev[0].request("BSS_FLUSH 0")
783         dev[0].scan_for_bss(bssid, freq=2412, only_new=True)
784         dev[0].select_network(id)
785         dev[0].wait_connected()
786         dev[0].request("DISCONNECT")
787         dev[0].wait_disconnected()
788         dev[0].dump_monitor()
789         entries = len(dev[0].request("PMKSA").splitlines()) - 1
790         if i == 32:
791             if entries != 32:
792                 raise Exception("Unexpected number of PMKSA entries after expected removal of the oldest entry")
793         elif i + 1 != entries:
794             raise Exception("Unexpected number of PMKSA entries")
795
796         hapd = hostapd.HostapdGlobal(apdev[0])
797         hapd.flush()
798         hapd.remove(apdev[0]['ifname'])
799
800 def test_pmksa_cache_preauth_timeout(dev, apdev):
801     """RSN pre-authentication timing out"""
802     try:
803         _test_pmksa_cache_preauth_timeout(dev, apdev)
804     finally:
805         dev[0].request("SET dot11RSNAConfigSATimeout 60")
806
807 def _test_pmksa_cache_preauth_timeout(dev, apdev):
808     dev[0].request("SET dot11RSNAConfigSATimeout 1")
809     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
810     hapd = hostapd.add_ap(apdev[0], params)
811     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
812                 password_hex="0123456789abcdef0123456789abcdef",
813                 bssid=apdev[0]['bssid'])
814     if "OK" not in dev[0].request("PREAUTH f2:11:22:33:44:55"):
815         raise Exception("PREAUTH failed")
816     ev = dev[0].wait_event(["RSN: pre-authentication with"], timeout=5)
817     if ev is None:
818         raise Exception("No timeout event seen")
819     if "timed out" not in ev:
820         raise Exception("Unexpected event: " + ev)
821
822 def test_pmksa_cache_preauth_wpas_oom(dev, apdev):
823     """RSN pre-authentication OOM in wpa_supplicant"""
824     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
825     hapd = hostapd.add_ap(apdev[0], params)
826     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
827                 password_hex="0123456789abcdef0123456789abcdef",
828                 bssid=apdev[0]['bssid'])
829     for i in range(1, 11):
830         with alloc_fail(dev[0], i, "rsn_preauth_init"):
831             res = dev[0].request("PREAUTH f2:11:22:33:44:55").strip()
832             logger.info("Iteration %d - PREAUTH command results: %s" % (i, res))
833             for j in range(10):
834                 state = dev[0].request('GET_ALLOC_FAIL')
835                 if state.startswith('0:'):
836                     break
837                 time.sleep(0.05)
838
839 def test_pmksa_cache_ctrl(dev, apdev):
840     """PMKSA cache control interface operations"""
841     params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache")
842     hapd = hostapd.add_ap(apdev[0], params)
843     bssid = apdev[0]['bssid']
844     addr = dev[0].own_addr()
845
846     dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP",
847                    eap="GPSK", identity="gpsk user",
848                    password="abcdefghijklmnop0123456789abcdef",
849                    scan_freq="2412")
850
851     pmksa_sta = dev[0].get_pmksa(bssid)
852     if pmksa_sta is None:
853         raise Exception("No PMKSA cache entry created on STA")
854     pmksa_ap = hapd.get_pmksa(addr)
855     if pmksa_ap is None:
856         raise Exception("No PMKSA cache entry created on AP")
857     if pmksa_sta['pmkid'] != pmksa_ap['pmkid']:
858         raise Exception("PMKID mismatch in PMKSA cache entries")
859
860     if "OK" not in hapd.request("PMKSA_FLUSH"):
861         raise Exception("PMKSA_FLUSH failed")
862     pmksa_ap = hapd.get_pmksa(addr)
863     if pmksa_ap is not None:
864         raise Exception("PMKSA cache entry was not removed on AP")
865
866     dev[0].request("DISCONNECT")
867     dev[0].wait_disconnected()
868     dev[0].request("RECONNECT")
869     dev[0].wait_connected()
870
871     pmksa_sta2 = dev[0].get_pmksa(bssid)
872     if pmksa_sta2 is None:
873         raise Exception("No PMKSA cache entry created on STA after reconnect")
874     pmksa_ap2 = hapd.get_pmksa(addr)
875     if pmksa_ap2 is None:
876         raise Exception("No PMKSA cache entry created on AP after reconnect")
877     if pmksa_sta2['pmkid'] != pmksa_ap2['pmkid']:
878         raise Exception("PMKID mismatch in PMKSA cache entries after reconnect")
879     if pmksa_sta2['pmkid'] == pmksa_sta['pmkid']:
880         raise Exception("PMKID did not change after reconnect")