tests: Additional coverage in mesh_sae_groups_invalid
[mech_eap.git] / tests / hwsim / test_wpas_mesh.py
1 # wpa_supplicant mesh mode tests
2 # Copyright (c) 2014, cozybit Inc.
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 os
10 import struct
11 import subprocess
12 import time
13
14 import hwsim_utils
15 import hostapd
16 from wpasupplicant import WpaSupplicant
17 from utils import HwsimSkip, alloc_fail, fail_test, wait_fail_trigger
18 from tshark import run_tshark
19
20 def check_mesh_support(dev, secure=False):
21     if "MESH" not in dev.get_capability("modes"):
22         raise HwsimSkip("Driver does not support mesh")
23     if secure and "SAE" not in dev.get_capability("auth_alg"):
24         raise HwsimSkip("SAE not supported")
25
26 def check_mesh_scan(dev, params, other_started=False, beacon_int=0):
27     if not other_started:
28         dev.dump_monitor()
29     id = dev.request("SCAN " + params)
30     if "FAIL" in id:
31         raise Exception("Failed to start scan")
32     id = int(id)
33
34     if other_started:
35         ev = dev.wait_event(["CTRL-EVENT-SCAN-STARTED"])
36         if ev is None:
37             raise Exception("Other scan did not start")
38         if "id=" + str(id) in ev:
39             raise Exception("Own scan id unexpectedly included in start event")
40
41         ev = dev.wait_event(["CTRL-EVENT-SCAN-RESULTS"])
42         if ev is None:
43             raise Exception("Other scan did not complete")
44         if "id=" + str(id) in ev:
45             raise Exception(
46                 "Own scan id unexpectedly included in completed event")
47
48     ev = dev.wait_event(["CTRL-EVENT-SCAN-STARTED"])
49     if ev is None:
50         raise Exception("Scan did not start")
51     if "id=" + str(id) not in ev:
52         raise Exception("Scan id not included in start event")
53
54     ev = dev.wait_event(["CTRL-EVENT-SCAN-RESULTS"])
55     if ev is None:
56         raise Exception("Scan did not complete")
57     if "id=" + str(id) not in ev:
58         raise Exception("Scan id not included in completed event")
59
60     res = dev.request("SCAN_RESULTS")
61
62     if res.find("[MESH]") < 0:
63         raise Exception("Scan did not contain a MESH network")
64
65     bssid = res.splitlines()[1].split(' ')[0]
66     bss = dev.get_bss(bssid)
67     if bss is None:
68         raise Exception("Could not get BSS entry for mesh")
69     if 'mesh_capability' not in bss:
70         raise Exception("mesh_capability missing from BSS entry")
71     if beacon_int:
72         if 'beacon_int' not in bss:
73             raise Exception("beacon_int missing from BSS entry")
74         if str(beacon_int) != bss['beacon_int']:
75             raise Exception("Unexpected beacon_int in BSS entry: " + bss['beacon_int'])
76
77 def check_mesh_group_added(dev):
78     ev = dev.wait_event(["MESH-GROUP-STARTED"])
79     if ev is None:
80         raise Exception("Test exception: Couldn't join mesh")
81
82
83 def check_mesh_group_removed(dev):
84     ev = dev.wait_event(["MESH-GROUP-REMOVED"])
85     if ev is None:
86         raise Exception("Test exception: Couldn't leave mesh")
87
88
89 def check_mesh_peer_connected(dev, timeout=10):
90     ev = dev.wait_event(["MESH-PEER-CONNECTED"], timeout=timeout)
91     if ev is None:
92         raise Exception("Test exception: Remote peer did not connect.")
93
94
95 def check_mesh_peer_disconnected(dev):
96     ev = dev.wait_event(["MESH-PEER-DISCONNECTED"])
97     if ev is None:
98         raise Exception("Test exception: Peer disconnect event not detected.")
99
100
101 def test_wpas_add_set_remove_support(dev):
102     """wpa_supplicant MESH add/set/remove network support"""
103     check_mesh_support(dev[0])
104     id = dev[0].add_network()
105     dev[0].set_network(id, "mode", "5")
106     dev[0].remove_network(id)
107
108 def add_open_mesh_network(dev, freq="2412", start=True, beacon_int=0,
109                           basic_rates=None, chwidth=0):
110     id = dev.add_network()
111     dev.set_network(id, "mode", "5")
112     dev.set_network_quoted(id, "ssid", "wpas-mesh-open")
113     dev.set_network(id, "key_mgmt", "NONE")
114     if freq:
115         dev.set_network(id, "frequency", freq)
116     if chwidth > 0:
117         dev.set_network(id, "max_oper_chwidth", str(chwidth))
118     if beacon_int:
119         dev.set_network(id, "beacon_int", str(beacon_int))
120     if basic_rates:
121         dev.set_network(id, "mesh_basic_rates", basic_rates)
122     if start:
123         dev.mesh_group_add(id)
124     return id
125
126 def test_wpas_mesh_group_added(dev):
127     """wpa_supplicant MESH group add"""
128     check_mesh_support(dev[0])
129     add_open_mesh_network(dev[0])
130
131     # Check for MESH-GROUP-STARTED event
132     check_mesh_group_added(dev[0])
133
134
135 def test_wpas_mesh_group_remove(dev):
136     """wpa_supplicant MESH group remove"""
137     check_mesh_support(dev[0])
138     add_open_mesh_network(dev[0])
139     # Check for MESH-GROUP-STARTED event
140     check_mesh_group_added(dev[0])
141     dev[0].mesh_group_remove()
142     # Check for MESH-GROUP-REMOVED event
143     check_mesh_group_removed(dev[0])
144     dev[0].mesh_group_remove()
145
146 def test_wpas_mesh_peer_connected(dev):
147     """wpa_supplicant MESH peer connected"""
148     check_mesh_support(dev[0])
149     add_open_mesh_network(dev[0], beacon_int=160)
150     add_open_mesh_network(dev[1], beacon_int=160)
151
152     # Check for mesh joined
153     check_mesh_group_added(dev[0])
154     check_mesh_group_added(dev[1])
155
156     # Check for peer connected
157     check_mesh_peer_connected(dev[0])
158     check_mesh_peer_connected(dev[1])
159
160
161 def test_wpas_mesh_peer_disconnected(dev):
162     """wpa_supplicant MESH peer disconnected"""
163     check_mesh_support(dev[0])
164     add_open_mesh_network(dev[0])
165     add_open_mesh_network(dev[1])
166
167     # Check for mesh joined
168     check_mesh_group_added(dev[0])
169     check_mesh_group_added(dev[1])
170
171     # Check for peer connected
172     check_mesh_peer_connected(dev[0])
173     check_mesh_peer_connected(dev[1])
174
175     # Remove group on dev 1
176     dev[1].mesh_group_remove()
177     # Device 0 should get a disconnection event
178     check_mesh_peer_disconnected(dev[0])
179
180
181 def test_wpas_mesh_mode_scan(dev):
182     """wpa_supplicant MESH scan support"""
183     check_mesh_support(dev[0])
184     add_open_mesh_network(dev[0])
185     add_open_mesh_network(dev[1], beacon_int=175)
186
187     # Check for mesh joined
188     check_mesh_group_added(dev[0])
189     check_mesh_group_added(dev[1])
190
191     # Check for Mesh scan
192     check_mesh_scan(dev[0], "use_id=1", beacon_int=175)
193
194 def test_wpas_mesh_open(dev, apdev):
195     """wpa_supplicant open MESH network connectivity"""
196     check_mesh_support(dev[0])
197     add_open_mesh_network(dev[0], freq="2462", basic_rates="60 120 240")
198     add_open_mesh_network(dev[1], freq="2462", basic_rates="60 120 240")
199
200     # Check for mesh joined
201     check_mesh_group_added(dev[0])
202     check_mesh_group_added(dev[1])
203
204     # Check for peer connected
205     check_mesh_peer_connected(dev[0])
206     check_mesh_peer_connected(dev[1])
207
208     # Test connectivity 0->1 and 1->0
209     hwsim_utils.test_connectivity(dev[0], dev[1])
210
211 def test_wpas_mesh_open_no_auto(dev, apdev):
212     """wpa_supplicant open MESH network connectivity"""
213     check_mesh_support(dev[0])
214     id = add_open_mesh_network(dev[0], start=False)
215     dev[0].set_network(id, "dot11MeshMaxRetries", "16")
216     dev[0].set_network(id, "dot11MeshRetryTimeout", "255")
217     dev[0].mesh_group_add(id)
218
219     id = add_open_mesh_network(dev[1], start=False)
220     dev[1].set_network(id, "no_auto_peer", "1")
221     dev[1].mesh_group_add(id)
222
223     # Check for mesh joined
224     check_mesh_group_added(dev[0])
225     check_mesh_group_added(dev[1])
226
227     # Check for peer connected
228     check_mesh_peer_connected(dev[0], timeout=30)
229     check_mesh_peer_connected(dev[1])
230
231     # Test connectivity 0->1 and 1->0
232     hwsim_utils.test_connectivity(dev[0], dev[1])
233
234 def add_mesh_secure_net(dev, psk=True):
235     id = dev.add_network()
236     dev.set_network(id, "mode", "5")
237     dev.set_network_quoted(id, "ssid", "wpas-mesh-sec")
238     dev.set_network(id, "key_mgmt", "SAE")
239     dev.set_network(id, "frequency", "2412")
240     if psk:
241         dev.set_network_quoted(id, "psk", "thisismypassphrase!")
242     return id
243
244 def test_wpas_mesh_secure(dev, apdev):
245     """wpa_supplicant secure MESH network connectivity"""
246     check_mesh_support(dev[0], secure=True)
247     dev[0].request("SET sae_groups ")
248     id = add_mesh_secure_net(dev[0])
249     dev[0].mesh_group_add(id)
250
251     dev[1].request("SET sae_groups ")
252     id = add_mesh_secure_net(dev[1])
253     dev[1].mesh_group_add(id)
254
255     # Check for mesh joined
256     check_mesh_group_added(dev[0])
257     check_mesh_group_added(dev[1])
258
259     # Check for peer connected
260     check_mesh_peer_connected(dev[0])
261     check_mesh_peer_connected(dev[1])
262
263     # Test connectivity 0->1 and 1->0
264     hwsim_utils.test_connectivity(dev[0], dev[1])
265
266 def test_wpas_mesh_secure_sae_group_mismatch(dev, apdev):
267     """wpa_supplicant secure MESH and SAE group mismatch"""
268     check_mesh_support(dev[0], secure=True)
269     addr0 = dev[0].p2p_interface_addr()
270     addr1 = dev[1].p2p_interface_addr()
271     addr2 = dev[2].p2p_interface_addr()
272
273     dev[0].request("SET sae_groups 19 25")
274     id = add_mesh_secure_net(dev[0])
275     dev[0].mesh_group_add(id)
276
277     dev[1].request("SET sae_groups 19")
278     id = add_mesh_secure_net(dev[1])
279     dev[1].mesh_group_add(id)
280
281     dev[2].request("SET sae_groups 26")
282     id = add_mesh_secure_net(dev[2])
283     dev[2].mesh_group_add(id)
284
285     check_mesh_group_added(dev[0])
286     check_mesh_group_added(dev[1])
287     check_mesh_group_added(dev[2])
288
289     ev = dev[0].wait_event(["MESH-PEER-CONNECTED"])
290     if ev is None:
291         raise Exception("Remote peer did not connect")
292     if addr1 not in ev:
293         raise Exception("Unexpected peer connected: " + ev)
294
295     ev = dev[1].wait_event(["MESH-PEER-CONNECTED"])
296     if ev is None:
297         raise Exception("Remote peer did not connect")
298     if addr0 not in ev:
299         raise Exception("Unexpected peer connected: " + ev)
300
301     ev = dev[2].wait_event(["MESH-PEER-CONNECTED"], timeout=1)
302     if ev is not None:
303         raise Exception("Unexpected peer connection at dev[2]: " + ev)
304
305     ev = dev[0].wait_event(["MESH-PEER-CONNECTED"], timeout=0.1)
306     if ev is not None:
307         raise Exception("Unexpected peer connection: " + ev)
308
309     ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.1)
310     if ev is not None:
311         raise Exception("Unexpected peer connection: " + ev)
312
313     dev[0].request("SET sae_groups ")
314     dev[1].request("SET sae_groups ")
315     dev[2].request("SET sae_groups ")
316
317 def test_wpas_mesh_secure_sae_group_negotiation(dev, apdev):
318     """wpa_supplicant secure MESH and SAE group negotiation"""
319     check_mesh_support(dev[0], secure=True)
320     addr0 = dev[0].own_addr()
321     addr1 = dev[1].own_addr()
322
323     #dev[0].request("SET sae_groups 21 20 25 26")
324     dev[0].request("SET sae_groups 25")
325     id = add_mesh_secure_net(dev[0])
326     dev[0].mesh_group_add(id)
327
328     dev[1].request("SET sae_groups 19 25")
329     id = add_mesh_secure_net(dev[1])
330     dev[1].mesh_group_add(id)
331
332     check_mesh_group_added(dev[0])
333     check_mesh_group_added(dev[1])
334
335     check_mesh_peer_connected(dev[0])
336     check_mesh_peer_connected(dev[1])
337
338     dev[0].request("SET sae_groups ")
339     dev[1].request("SET sae_groups ")
340
341 def test_wpas_mesh_secure_sae_missing_password(dev, apdev):
342     """wpa_supplicant secure MESH and missing SAE password"""
343     check_mesh_support(dev[0], secure=True)
344     id = add_mesh_secure_net(dev[0], psk=False)
345     dev[0].set_network(id, "psk", "8f20b381f9b84371d61b5080ad85cac3c61ab3ca9525be5b2d0f4da3d979187a")
346     dev[0].mesh_group_add(id)
347     ev = dev[0].wait_event(["MESH-GROUP-STARTED", "Could not join mesh"],
348                            timeout=5)
349     if ev is None:
350         raise Exception("Timeout on mesh start event")
351     if "MESH-GROUP-STARTED" in ev:
352         raise Exception("Unexpected mesh group start")
353     ev = dev[0].wait_event(["MESH-GROUP-STARTED"], timeout=0.1)
354     if ev is not None:
355         raise Exception("Unexpected mesh group start")
356
357 def test_wpas_mesh_secure_no_auto(dev, apdev):
358     """wpa_supplicant secure MESH network connectivity"""
359     check_mesh_support(dev[0], secure=True)
360     dev[0].request("SET sae_groups 19")
361     id = add_mesh_secure_net(dev[0])
362     dev[0].mesh_group_add(id)
363
364     dev[1].request("SET sae_groups 19")
365     id = add_mesh_secure_net(dev[1])
366     dev[1].set_network(id, "no_auto_peer", "1")
367     dev[1].mesh_group_add(id)
368
369     # Check for mesh joined
370     check_mesh_group_added(dev[0])
371     check_mesh_group_added(dev[1])
372
373     # Check for peer connected
374     check_mesh_peer_connected(dev[0], timeout=30)
375     check_mesh_peer_connected(dev[1])
376
377     # Test connectivity 0->1 and 1->0
378     hwsim_utils.test_connectivity(dev[0], dev[1])
379
380     dev[0].request("SET sae_groups ")
381     dev[1].request("SET sae_groups ")
382
383 def test_wpas_mesh_secure_dropped_frame(dev, apdev):
384     """Secure mesh network connectivity when the first plink Open is dropped"""
385     check_mesh_support(dev[0], secure=True)
386
387     dev[0].request("SET ext_mgmt_frame_handling 1")
388     dev[0].request("SET sae_groups ")
389     id = add_mesh_secure_net(dev[0])
390     dev[0].mesh_group_add(id)
391
392     dev[1].request("SET sae_groups ")
393     id = add_mesh_secure_net(dev[1])
394     dev[1].mesh_group_add(id)
395
396     # Check for mesh joined
397     check_mesh_group_added(dev[0])
398     check_mesh_group_added(dev[1])
399
400     # Drop the first Action frame (plink Open) to test unexpected order of
401     # Confirm/Open messages.
402     count = 0
403     while True:
404         count += 1
405         if count > 10:
406             raise Exception("Did not see Action frames")
407         rx_msg = dev[0].mgmt_rx()
408         if rx_msg is None:
409             raise Exception("MGMT-RX timeout")
410         if rx_msg['subtype'] == 13:
411             logger.info("Drop the first Action frame")
412             break
413         if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(rx_msg['freq'], rx_msg['datarate'], rx_msg['ssi_signal'], rx_msg['frame'].encode('hex'))):
414             raise Exception("MGMT_RX_PROCESS failed")
415
416     dev[0].request("SET ext_mgmt_frame_handling 0")
417
418     # Check for peer connected
419     check_mesh_peer_connected(dev[0])
420     check_mesh_peer_connected(dev[1])
421
422     # Test connectivity 0->1 and 1->0
423     hwsim_utils.test_connectivity(dev[0], dev[1])
424
425 def test_wpas_mesh_ctrl(dev):
426     """wpa_supplicant ctrl_iface mesh command error cases"""
427     check_mesh_support(dev[0])
428     if "FAIL" not in dev[0].request("MESH_GROUP_ADD 123"):
429         raise Exception("Unexpected MESH_GROUP_ADD success")
430     id = dev[0].add_network()
431     if "FAIL" not in dev[0].request("MESH_GROUP_ADD %d" % id):
432         raise Exception("Unexpected MESH_GROUP_ADD success")
433     dev[0].set_network(id, "mode", "5")
434     dev[0].set_network(id, "key_mgmt", "WPA-PSK")
435     if "FAIL" not in dev[0].request("MESH_GROUP_ADD %d" % id):
436         raise Exception("Unexpected MESH_GROUP_ADD success")
437
438     if "FAIL" not in dev[0].request("MESH_GROUP_REMOVE foo"):
439         raise Exception("Unexpected MESH_GROUP_REMOVE success")
440
441 def test_wpas_mesh_dynamic_interface(dev):
442     """wpa_supplicant mesh with dynamic interface"""
443     check_mesh_support(dev[0])
444     mesh0 = None
445     mesh1 = None
446     try:
447         mesh0 = dev[0].request("MESH_INTERFACE_ADD ifname=mesh0")
448         if "FAIL" in mesh0:
449             raise Exception("MESH_INTERFACE_ADD failed")
450         mesh1 = dev[1].request("MESH_INTERFACE_ADD")
451         if "FAIL" in mesh1:
452             raise Exception("MESH_INTERFACE_ADD failed")
453
454         wpas0 = WpaSupplicant(ifname=mesh0)
455         wpas1 = WpaSupplicant(ifname=mesh1)
456         logger.info(mesh0 + " address " + wpas0.get_status_field("address"))
457         logger.info(mesh1 + " address " + wpas1.get_status_field("address"))
458
459         add_open_mesh_network(wpas0)
460         add_open_mesh_network(wpas1)
461         check_mesh_group_added(wpas0)
462         check_mesh_group_added(wpas1)
463         check_mesh_peer_connected(wpas0)
464         check_mesh_peer_connected(wpas1)
465         hwsim_utils.test_connectivity(wpas0, wpas1)
466
467         # Must not allow MESH_GROUP_REMOVE on dynamic interface
468         if "FAIL" not in wpas0.request("MESH_GROUP_REMOVE " + mesh0):
469             raise Exception("Invalid MESH_GROUP_REMOVE accepted")
470         if "FAIL" not in wpas1.request("MESH_GROUP_REMOVE " + mesh1):
471             raise Exception("Invalid MESH_GROUP_REMOVE accepted")
472
473         # Must not allow MESH_GROUP_REMOVE on another radio interface
474         if "FAIL" not in wpas0.request("MESH_GROUP_REMOVE " + mesh1):
475             raise Exception("Invalid MESH_GROUP_REMOVE accepted")
476         if "FAIL" not in wpas1.request("MESH_GROUP_REMOVE " + mesh0):
477             raise Exception("Invalid MESH_GROUP_REMOVE accepted")
478
479         wpas0.remove_ifname()
480         wpas1.remove_ifname()
481
482         if "OK" not in dev[0].request("MESH_GROUP_REMOVE " + mesh0):
483             raise Exception("MESH_GROUP_REMOVE failed")
484         if "OK" not in dev[1].request("MESH_GROUP_REMOVE " + mesh1):
485             raise Exception("MESH_GROUP_REMOVE failed")
486
487         if "FAIL" not in dev[0].request("MESH_GROUP_REMOVE " + mesh0):
488             raise Exception("Invalid MESH_GROUP_REMOVE accepted")
489         if "FAIL" not in dev[1].request("MESH_GROUP_REMOVE " + mesh1):
490             raise Exception("Invalid MESH_GROUP_REMOVE accepted")
491
492         logger.info("Make sure another dynamic group can be added")
493         mesh0 = dev[0].request("MESH_INTERFACE_ADD ifname=mesh0")
494         if "FAIL" in mesh0:
495             raise Exception("MESH_INTERFACE_ADD failed")
496         mesh1 = dev[1].request("MESH_INTERFACE_ADD")
497         if "FAIL" in mesh1:
498             raise Exception("MESH_INTERFACE_ADD failed")
499
500         wpas0 = WpaSupplicant(ifname=mesh0)
501         wpas1 = WpaSupplicant(ifname=mesh1)
502         logger.info(mesh0 + " address " + wpas0.get_status_field("address"))
503         logger.info(mesh1 + " address " + wpas1.get_status_field("address"))
504
505         add_open_mesh_network(wpas0)
506         add_open_mesh_network(wpas1)
507         check_mesh_group_added(wpas0)
508         check_mesh_group_added(wpas1)
509         check_mesh_peer_connected(wpas0)
510         check_mesh_peer_connected(wpas1)
511         hwsim_utils.test_connectivity(wpas0, wpas1)
512     finally:
513         if mesh0:
514             dev[0].request("MESH_GROUP_REMOVE " + mesh0)
515         if mesh1:
516             dev[1].request("MESH_GROUP_REMOVE " + mesh1)
517
518 def test_wpas_mesh_max_peering(dev, apdev):
519     """Mesh max peering limit"""
520     check_mesh_support(dev[0])
521     try:
522         dev[0].request("SET max_peer_links 1")
523
524         # first, connect dev[0] and dev[1]
525         add_open_mesh_network(dev[0])
526         add_open_mesh_network(dev[1])
527         for i in range(2):
528             ev = dev[i].wait_event(["MESH-PEER-CONNECTED"])
529             if ev is None:
530                 raise Exception("dev%d did not connect with any peer" % i)
531
532         # add dev[2] which will try to connect with both dev[0] and dev[1],
533         # but can complete connection only with dev[1]
534         add_open_mesh_network(dev[2])
535         for i in range(1, 3):
536             ev = dev[i].wait_event(["MESH-PEER-CONNECTED"])
537             if ev is None:
538                 raise Exception("dev%d did not connect the second peer" % i)
539
540         ev = dev[0].wait_event(["MESH-PEER-CONNECTED"], timeout=1)
541         if ev is not None:
542             raise Exception("dev0 connection beyond max peering limit")
543
544         ev = dev[2].wait_event(["MESH-PEER-CONNECTED"], timeout=0.1)
545         if ev is not None:
546             raise Exception("dev2 reported unexpected peering: " + ev)
547
548         for i in range(3):
549             dev[i].mesh_group_remove()
550             check_mesh_group_removed(dev[i])
551     finally:
552         dev[0].request("SET max_peer_links 99")
553
554 def test_wpas_mesh_open_5ghz(dev, apdev):
555     """wpa_supplicant open MESH network on 5 GHz band"""
556     try:
557         _test_wpas_mesh_open_5ghz(dev, apdev)
558     finally:
559         subprocess.call(['iw', 'reg', 'set', '00'])
560         dev[0].flush_scan_cache()
561         dev[1].flush_scan_cache()
562
563 def _test_wpas_mesh_open_5ghz(dev, apdev):
564     check_mesh_support(dev[0])
565     subprocess.call(['iw', 'reg', 'set', 'US'])
566     for i in range(2):
567         for j in range(5):
568             ev = dev[i].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
569             if ev is None:
570                 raise Exception("No regdom change event")
571             if "alpha2=US" in ev:
572                 break
573         add_open_mesh_network(dev[i], freq="5180")
574
575     # Check for mesh joined
576     check_mesh_group_added(dev[0])
577     check_mesh_group_added(dev[1])
578
579     # Check for peer connected
580     check_mesh_peer_connected(dev[0])
581     check_mesh_peer_connected(dev[1])
582
583     # Test connectivity 0->1 and 1->0
584     hwsim_utils.test_connectivity(dev[0], dev[1])
585
586 def test_wpas_mesh_open_vht_80p80(dev, apdev):
587     """wpa_supplicant open MESH network on VHT 80+80 MHz channel"""
588     try:
589         _test_wpas_mesh_open_vht_80p80(dev, apdev)
590     finally:
591         subprocess.call(['iw', 'reg', 'set', '00'])
592         dev[0].flush_scan_cache()
593         dev[1].flush_scan_cache()
594
595 def _test_wpas_mesh_open_vht_80p80(dev, apdev):
596     check_mesh_support(dev[0])
597     subprocess.call(['iw', 'reg', 'set', 'US'])
598     for i in range(2):
599         for j in range(5):
600             ev = dev[i].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
601             if ev is None:
602                 raise Exception("No regdom change event")
603             if "alpha2=US" in ev:
604                 break
605         add_open_mesh_network(dev[i], freq="5180", chwidth=3)
606
607     # Check for mesh joined
608     check_mesh_group_added(dev[0])
609     check_mesh_group_added(dev[1])
610
611     # Check for peer connected
612     check_mesh_peer_connected(dev[0])
613     check_mesh_peer_connected(dev[1])
614
615     # Test connectivity 0->1 and 1->0
616     hwsim_utils.test_connectivity(dev[0], dev[1])
617
618     sig = dev[0].request("SIGNAL_POLL").splitlines()
619     if "WIDTH=80+80 MHz" not in sig:
620         raise Exception("Unexpected SIGNAL_POLL value(2): " + str(sig))
621     if "CENTER_FRQ1=5210" not in sig:
622         raise Exception("Unexpected SIGNAL_POLL value(3): " + str(sig))
623     if "CENTER_FRQ2=5775" not in sig:
624         raise Exception("Unexpected SIGNAL_POLL value(4): " + str(sig))
625
626     sig = dev[1].request("SIGNAL_POLL").splitlines()
627     if "WIDTH=80+80 MHz" not in sig:
628         raise Exception("Unexpected SIGNAL_POLL value(2b): " + str(sig))
629     if "CENTER_FRQ1=5210" not in sig:
630         raise Exception("Unexpected SIGNAL_POLL value(3b): " + str(sig))
631     if "CENTER_FRQ2=5775" not in sig:
632         raise Exception("Unexpected SIGNAL_POLL value(4b): " + str(sig))
633
634 def test_mesh_open_vht_160(dev, apdev):
635     """Open mesh network on VHT 160 MHz channel"""
636     try:
637         _test_mesh_open_vht_160(dev, apdev)
638     finally:
639         subprocess.call(['iw', 'reg', 'set', '00'])
640         dev[0].flush_scan_cache()
641         dev[1].flush_scan_cache()
642
643 def _test_mesh_open_vht_160(dev, apdev):
644     check_mesh_support(dev[0])
645     subprocess.call(['iw', 'reg', 'set', 'ZA'])
646     for i in range(2):
647         for j in range(5):
648             ev = dev[i].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
649             if ev is None:
650                 raise Exception("No regdom change event")
651             if "alpha2=ZA" in ev:
652                 break
653
654         cmd = subprocess.Popen(["iw", "reg", "get"], stdout=subprocess.PIPE)
655         reg = cmd.stdout.read()
656         if "@ 160)" not in reg:
657             raise HwsimSkip("160 MHz channel not supported in regulatory information")
658
659         add_open_mesh_network(dev[i], freq="5520", chwidth=2)
660
661     # Check for mesh joined
662     check_mesh_group_added(dev[0])
663     check_mesh_group_added(dev[1])
664
665     # Check for peer connected
666     check_mesh_peer_connected(dev[0])
667     check_mesh_peer_connected(dev[1])
668
669     # Test connectivity 0->1 and 1->0
670     hwsim_utils.test_connectivity(dev[0], dev[1])
671
672     sig = dev[0].request("SIGNAL_POLL").splitlines()
673     if "WIDTH=160 MHz" not in sig:
674         raise Exception("Unexpected SIGNAL_POLL value(2): " + str(sig))
675     if "FREQUENCY=5520" not in sig:
676         raise Exception("Unexpected SIGNAL_POLL value(3): " + str(sig))
677
678     sig = dev[1].request("SIGNAL_POLL").splitlines()
679     if "WIDTH=160 MHz" not in sig:
680         raise Exception("Unexpected SIGNAL_POLL value(2b): " + str(sig))
681     if "FREQUENCY=5520" not in sig:
682         raise Exception("Unexpected SIGNAL_POLL value(3b): " + str(sig))
683
684 def test_wpas_mesh_password_mismatch(dev, apdev):
685     """Mesh network and one device with mismatching password"""
686     check_mesh_support(dev[0], secure=True)
687     dev[0].request("SET sae_groups ")
688     id = add_mesh_secure_net(dev[0])
689     dev[0].mesh_group_add(id)
690
691     dev[1].request("SET sae_groups ")
692     id = add_mesh_secure_net(dev[1])
693     dev[1].mesh_group_add(id)
694
695     dev[2].request("SET sae_groups ")
696     id = add_mesh_secure_net(dev[2])
697     dev[2].set_network_quoted(id, "psk", "wrong password")
698     dev[2].mesh_group_add(id)
699
700     # The two peers with matching password need to be able to connect
701     check_mesh_group_added(dev[0])
702     check_mesh_group_added(dev[1])
703     check_mesh_peer_connected(dev[0])
704     check_mesh_peer_connected(dev[1])
705
706     ev = dev[2].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=20)
707     if ev is None:
708         raise Exception("dev2 did not report auth failure (1)")
709     ev = dev[2].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=20)
710     if ev is None:
711         raise Exception("dev2 did not report auth failure (2)")
712
713     count = 0
714     ev = dev[0].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=1)
715     if ev is None:
716         logger.info("dev0 did not report auth failure")
717     else:
718         if "addr=" + dev[2].own_addr() not in ev:
719             raise Exception("Unexpected peer address in dev0 event: " + ev)
720         count += 1
721
722     ev = dev[1].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=1)
723     if ev is None:
724         logger.info("dev1 did not report auth failure")
725     else:
726         if "addr=" + dev[2].own_addr() not in ev:
727             raise Exception("Unexpected peer address in dev1 event: " + ev)
728         count += 1
729
730     hwsim_utils.test_connectivity(dev[0], dev[1])
731
732     for i in range(2):
733         try:
734             hwsim_utils.test_connectivity(dev[i], dev[2], timeout=1)
735             raise Exception("Data connectivity test passed unexpectedly")
736         except Exception, e:
737             if "data delivery failed" not in str(e):
738                 raise
739
740     if count == 0:
741         raise Exception("Neither dev0 nor dev1 reported auth failure")
742
743 def test_wpas_mesh_password_mismatch_retry(dev, apdev, params):
744     """Mesh password mismatch and retry [long]"""
745     if not params['long']:
746         raise HwsimSkip("Skip test case with long duration due to --long not specified")
747     check_mesh_support(dev[0], secure=True)
748     dev[0].request("SET sae_groups ")
749     id = add_mesh_secure_net(dev[0])
750     dev[0].mesh_group_add(id)
751
752     dev[1].request("SET sae_groups ")
753     id = add_mesh_secure_net(dev[1])
754     dev[1].set_network_quoted(id, "psk", "wrong password")
755     dev[1].mesh_group_add(id)
756
757     # Check for mesh joined
758     check_mesh_group_added(dev[0])
759     check_mesh_group_added(dev[1])
760
761     for i in range(4):
762         ev = dev[0].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=20)
763         if ev is None:
764             raise Exception("dev0 did not report auth failure (%d)" % i)
765         ev = dev[1].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=20)
766         if ev is None:
767             raise Exception("dev1 did not report auth failure (%d)" % i)
768
769     ev = dev[0].wait_event(["MESH-SAE-AUTH-BLOCKED"], timeout=10)
770     if ev is None:
771         raise Exception("dev0 did not report auth blocked")
772     ev = dev[1].wait_event(["MESH-SAE-AUTH-BLOCKED"], timeout=10)
773     if ev is None:
774         raise Exception("dev1 did not report auth blocked")
775
776 def test_mesh_wpa_auth_init_oom(dev, apdev):
777     """Secure mesh network setup failing due to wpa_init() OOM"""
778     check_mesh_support(dev[0], secure=True)
779     dev[0].request("SET sae_groups ")
780     with alloc_fail(dev[0], 1, "wpa_init"):
781         id = add_mesh_secure_net(dev[0])
782         dev[0].mesh_group_add(id)
783         ev = dev[0].wait_event(["MESH-GROUP-STARTED"], timeout=0.2)
784         if ev is not None:
785             raise Exception("Unexpected mesh group start during OOM")
786
787 def test_mesh_wpa_init_fail(dev, apdev):
788     """Secure mesh network setup local failure"""
789     check_mesh_support(dev[0], secure=True)
790     dev[0].request("SET sae_groups ")
791
792     with fail_test(dev[0], 1, "os_get_random;=__mesh_rsn_auth_init"):
793         id = add_mesh_secure_net(dev[0])
794         dev[0].mesh_group_add(id)
795         wait_fail_trigger(dev[0], "GET_FAIL")
796
797     dev[0].dump_monitor()
798     with alloc_fail(dev[0], 1, "mesh_rsn_auth_init"):
799         id = add_mesh_secure_net(dev[0])
800         dev[0].mesh_group_add(id)
801         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
802
803     dev[0].dump_monitor()
804     with fail_test(dev[0], 1, "os_get_random;mesh_rsn_init_ampe_sta"):
805         id = add_mesh_secure_net(dev[0])
806         dev[0].mesh_group_add(id)
807         dev[1].request("SET sae_groups ")
808         id = add_mesh_secure_net(dev[1])
809         dev[1].mesh_group_add(id)
810         wait_fail_trigger(dev[0], "GET_FAIL")
811
812 def test_wpas_mesh_reconnect(dev, apdev):
813     """Secure mesh network plink counting during reconnection"""
814     check_mesh_support(dev[0])
815     try:
816         _test_wpas_mesh_reconnect(dev)
817     finally:
818         dev[0].request("SET max_peer_links 99")
819
820 def _test_wpas_mesh_reconnect(dev):
821     dev[0].request("SET max_peer_links 2")
822     dev[0].request("SET sae_groups ")
823     id = add_mesh_secure_net(dev[0])
824     dev[0].set_network(id, "beacon_int", "100")
825     dev[0].mesh_group_add(id)
826     dev[1].request("SET sae_groups ")
827     id = add_mesh_secure_net(dev[1])
828     dev[1].mesh_group_add(id)
829     check_mesh_group_added(dev[0])
830     check_mesh_group_added(dev[1])
831     check_mesh_peer_connected(dev[0])
832     check_mesh_peer_connected(dev[1])
833
834     for i in range(3):
835         # Drop incoming management frames to avoid handling link close
836         dev[0].request("SET ext_mgmt_frame_handling 1")
837         dev[1].mesh_group_remove()
838         check_mesh_group_removed(dev[1])
839         dev[1].request("FLUSH")
840         dev[0].request("SET ext_mgmt_frame_handling 0")
841         id = add_mesh_secure_net(dev[1])
842         dev[1].mesh_group_add(id)
843         check_mesh_group_added(dev[1])
844         check_mesh_peer_connected(dev[1])
845         dev[0].dump_monitor()
846         dev[1].dump_monitor()
847
848 def test_wpas_mesh_gate_forwarding(dev, apdev, p):
849     """Mesh forwards traffic to unknown sta to mesh gates"""
850     addr0 = dev[0].own_addr()
851     addr1 = dev[1].own_addr()
852     addr2 = dev[2].own_addr()
853     external_sta = '02:11:22:33:44:55'
854
855     # start 3 node connected mesh
856     check_mesh_support(dev[0])
857     for i in range(3):
858         add_open_mesh_network(dev[i])
859         check_mesh_group_added(dev[i])
860     for i in range(3):
861         check_mesh_peer_connected(dev[i])
862
863     hwsim_utils.test_connectivity(dev[0], dev[1])
864     hwsim_utils.test_connectivity(dev[1], dev[2])
865     hwsim_utils.test_connectivity(dev[0], dev[2])
866
867     # dev0 and dev1 are mesh gates
868     subprocess.call(['iw', 'dev', dev[0].ifname, 'set', 'mesh_param',
869                      'mesh_gate_announcements=1'])
870     subprocess.call(['iw', 'dev', dev[1].ifname, 'set', 'mesh_param',
871                      'mesh_gate_announcements=1'])
872
873     # wait for gate announcement frames
874     time.sleep(1)
875
876     # data frame from dev2 -> external sta should be sent to both gates
877     dev[2].request("DATA_TEST_CONFIG 1")
878     dev[2].request("DATA_TEST_TX {} {} 0".format(external_sta, addr2))
879     dev[2].request("DATA_TEST_CONFIG 0")
880
881     capfile = os.path.join(p['logdir'], "hwsim0.pcapng")
882     filt = "wlan.sa==%s && wlan_mgt.fixed.mesh_addr5==%s" % (addr2,
883                                                              external_sta)
884     for i in range(15):
885         da = run_tshark(capfile, filt, [ "wlan.da" ])
886         if addr0 in da and addr1 in da:
887             logger.debug("Frames seen in tshark iteration %d" % i)
888             break
889         time.sleep(0.3)
890
891     if addr0 not in da:
892         raise Exception("Frame to gate %s not observed" % addr0)
893     if addr1 not in da:
894         raise Exception("Frame to gate %s not observed" % addr1)
895
896 def test_wpas_mesh_pmksa_caching(dev, apdev):
897     """Secure mesh network and PMKSA caching"""
898     check_mesh_support(dev[0], secure=True)
899     dev[0].request("SET sae_groups ")
900     id = add_mesh_secure_net(dev[0])
901     dev[0].mesh_group_add(id)
902
903     dev[1].request("SET sae_groups ")
904     id = add_mesh_secure_net(dev[1])
905     dev[1].mesh_group_add(id)
906
907     # Check for mesh joined
908     check_mesh_group_added(dev[0])
909     check_mesh_group_added(dev[1])
910
911     # Check for peer connected
912     check_mesh_peer_connected(dev[0])
913     check_mesh_peer_connected(dev[1])
914
915     addr0 = dev[0].own_addr()
916     addr1 = dev[1].own_addr()
917     pmksa0 = dev[0].get_pmksa(addr1)
918     pmksa1 = dev[1].get_pmksa(addr0)
919     if pmksa0 is None or pmksa1 is None:
920         raise Exception("No PMKSA cache entry created")
921     if pmksa0['pmkid'] != pmksa1['pmkid']:
922         raise Exception("PMKID mismatch in PMKSA cache entries")
923
924     if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
925         raise Exception("Failed to remove peer")
926     pmksa0b = dev[0].get_pmksa(addr1)
927     if pmksa0b is None:
928         raise Exception("PMKSA cache entry not maintained")
929     time.sleep(0.1)
930
931     if "FAIL" not in dev[0].request("MESH_PEER_ADD " + addr1):
932         raise Exception("MESH_PEER_ADD unexpectedly succeeded in no_auto_peer=0 case")
933
934 def test_wpas_mesh_pmksa_caching2(dev, apdev):
935     """Secure mesh network and PMKSA caching with no_auto_peer=1"""
936     check_mesh_support(dev[0], secure=True)
937     addr0 = dev[0].own_addr()
938     addr1 = dev[1].own_addr()
939     dev[0].request("SET sae_groups ")
940     id = add_mesh_secure_net(dev[0])
941     dev[0].set_network(id, "no_auto_peer", "1")
942     dev[0].mesh_group_add(id)
943
944     dev[1].request("SET sae_groups ")
945     id = add_mesh_secure_net(dev[1])
946     dev[1].set_network(id, "no_auto_peer", "1")
947     dev[1].mesh_group_add(id)
948
949     # Check for mesh joined
950     check_mesh_group_added(dev[0])
951     check_mesh_group_added(dev[1])
952
953     # Check for peer connected
954     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
955     if ev is None:
956         raise Exception("Missing no-initiate message")
957     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
958         raise Exception("MESH_PEER_ADD failed")
959     check_mesh_peer_connected(dev[0])
960     check_mesh_peer_connected(dev[1])
961
962     pmksa0 = dev[0].get_pmksa(addr1)
963     pmksa1 = dev[1].get_pmksa(addr0)
964     if pmksa0 is None or pmksa1 is None:
965         raise Exception("No PMKSA cache entry created")
966     if pmksa0['pmkid'] != pmksa1['pmkid']:
967         raise Exception("PMKID mismatch in PMKSA cache entries")
968
969     if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
970         raise Exception("Failed to remove peer")
971     pmksa0b = dev[0].get_pmksa(addr1)
972     if pmksa0b is None:
973         raise Exception("PMKSA cache entry not maintained")
974
975     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
976     if ev is None:
977         raise Exception("Missing no-initiate message (2)")
978     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
979         raise Exception("MESH_PEER_ADD failed (2)")
980     check_mesh_peer_connected(dev[0])
981     check_mesh_peer_connected(dev[1])
982
983     pmksa0c = dev[0].get_pmksa(addr1)
984     pmksa1c = dev[1].get_pmksa(addr0)
985     if pmksa0c is None or pmksa1c is None:
986         raise Exception("No PMKSA cache entry created (2)")
987     if pmksa0c['pmkid'] != pmksa1c['pmkid']:
988         raise Exception("PMKID mismatch in PMKSA cache entries")
989     if pmksa0['pmkid'] != pmksa0c['pmkid']:
990         raise Exception("PMKID changed")
991
992     hwsim_utils.test_connectivity(dev[0], dev[1])
993
994 def test_wpas_mesh_pmksa_caching_no_match(dev, apdev):
995     """Secure mesh network and PMKSA caching with no PMKID match"""
996     check_mesh_support(dev[0], secure=True)
997     addr0 = dev[0].own_addr()
998     addr1 = dev[1].own_addr()
999     dev[0].request("SET sae_groups ")
1000     id = add_mesh_secure_net(dev[0])
1001     dev[0].set_network(id, "no_auto_peer", "1")
1002     dev[0].mesh_group_add(id)
1003
1004     dev[1].request("SET sae_groups ")
1005     id = add_mesh_secure_net(dev[1])
1006     dev[1].set_network(id, "no_auto_peer", "1")
1007     dev[1].mesh_group_add(id)
1008
1009     # Check for mesh joined
1010     check_mesh_group_added(dev[0])
1011     check_mesh_group_added(dev[1])
1012
1013     # Check for peer connected
1014     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1015     if ev is None:
1016         raise Exception("Missing no-initiate message")
1017     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1018         raise Exception("MESH_PEER_ADD failed")
1019     check_mesh_peer_connected(dev[0])
1020     check_mesh_peer_connected(dev[1])
1021
1022     pmksa0 = dev[0].get_pmksa(addr1)
1023     pmksa1 = dev[1].get_pmksa(addr0)
1024     if pmksa0 is None or pmksa1 is None:
1025         raise Exception("No PMKSA cache entry created")
1026     if pmksa0['pmkid'] != pmksa1['pmkid']:
1027         raise Exception("PMKID mismatch in PMKSA cache entries")
1028
1029     if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1030         raise Exception("Failed to remove peer")
1031
1032     if "OK" not in dev[1].request("PMKSA_FLUSH"):
1033         raise Exception("Failed to flush PMKSA cache")
1034
1035     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1036     if ev is None:
1037         raise Exception("Missing no-initiate message (2)")
1038     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1039         raise Exception("MESH_PEER_ADD failed (2)")
1040     check_mesh_peer_connected(dev[0])
1041     check_mesh_peer_connected(dev[1])
1042
1043     pmksa0c = dev[0].get_pmksa(addr1)
1044     pmksa1c = dev[1].get_pmksa(addr0)
1045     if pmksa0c is None or pmksa1c is None:
1046         raise Exception("No PMKSA cache entry created (2)")
1047     if pmksa0c['pmkid'] != pmksa1c['pmkid']:
1048         raise Exception("PMKID mismatch in PMKSA cache entries")
1049     if pmksa0['pmkid'] == pmksa0c['pmkid']:
1050         raise Exception("PMKID did not change")
1051
1052     hwsim_utils.test_connectivity(dev[0], dev[1])
1053
1054 def test_mesh_pmksa_caching_oom(dev, apdev):
1055     """Secure mesh network and PMKSA caching failing due to OOM"""
1056     check_mesh_support(dev[0], secure=True)
1057     addr0 = dev[0].own_addr()
1058     addr1 = dev[1].own_addr()
1059     dev[0].request("SET sae_groups ")
1060     id = add_mesh_secure_net(dev[0])
1061     dev[0].set_network(id, "no_auto_peer", "1")
1062     dev[0].mesh_group_add(id)
1063
1064     dev[1].request("SET sae_groups ")
1065     id = add_mesh_secure_net(dev[1])
1066     dev[1].set_network(id, "no_auto_peer", "1")
1067     dev[1].mesh_group_add(id)
1068
1069     # Check for mesh joined
1070     check_mesh_group_added(dev[0])
1071     check_mesh_group_added(dev[1])
1072
1073     # Check for peer connected
1074     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1075     if ev is None:
1076         raise Exception("Missing no-initiate message")
1077     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1078         raise Exception("MESH_PEER_ADD failed")
1079     check_mesh_peer_connected(dev[0])
1080     check_mesh_peer_connected(dev[1])
1081
1082     if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1083         raise Exception("Failed to remove peer")
1084     pmksa0b = dev[0].get_pmksa(addr1)
1085     if pmksa0b is None:
1086         raise Exception("PMKSA cache entry not maintained")
1087
1088     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1089     if ev is None:
1090         raise Exception("Missing no-initiate message (2)")
1091
1092     with alloc_fail(dev[0], 1, "wpa_auth_sta_init;mesh_rsn_auth_sae_sta"):
1093         if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1094             raise Exception("MESH_PEER_ADD failed (2)")
1095         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
1096
1097 def test_mesh_oom(dev, apdev):
1098     """Mesh network setup failing due to OOM"""
1099     check_mesh_support(dev[0], secure=True)
1100     dev[0].request("SET sae_groups ")
1101
1102     with alloc_fail(dev[0], 1, "mesh_config_create"):
1103         add_open_mesh_network(dev[0])
1104         ev = dev[0].wait_event(["Failed to init mesh"])
1105         if ev is None:
1106             raise Exception("Init failure not reported")
1107
1108     with alloc_fail(dev[0], 4, "=wpa_supplicant_mesh_init"):
1109         add_open_mesh_network(dev[0], basic_rates="60 120 240")
1110         ev = dev[0].wait_event(["Failed to init mesh"])
1111         if ev is None:
1112             raise Exception("Init failure not reported")
1113
1114     for i in range(1, 66):
1115         dev[0].dump_monitor()
1116         logger.info("Test instance %d" % i)
1117         try:
1118             with alloc_fail(dev[0], i, "wpa_supplicant_mesh_init"):
1119                 add_open_mesh_network(dev[0])
1120                 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
1121                 ev = dev[0].wait_event(["Failed to init mesh",
1122                                         "MESH-GROUP-STARTED"])
1123                 if ev is None:
1124                     raise Exception("Init failure not reported")
1125         except Exception, e:
1126             if i < 15:
1127                 raise
1128             logger.info("Ignore no-oom for i=%d" % i)
1129
1130     with alloc_fail(dev[0], 5, "=wpa_supplicant_mesh_init"):
1131         id = add_mesh_secure_net(dev[0])
1132         dev[0].mesh_group_add(id)
1133         ev = dev[0].wait_event(["Failed to init mesh"])
1134         if ev is None:
1135             raise Exception("Init failure not reported")
1136
1137 def test_mesh_add_interface_oom(dev):
1138     """wpa_supplicant mesh with dynamic interface addition failing"""
1139     check_mesh_support(dev[0])
1140     for i in range(1, 3):
1141         mesh = None
1142         try:
1143             with alloc_fail(dev[0], i, "wpas_mesh_add_interface"):
1144                 mesh = dev[0].request("MESH_INTERFACE_ADD").strip()
1145         finally:
1146             if mesh and mesh != "FAIL":
1147                 dev[0].request("MESH_GROUP_REMOVE " + mesh)
1148
1149 def test_mesh_scan_oom(dev):
1150     """wpa_supplicant mesh scan results and OOM"""
1151     check_mesh_support(dev[0])
1152     add_open_mesh_network(dev[0])
1153     check_mesh_group_added(dev[0])
1154     for i in range(5):
1155         dev[1].scan(freq="2412")
1156         res = dev[1].request("SCAN_RESULTS")
1157         if "[MESH]" in res:
1158             break
1159     for r in res.splitlines():
1160         if "[MESH]" in r:
1161             break
1162     bssid = r.split('\t')[0]
1163
1164     bss = dev[1].get_bss(bssid)
1165     if bss is None:
1166         raise Exception("Could not get BSS entry for mesh")
1167
1168     for i in range(1, 3):
1169         with alloc_fail(dev[1], i, "mesh_attr_text"):
1170             bss = dev[1].get_bss(bssid)
1171             if bss is not None:
1172                 raise Exception("Unexpected BSS result during OOM")
1173
1174 def test_mesh_drv_fail(dev, apdev):
1175     """Mesh network setup failing due to driver command failure"""
1176     check_mesh_support(dev[0], secure=True)
1177     dev[0].request("SET sae_groups ")
1178
1179     with fail_test(dev[0], 1, "nl80211_join_mesh"):
1180         add_open_mesh_network(dev[0])
1181         ev = dev[0].wait_event(["mesh join error"])
1182         if ev is None:
1183             raise Exception("Join failure not reported")
1184
1185     dev[0].dump_monitor()
1186     with fail_test(dev[0], 1, "wpa_driver_nl80211_if_add"):
1187         if "FAIL" not in dev[0].request("MESH_INTERFACE_ADD").strip():
1188             raise Exception("Interface added unexpectedly")
1189
1190     dev[0].dump_monitor()
1191     with fail_test(dev[0], 1, "wpa_driver_nl80211_init_mesh"):
1192         add_open_mesh_network(dev[0])
1193         ev = dev[0].wait_event(["Could not join mesh"])
1194         if ev is None:
1195             raise Exception("Join failure not reported")
1196
1197 def test_mesh_sae_groups_invalid(dev, apdev):
1198     """Mesh with invalid SAE group configuration"""
1199     check_mesh_support(dev[0], secure=True)
1200
1201     dev[0].request("SET sae_groups 25")
1202     id = add_mesh_secure_net(dev[0])
1203     dev[0].mesh_group_add(id)
1204
1205     dev[1].request("SET sae_groups 123 122 121")
1206     id = add_mesh_secure_net(dev[1])
1207     dev[1].mesh_group_add(id)
1208
1209     check_mesh_group_added(dev[0])
1210     check_mesh_group_added(dev[1])
1211
1212     ev = dev[0].wait_event(["new peer notification"], timeout=10)
1213     if ev is None:
1214         raise Exception("dev[0] did not see peer")
1215     ev = dev[1].wait_event(["new peer notification"], timeout=10)
1216     if ev is None:
1217         raise Exception("dev[1] did not see peer")
1218
1219     ev = dev[0].wait_event(["MESH-PEER-CONNECTED"], timeout=0.1)
1220     if ev is not None:
1221         raise Exception("Unexpected connection(0)")
1222
1223     ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
1224     if ev is not None:
1225         raise Exception("Unexpected connection(1)")
1226
1227     # Additional coverage in mesh_rsn_sae_group() with non-zero
1228     # wpa_s->mesh_rsn->sae_group_index.
1229     dev[0].dump_monitor()
1230     dev[1].dump_monitor()
1231     id = add_mesh_secure_net(dev[2])
1232     dev[2].mesh_group_add(id)
1233     check_mesh_group_added(dev[2])
1234     check_mesh_peer_connected(dev[0])
1235     check_mesh_peer_connected(dev[2])
1236     ev = dev[1].wait_event(["new peer notification"], timeout=10)
1237     if ev is None:
1238         raise Exception("dev[1] did not see peer(2)")
1239     dev[0].dump_monitor()
1240     dev[1].dump_monitor()
1241     dev[2].dump_monitor()
1242
1243     dev[0].request("SET sae_groups ")
1244     dev[1].request("SET sae_groups ")
1245
1246 def test_mesh_sae_failure(dev, apdev):
1247     """Mesh and local SAE failures"""
1248     check_mesh_support(dev[0], secure=True)
1249
1250     dev[0].request("SET sae_groups ")
1251     dev[1].request("SET sae_groups ")
1252
1253     funcs = [ (1, "=mesh_rsn_auth_sae_sta", True),
1254               (1, "mesh_rsn_build_sae_commit;mesh_rsn_auth_sae_sta", False),
1255               (1, "auth_sae_init_committed;mesh_rsn_auth_sae_sta", True),
1256               (1, "=mesh_rsn_protect_frame", True),
1257               (2, "=mesh_rsn_protect_frame", True),
1258               (1, "aes_siv_encrypt;mesh_rsn_protect_frame", True),
1259               (1, "=mesh_rsn_process_ampe", True),
1260               (1, "aes_siv_decrypt;mesh_rsn_process_ampe", True) ]
1261     for count, func, success in funcs:
1262         id = add_mesh_secure_net(dev[0])
1263         dev[0].mesh_group_add(id)
1264
1265         with alloc_fail(dev[1], count, func):
1266             id = add_mesh_secure_net(dev[1])
1267             dev[1].mesh_group_add(id)
1268             check_mesh_group_added(dev[0])
1269             check_mesh_group_added(dev[1])
1270             if success:
1271                 # retry is expected to work
1272                 check_mesh_peer_connected(dev[0])
1273                 check_mesh_peer_connected(dev[1])
1274             else:
1275                 wait_fail_trigger(dev[1], "GET_ALLOC_FAIL")
1276         dev[0].mesh_group_remove()
1277         dev[1].mesh_group_remove()
1278         check_mesh_group_removed(dev[0])
1279         check_mesh_group_removed(dev[1])
1280
1281 def test_mesh_failure(dev, apdev):
1282     """Mesh and local failures"""
1283     check_mesh_support(dev[0])
1284
1285     funcs = [ (1, "ap_sta_add;mesh_mpm_add_peer", True),
1286               (1, "wpabuf_alloc;mesh_mpm_send_plink_action", True) ]
1287     for count, func, success in funcs:
1288         add_open_mesh_network(dev[0])
1289
1290         with alloc_fail(dev[1], count, func):
1291             add_open_mesh_network(dev[1])
1292             check_mesh_group_added(dev[0])
1293             check_mesh_group_added(dev[1])
1294             if success:
1295                 # retry is expected to work
1296                 check_mesh_peer_connected(dev[0])
1297                 check_mesh_peer_connected(dev[1])
1298             else:
1299                 wait_fail_trigger(dev[1], "GET_ALLOC_FAIL")
1300         dev[0].mesh_group_remove()
1301         dev[1].mesh_group_remove()
1302         check_mesh_group_removed(dev[0])
1303         check_mesh_group_removed(dev[1])
1304
1305     funcs = [ (1, "mesh_mpm_init_link", True) ]
1306     for count, func, success in funcs:
1307         add_open_mesh_network(dev[0])
1308
1309         with fail_test(dev[1], count, func):
1310             add_open_mesh_network(dev[1])
1311             check_mesh_group_added(dev[0])
1312             check_mesh_group_added(dev[1])
1313             if success:
1314                 # retry is expected to work
1315                 check_mesh_peer_connected(dev[0])
1316                 check_mesh_peer_connected(dev[1])
1317             else:
1318                 wait_fail_trigger(dev[1], "GET_FAIL")
1319         dev[0].mesh_group_remove()
1320         dev[1].mesh_group_remove()
1321         check_mesh_group_removed(dev[0])
1322         check_mesh_group_removed(dev[1])
1323
1324 def test_mesh_invalid_frequency(dev, apdev):
1325     """Mesh and invalid frequency configuration"""
1326     check_mesh_support(dev[0])
1327     add_open_mesh_network(dev[0], freq=None)
1328     ev = dev[0].wait_event(["MESH-GROUP-STARTED",
1329                             "Could not join mesh"])
1330     if ev is None or "Could not join mesh" not in ev:
1331         raise Exception("Mesh join failure not reported")
1332     dev[0].request("REMOVE_NETWORK all")
1333
1334     add_open_mesh_network(dev[0], freq="2413")
1335     ev = dev[0].wait_event(["MESH-GROUP-STARTED",
1336                             "Could not join mesh"])
1337     if ev is None or "Could not join mesh" not in ev:
1338         raise Exception("Mesh join failure not reported")
1339
1340 def test_mesh_default_beacon_int(dev, apdev):
1341     """Mesh and default beacon interval"""
1342     check_mesh_support(dev[0])
1343     try:
1344         dev[0].request("SET beacon_int 200")
1345         add_open_mesh_network(dev[0])
1346         check_mesh_group_added(dev[0])
1347     finally:
1348         dev[0].request("SET beacon_int 0")
1349
1350 def test_mesh_scan_parse_error(dev, apdev):
1351     """Mesh scan element parse error"""
1352     check_mesh_support(dev[0])
1353     params = { "ssid": "open",
1354                "beacon_int": "2000" }
1355     hapd = hostapd.add_ap(apdev[0], params)
1356     bssid = apdev[0]['bssid']
1357     hapd.set('vendor_elements', 'dd0201')
1358     for i in range(10):
1359         dev[0].scan(freq=2412)
1360         if bssid in dev[0].request("SCAN_RESULTS"):
1361             break
1362     # This will fail in IE parsing due to the truncated IE in the Probe
1363     # Response frame.
1364     bss = dev[0].request("BSS " + bssid)
1365
1366 def test_mesh_missing_mic(dev, apdev):
1367     """Secure mesh network and missing MIC"""
1368     check_mesh_support(dev[0], secure=True)
1369
1370     dev[0].request("SET ext_mgmt_frame_handling 1")
1371     dev[0].request("SET sae_groups ")
1372     id = add_mesh_secure_net(dev[0])
1373     dev[0].mesh_group_add(id)
1374
1375     dev[1].request("SET sae_groups ")
1376     id = add_mesh_secure_net(dev[1])
1377     dev[1].mesh_group_add(id)
1378
1379     # Check for mesh joined
1380     check_mesh_group_added(dev[0])
1381     check_mesh_group_added(dev[1])
1382
1383     count = 0
1384     remove_mic = True
1385     while True:
1386         count += 1
1387         if count > 15:
1388             raise Exception("Did not see Action frames")
1389         rx_msg = dev[0].mgmt_rx()
1390         if rx_msg is None:
1391             raise Exception("MGMT-RX timeout")
1392         if rx_msg['subtype'] == 13:
1393             payload = rx_msg['payload']
1394             frame = rx_msg['frame']
1395             (categ, action) = struct.unpack('BB', payload[0:2])
1396             if categ == 15 and action == 1 and remove_mic:
1397                 # Mesh Peering Open
1398                 pos = frame.find('\x8c\x10')
1399                 if not pos:
1400                     raise Exception("Could not find MIC element")
1401                 logger.info("Found MIC at %d" % pos)
1402                 # Remove MIC
1403                 rx_msg['frame'] = frame[0:pos]
1404                 remove_mic = False
1405         if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(rx_msg['freq'], rx_msg['datarate'], rx_msg['ssi_signal'], rx_msg['frame'].encode('hex'))):
1406             raise Exception("MGMT_RX_PROCESS failed")
1407         ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
1408         if ev:
1409             break
1410
1411 def test_mesh_pmkid_mismatch(dev, apdev):
1412     """Secure mesh network and PMKID mismatch"""
1413     check_mesh_support(dev[0], secure=True)
1414     addr0 = dev[0].own_addr()
1415     addr1 = dev[1].own_addr()
1416     dev[0].request("SET sae_groups ")
1417     id = add_mesh_secure_net(dev[0])
1418     dev[0].set_network(id, "no_auto_peer", "1")
1419     dev[0].mesh_group_add(id)
1420
1421     dev[1].request("SET sae_groups ")
1422     id = add_mesh_secure_net(dev[1])
1423     dev[1].set_network(id, "no_auto_peer", "1")
1424     dev[1].mesh_group_add(id)
1425
1426     # Check for mesh joined
1427     check_mesh_group_added(dev[0])
1428     check_mesh_group_added(dev[1])
1429
1430     # Check for peer connected
1431     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1432     if ev is None:
1433         raise Exception("Missing no-initiate message")
1434     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1435         raise Exception("MESH_PEER_ADD failed")
1436     check_mesh_peer_connected(dev[0])
1437     check_mesh_peer_connected(dev[1])
1438
1439     if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1440         raise Exception("Failed to remove peer")
1441
1442     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1443     if ev is None:
1444         raise Exception("Missing no-initiate message (2)")
1445     dev[0].dump_monitor()
1446     dev[1].dump_monitor()
1447     dev[0].request("SET ext_mgmt_frame_handling 1")
1448     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1449         raise Exception("MESH_PEER_ADD failed (2)")
1450
1451     count = 0
1452     break_pmkid = True
1453     while True:
1454         count += 1
1455         if count > 50:
1456             raise Exception("Did not see Action frames")
1457         rx_msg = dev[0].mgmt_rx()
1458         if rx_msg is None:
1459             ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.1)
1460             if ev:
1461                 break
1462             raise Exception("MGMT-RX timeout")
1463         if rx_msg['subtype'] == 13:
1464             payload = rx_msg['payload']
1465             frame = rx_msg['frame']
1466             (categ, action) = struct.unpack('BB', payload[0:2])
1467             if categ == 15 and action == 1 and break_pmkid:
1468                 # Mesh Peering Open
1469                 pos = frame.find('\x75\x14')
1470                 if not pos:
1471                     raise Exception("Could not find Mesh Peering Management element")
1472                 logger.info("Found Mesh Peering Management element at %d" % pos)
1473                 # Break PMKID to hit "Mesh RSN: Invalid PMKID (Chosen PMK did
1474                 # not match calculated PMKID)"
1475                 rx_msg['frame'] = frame[0:pos + 6] + '\x00\x00\x00\x00' + frame[pos + 10:]
1476                 break_pmkid = False
1477         if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(rx_msg['freq'], rx_msg['datarate'], rx_msg['ssi_signal'], rx_msg['frame'].encode('hex'))):
1478             raise Exception("MGMT_RX_PROCESS failed")
1479         ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
1480         if ev:
1481             break
1482
1483 def test_mesh_peering_proto(dev, apdev):
1484     """Mesh peering management protocol testing"""
1485     check_mesh_support(dev[0])
1486
1487     dev[0].request("SET ext_mgmt_frame_handling 1")
1488     add_open_mesh_network(dev[0], beacon_int=160)
1489     add_open_mesh_network(dev[1], beacon_int=160)
1490
1491     count = 0
1492     test = 1
1493     while True:
1494         count += 1
1495         if count > 50:
1496             raise Exception("Did not see Action frames")
1497         rx_msg = dev[0].mgmt_rx()
1498         if rx_msg is None:
1499             ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
1500             if ev:
1501                 break
1502             raise Exception("MGMT-RX timeout")
1503         if rx_msg['subtype'] == 13:
1504             payload = rx_msg['payload']
1505             frame = rx_msg['frame']
1506             (categ, action) = struct.unpack('BB', payload[0:2])
1507             if categ == 15 and action == 1 and test == 1:
1508                 # Mesh Peering Open
1509                 pos = frame.find('\x75\x04')
1510                 if not pos:
1511                     raise Exception("Could not find Mesh Peering Management element")
1512                 logger.info("Found Mesh Peering Management element at %d" % pos)
1513                 # Remove the element to hit
1514                 # "MPM: No Mesh Peering Management element"
1515                 rx_msg['frame'] = frame[0:pos]
1516                 test += 1
1517             elif categ == 15 and action == 1 and test == 2:
1518                 # Mesh Peering Open
1519                 pos = frame.find('\x72\x0e')
1520                 if not pos:
1521                     raise Exception("Could not find Mesh ID element")
1522                 logger.info("Found Mesh ID element at %d" % pos)
1523                 # Remove the element to hit
1524                 # "MPM: No Mesh ID or Mesh Configuration element"
1525                 rx_msg['frame'] = frame[0:pos] + frame[pos + 16:]
1526                 test += 1
1527             elif categ == 15 and action == 1 and test == 3:
1528                 # Mesh Peering Open
1529                 pos = frame.find('\x72\x0e')
1530                 if not pos:
1531                     raise Exception("Could not find Mesh ID element")
1532                 logger.info("Found Mesh ID element at %d" % pos)
1533                 # Replace Mesh ID to hit "MPM: Mesh ID or Mesh Configuration
1534                 # element do not match local MBSS"
1535                 rx_msg['frame'] = frame[0:pos] + '\x72\x0etest-test-test' + frame[pos + 16:]
1536                 test += 1
1537             elif categ == 15 and action == 1 and test == 4:
1538                 # Mesh Peering Open
1539                 # Remove IEs to hit
1540                 # "MPM: Ignore too short action frame 1 ie_len 0"
1541                 rx_msg['frame'] = frame[0:26]
1542                 test += 1
1543             elif categ == 15 and action == 1 and test == 5:
1544                 # Mesh Peering Open
1545                 # Truncate IEs to hit
1546                 # "MPM: Failed to parse PLINK IEs"
1547                 rx_msg['frame'] = frame[0:30]
1548                 test += 1
1549             elif categ == 15 and action == 1 and test == 6:
1550                 # Mesh Peering Open
1551                 pos = frame.find('\x75\x04')
1552                 if not pos:
1553                     raise Exception("Could not find Mesh Peering Management element")
1554                 logger.info("Found Mesh Peering Management element at %d" % pos)
1555                 # Truncate the element to hit
1556                 # "MPM: Invalid peer mgmt ie" and
1557                 # "MPM: Mesh parsing rejected frame"
1558                 rx_msg['frame'] = frame[0:pos] + '\x75\x00\x00\x00' + frame[pos + 6:]
1559                 test += 1
1560         if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(rx_msg['freq'], rx_msg['datarate'], rx_msg['ssi_signal'], rx_msg['frame'].encode('hex'))):
1561             raise Exception("MGMT_RX_PROCESS failed")
1562         ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
1563         if ev:
1564             break
1565
1566     if test != 7:
1567         raise Exception("Not all test frames completed")