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