43d76502e02a13d26c12d165dbcbc249ceb5b202
[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_mesh_secure_fail(dev, apdev):
557     """Secure mesh network connectivity failure"""
558     check_mesh_support(dev[0], secure=True)
559     dev[0].request("SET sae_groups ")
560     id = add_mesh_secure_net(dev[0], pmf=True)
561     dev[0].mesh_group_add(id)
562
563     dev[1].request("SET sae_groups ")
564     id = add_mesh_secure_net(dev[1], pmf=True)
565
566     with fail_test(dev[0], 1, "wpa_driver_nl80211_sta_add;mesh_mpm_auth_peer"):
567         dev[1].mesh_group_add(id)
568
569         check_mesh_group_added(dev[0])
570         check_mesh_group_added(dev[1])
571
572         check_mesh_peer_connected(dev[0])
573         check_mesh_peer_connected(dev[1])
574
575 def test_wpas_mesh_ctrl(dev):
576     """wpa_supplicant ctrl_iface mesh command error cases"""
577     check_mesh_support(dev[0])
578     if "FAIL" not in dev[0].request("MESH_GROUP_ADD 123"):
579         raise Exception("Unexpected MESH_GROUP_ADD success")
580     id = dev[0].add_network()
581     if "FAIL" not in dev[0].request("MESH_GROUP_ADD %d" % id):
582         raise Exception("Unexpected MESH_GROUP_ADD success")
583     dev[0].set_network(id, "mode", "5")
584     dev[0].set_network(id, "key_mgmt", "WPA-PSK")
585     if "FAIL" not in dev[0].request("MESH_GROUP_ADD %d" % id):
586         raise Exception("Unexpected MESH_GROUP_ADD success")
587
588     if "FAIL" not in dev[0].request("MESH_GROUP_REMOVE foo"):
589         raise Exception("Unexpected MESH_GROUP_REMOVE success")
590
591 def test_wpas_mesh_dynamic_interface(dev):
592     """wpa_supplicant mesh with dynamic interface"""
593     check_mesh_support(dev[0])
594     mesh0 = None
595     mesh1 = None
596     try:
597         mesh0 = dev[0].request("MESH_INTERFACE_ADD ifname=mesh0")
598         if "FAIL" in mesh0:
599             raise Exception("MESH_INTERFACE_ADD failed")
600         mesh1 = dev[1].request("MESH_INTERFACE_ADD")
601         if "FAIL" in mesh1:
602             raise Exception("MESH_INTERFACE_ADD failed")
603
604         wpas0 = WpaSupplicant(ifname=mesh0)
605         wpas1 = WpaSupplicant(ifname=mesh1)
606         logger.info(mesh0 + " address " + wpas0.get_status_field("address"))
607         logger.info(mesh1 + " address " + wpas1.get_status_field("address"))
608
609         add_open_mesh_network(wpas0)
610         add_open_mesh_network(wpas1)
611         check_mesh_group_added(wpas0)
612         check_mesh_group_added(wpas1)
613         check_mesh_peer_connected(wpas0)
614         check_mesh_peer_connected(wpas1)
615         hwsim_utils.test_connectivity(wpas0, wpas1)
616
617         # Must not allow MESH_GROUP_REMOVE on dynamic interface
618         if "FAIL" not in wpas0.request("MESH_GROUP_REMOVE " + mesh0):
619             raise Exception("Invalid MESH_GROUP_REMOVE accepted")
620         if "FAIL" not in wpas1.request("MESH_GROUP_REMOVE " + mesh1):
621             raise Exception("Invalid MESH_GROUP_REMOVE accepted")
622
623         # Must not allow MESH_GROUP_REMOVE on another radio interface
624         if "FAIL" not in wpas0.request("MESH_GROUP_REMOVE " + mesh1):
625             raise Exception("Invalid MESH_GROUP_REMOVE accepted")
626         if "FAIL" not in wpas1.request("MESH_GROUP_REMOVE " + mesh0):
627             raise Exception("Invalid MESH_GROUP_REMOVE accepted")
628
629         wpas0.remove_ifname()
630         wpas1.remove_ifname()
631
632         if "OK" not in dev[0].request("MESH_GROUP_REMOVE " + mesh0):
633             raise Exception("MESH_GROUP_REMOVE failed")
634         if "OK" not in dev[1].request("MESH_GROUP_REMOVE " + mesh1):
635             raise Exception("MESH_GROUP_REMOVE failed")
636
637         if "FAIL" not in dev[0].request("MESH_GROUP_REMOVE " + mesh0):
638             raise Exception("Invalid MESH_GROUP_REMOVE accepted")
639         if "FAIL" not in dev[1].request("MESH_GROUP_REMOVE " + mesh1):
640             raise Exception("Invalid MESH_GROUP_REMOVE accepted")
641
642         logger.info("Make sure another dynamic group can be added")
643         mesh0 = dev[0].request("MESH_INTERFACE_ADD ifname=mesh0")
644         if "FAIL" in mesh0:
645             raise Exception("MESH_INTERFACE_ADD failed")
646         mesh1 = dev[1].request("MESH_INTERFACE_ADD")
647         if "FAIL" in mesh1:
648             raise Exception("MESH_INTERFACE_ADD failed")
649
650         wpas0 = WpaSupplicant(ifname=mesh0)
651         wpas1 = WpaSupplicant(ifname=mesh1)
652         logger.info(mesh0 + " address " + wpas0.get_status_field("address"))
653         logger.info(mesh1 + " address " + wpas1.get_status_field("address"))
654
655         add_open_mesh_network(wpas0)
656         add_open_mesh_network(wpas1)
657         check_mesh_group_added(wpas0)
658         check_mesh_group_added(wpas1)
659         check_mesh_peer_connected(wpas0)
660         check_mesh_peer_connected(wpas1)
661         hwsim_utils.test_connectivity(wpas0, wpas1)
662     finally:
663         if mesh0:
664             dev[0].request("MESH_GROUP_REMOVE " + mesh0)
665         if mesh1:
666             dev[1].request("MESH_GROUP_REMOVE " + mesh1)
667
668 def test_wpas_mesh_max_peering(dev, apdev, params):
669     """Mesh max peering limit"""
670     check_mesh_support(dev[0])
671     try:
672         dev[0].request("SET max_peer_links 1")
673
674         # first, connect dev[0] and dev[1]
675         add_open_mesh_network(dev[0])
676         add_open_mesh_network(dev[1])
677         for i in range(2):
678             ev = dev[i].wait_event(["MESH-PEER-CONNECTED"])
679             if ev is None:
680                 raise Exception("dev%d did not connect with any peer" % i)
681
682         # add dev[2] which will try to connect with both dev[0] and dev[1],
683         # but can complete connection only with dev[1]
684         add_open_mesh_network(dev[2])
685         for i in range(1, 3):
686             ev = dev[i].wait_event(["MESH-PEER-CONNECTED"])
687             if ev is None:
688                 raise Exception("dev%d did not connect the second peer" % i)
689
690         ev = dev[0].wait_event(["MESH-PEER-CONNECTED"], timeout=1)
691         if ev is not None:
692             raise Exception("dev0 connection beyond max peering limit")
693
694         ev = dev[2].wait_event(["MESH-PEER-CONNECTED"], timeout=0.1)
695         if ev is not None:
696             raise Exception("dev2 reported unexpected peering: " + ev)
697
698         for i in range(3):
699             dev[i].mesh_group_remove()
700             check_mesh_group_removed(dev[i])
701     finally:
702         dev[0].request("SET max_peer_links 99")
703
704     addr0 = dev[0].own_addr()
705     addr1 = dev[1].own_addr()
706     addr2 = dev[2].own_addr()
707
708     capfile = os.path.join(params['logdir'], "hwsim0.pcapng")
709     filt = "wlan.fc.type_subtype == 8"
710     out = run_tshark(capfile, filt, [ "wlan.sa", "wlan.mesh.config.cap" ])
711     pkts = out.splitlines()
712     one = [ 0, 0, 0 ]
713     zero = [ 0, 0, 0 ]
714     for pkt in pkts:
715         addr, cap = pkt.split('\t')
716         cap = int(cap, 16)
717         if addr == addr0:
718             idx = 0
719         elif addr == addr1:
720             idx = 1
721         elif addr == addr2:
722             idx = 2
723         else:
724             continue
725         if cap & 0x01:
726             one[idx] += 1
727         else:
728             zero[idx] += 1
729     logger.info("one: " + str(one))
730     logger.info("zero: " + str(zero))
731     if zero[0] == 0:
732         raise Exception("Accepting Additional Mesh Peerings not cleared")
733     if one[0] == 0:
734         raise Exception("Accepting Additional Mesh Peerings was not set in the first Beacon frame")
735     if zero[1] > 0 or zero[2] > 0 or one[1] == 0 or one[2] == 0:
736         raise Exception("Unexpected value in Accepting Additional Mesh Peerings from other STAs")
737
738 def test_wpas_mesh_open_5ghz(dev, apdev):
739     """wpa_supplicant open MESH network on 5 GHz band"""
740     try:
741         _test_wpas_mesh_open_5ghz(dev, apdev)
742     finally:
743         subprocess.call(['iw', 'reg', 'set', '00'])
744         dev[0].flush_scan_cache()
745         dev[1].flush_scan_cache()
746
747 def _test_wpas_mesh_open_5ghz(dev, apdev):
748     check_mesh_support(dev[0])
749     subprocess.call(['iw', 'reg', 'set', 'US'])
750     for i in range(2):
751         for j in range(5):
752             ev = dev[i].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
753             if ev is None:
754                 raise Exception("No regdom change event")
755             if "alpha2=US" in ev:
756                 break
757         add_open_mesh_network(dev[i], freq="5180")
758
759     # Check for mesh joined
760     check_mesh_group_added(dev[0])
761     check_mesh_group_added(dev[1])
762
763     # Check for peer connected
764     check_mesh_peer_connected(dev[0])
765     check_mesh_peer_connected(dev[1])
766
767     # Test connectivity 0->1 and 1->0
768     hwsim_utils.test_connectivity(dev[0], dev[1])
769
770 def test_wpas_mesh_open_vht_80p80(dev, apdev):
771     """wpa_supplicant open MESH network on VHT 80+80 MHz channel"""
772     try:
773         _test_wpas_mesh_open_vht_80p80(dev, apdev)
774     finally:
775         subprocess.call(['iw', 'reg', 'set', '00'])
776         dev[0].flush_scan_cache()
777         dev[1].flush_scan_cache()
778
779 def _test_wpas_mesh_open_vht_80p80(dev, apdev):
780     check_mesh_support(dev[0])
781     subprocess.call(['iw', 'reg', 'set', 'US'])
782     for i in range(2):
783         for j in range(5):
784             ev = dev[i].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
785             if ev is None:
786                 raise Exception("No regdom change event")
787             if "alpha2=US" in ev:
788                 break
789         add_open_mesh_network(dev[i], freq="5180", chwidth=3)
790
791     # Check for mesh joined
792     check_mesh_group_added(dev[0])
793     check_mesh_group_added(dev[1])
794
795     # Check for peer connected
796     check_mesh_peer_connected(dev[0])
797     check_mesh_peer_connected(dev[1])
798
799     # Test connectivity 0->1 and 1->0
800     hwsim_utils.test_connectivity(dev[0], dev[1])
801
802     sig = dev[0].request("SIGNAL_POLL").splitlines()
803     if "WIDTH=80+80 MHz" not in sig:
804         raise Exception("Unexpected SIGNAL_POLL value(2): " + str(sig))
805     if "CENTER_FRQ1=5210" not in sig:
806         raise Exception("Unexpected SIGNAL_POLL value(3): " + str(sig))
807     if "CENTER_FRQ2=5775" not in sig:
808         raise Exception("Unexpected SIGNAL_POLL value(4): " + str(sig))
809
810     sig = dev[1].request("SIGNAL_POLL").splitlines()
811     if "WIDTH=80+80 MHz" not in sig:
812         raise Exception("Unexpected SIGNAL_POLL value(2b): " + str(sig))
813     if "CENTER_FRQ1=5210" not in sig:
814         raise Exception("Unexpected SIGNAL_POLL value(3b): " + str(sig))
815     if "CENTER_FRQ2=5775" not in sig:
816         raise Exception("Unexpected SIGNAL_POLL value(4b): " + str(sig))
817
818 def test_mesh_open_vht_160(dev, apdev):
819     """Open mesh network on VHT 160 MHz channel"""
820     try:
821         _test_mesh_open_vht_160(dev, apdev)
822     finally:
823         subprocess.call(['iw', 'reg', 'set', '00'])
824         dev[0].flush_scan_cache()
825         dev[1].flush_scan_cache()
826
827 def _test_mesh_open_vht_160(dev, apdev):
828     check_mesh_support(dev[0])
829     subprocess.call(['iw', 'reg', 'set', 'ZA'])
830     for i in range(2):
831         for j in range(5):
832             ev = dev[i].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
833             if ev is None:
834                 raise Exception("No regdom change event")
835             if "alpha2=ZA" in ev:
836                 break
837
838         cmd = subprocess.Popen(["iw", "reg", "get"], stdout=subprocess.PIPE)
839         reg = cmd.stdout.read()
840         if "@ 160)" not in reg:
841             raise HwsimSkip("160 MHz channel not supported in regulatory information")
842
843         add_open_mesh_network(dev[i], freq="5520", chwidth=2)
844
845     # Check for mesh joined
846     check_mesh_group_added(dev[0])
847     check_mesh_group_added(dev[1])
848
849     # Check for peer connected
850     check_mesh_peer_connected(dev[0])
851     check_mesh_peer_connected(dev[1])
852
853     # Test connectivity 0->1 and 1->0
854     hwsim_utils.test_connectivity(dev[0], dev[1])
855
856     sig = dev[0].request("SIGNAL_POLL").splitlines()
857     if "WIDTH=160 MHz" not in sig:
858         raise Exception("Unexpected SIGNAL_POLL value(2): " + str(sig))
859     if "FREQUENCY=5520" not in sig:
860         raise Exception("Unexpected SIGNAL_POLL value(3): " + str(sig))
861
862     sig = dev[1].request("SIGNAL_POLL").splitlines()
863     if "WIDTH=160 MHz" not in sig:
864         raise Exception("Unexpected SIGNAL_POLL value(2b): " + str(sig))
865     if "FREQUENCY=5520" not in sig:
866         raise Exception("Unexpected SIGNAL_POLL value(3b): " + str(sig))
867
868 def test_wpas_mesh_password_mismatch(dev, apdev):
869     """Mesh network and one device with mismatching password"""
870     check_mesh_support(dev[0], secure=True)
871     dev[0].request("SET sae_groups ")
872     id = add_mesh_secure_net(dev[0])
873     dev[0].mesh_group_add(id)
874
875     dev[1].request("SET sae_groups ")
876     id = add_mesh_secure_net(dev[1])
877     dev[1].mesh_group_add(id)
878
879     dev[2].request("SET sae_groups ")
880     id = add_mesh_secure_net(dev[2])
881     dev[2].set_network_quoted(id, "psk", "wrong password")
882     dev[2].mesh_group_add(id)
883
884     # The two peers with matching password need to be able to connect
885     check_mesh_group_added(dev[0])
886     check_mesh_group_added(dev[1])
887     check_mesh_peer_connected(dev[0])
888     check_mesh_peer_connected(dev[1])
889
890     ev = dev[2].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=20)
891     if ev is None:
892         raise Exception("dev2 did not report auth failure (1)")
893     ev = dev[2].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=20)
894     if ev is None:
895         raise Exception("dev2 did not report auth failure (2)")
896
897     count = 0
898     ev = dev[0].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=1)
899     if ev is None:
900         logger.info("dev0 did not report auth failure")
901     else:
902         if "addr=" + dev[2].own_addr() not in ev:
903             raise Exception("Unexpected peer address in dev0 event: " + ev)
904         count += 1
905
906     ev = dev[1].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=1)
907     if ev is None:
908         logger.info("dev1 did not report auth failure")
909     else:
910         if "addr=" + dev[2].own_addr() not in ev:
911             raise Exception("Unexpected peer address in dev1 event: " + ev)
912         count += 1
913
914     hwsim_utils.test_connectivity(dev[0], dev[1])
915
916     for i in range(2):
917         try:
918             hwsim_utils.test_connectivity(dev[i], dev[2], timeout=1)
919             raise Exception("Data connectivity test passed unexpectedly")
920         except Exception, e:
921             if "data delivery failed" not in str(e):
922                 raise
923
924     if count == 0:
925         raise Exception("Neither dev0 nor dev1 reported auth failure")
926
927 def test_wpas_mesh_password_mismatch_retry(dev, apdev, params):
928     """Mesh password mismatch and retry [long]"""
929     if not params['long']:
930         raise HwsimSkip("Skip test case with long duration due to --long not specified")
931     check_mesh_support(dev[0], secure=True)
932     dev[0].request("SET sae_groups ")
933     id = add_mesh_secure_net(dev[0])
934     dev[0].mesh_group_add(id)
935
936     dev[1].request("SET sae_groups ")
937     id = add_mesh_secure_net(dev[1])
938     dev[1].set_network_quoted(id, "psk", "wrong password")
939     dev[1].mesh_group_add(id)
940
941     # Check for mesh joined
942     check_mesh_group_added(dev[0])
943     check_mesh_group_added(dev[1])
944
945     for i in range(4):
946         ev = dev[0].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=20)
947         if ev is None:
948             raise Exception("dev0 did not report auth failure (%d)" % i)
949         ev = dev[1].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=20)
950         if ev is None:
951             raise Exception("dev1 did not report auth failure (%d)" % i)
952
953     ev = dev[0].wait_event(["MESH-SAE-AUTH-BLOCKED"], timeout=10)
954     if ev is None:
955         raise Exception("dev0 did not report auth blocked")
956     ev = dev[1].wait_event(["MESH-SAE-AUTH-BLOCKED"], timeout=10)
957     if ev is None:
958         raise Exception("dev1 did not report auth blocked")
959
960 def test_mesh_wpa_auth_init_oom(dev, apdev):
961     """Secure mesh network setup failing due to wpa_init() OOM"""
962     check_mesh_support(dev[0], secure=True)
963     dev[0].request("SET sae_groups ")
964     with alloc_fail(dev[0], 1, "wpa_init"):
965         id = add_mesh_secure_net(dev[0])
966         dev[0].mesh_group_add(id)
967         ev = dev[0].wait_event(["MESH-GROUP-STARTED"], timeout=0.2)
968         if ev is not None:
969             raise Exception("Unexpected mesh group start during OOM")
970
971 def test_mesh_wpa_init_fail(dev, apdev):
972     """Secure mesh network setup local failure"""
973     check_mesh_support(dev[0], secure=True)
974     dev[0].request("SET sae_groups ")
975
976     with fail_test(dev[0], 1, "os_get_random;=__mesh_rsn_auth_init"):
977         id = add_mesh_secure_net(dev[0])
978         dev[0].mesh_group_add(id)
979         wait_fail_trigger(dev[0], "GET_FAIL")
980
981     dev[0].dump_monitor()
982     with alloc_fail(dev[0], 1, "mesh_rsn_auth_init"):
983         id = add_mesh_secure_net(dev[0])
984         dev[0].mesh_group_add(id)
985         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
986
987     dev[0].dump_monitor()
988     with fail_test(dev[0], 1, "os_get_random;mesh_rsn_init_ampe_sta"):
989         id = add_mesh_secure_net(dev[0])
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         wait_fail_trigger(dev[0], "GET_FAIL")
995
996 def test_wpas_mesh_reconnect(dev, apdev):
997     """Secure mesh network plink counting during reconnection"""
998     check_mesh_support(dev[0])
999     try:
1000         _test_wpas_mesh_reconnect(dev)
1001     finally:
1002         dev[0].request("SET max_peer_links 99")
1003
1004 def _test_wpas_mesh_reconnect(dev):
1005     dev[0].request("SET max_peer_links 2")
1006     dev[0].request("SET sae_groups ")
1007     id = add_mesh_secure_net(dev[0])
1008     dev[0].set_network(id, "beacon_int", "100")
1009     dev[0].mesh_group_add(id)
1010     dev[1].request("SET sae_groups ")
1011     id = add_mesh_secure_net(dev[1])
1012     dev[1].mesh_group_add(id)
1013     check_mesh_group_added(dev[0])
1014     check_mesh_group_added(dev[1])
1015     check_mesh_peer_connected(dev[0])
1016     check_mesh_peer_connected(dev[1])
1017
1018     for i in range(3):
1019         # Drop incoming management frames to avoid handling link close
1020         dev[0].request("SET ext_mgmt_frame_handling 1")
1021         dev[1].mesh_group_remove()
1022         check_mesh_group_removed(dev[1])
1023         dev[1].request("FLUSH")
1024         dev[0].request("SET ext_mgmt_frame_handling 0")
1025         id = add_mesh_secure_net(dev[1])
1026         dev[1].mesh_group_add(id)
1027         check_mesh_group_added(dev[1])
1028         check_mesh_peer_connected(dev[1])
1029         dev[0].dump_monitor()
1030         dev[1].dump_monitor()
1031
1032 def test_wpas_mesh_gate_forwarding(dev, apdev, p):
1033     """Mesh forwards traffic to unknown sta to mesh gates"""
1034     addr0 = dev[0].own_addr()
1035     addr1 = dev[1].own_addr()
1036     addr2 = dev[2].own_addr()
1037     external_sta = '02:11:22:33:44:55'
1038
1039     # start 3 node connected mesh
1040     check_mesh_support(dev[0])
1041     for i in range(3):
1042         add_open_mesh_network(dev[i])
1043         check_mesh_group_added(dev[i])
1044     for i in range(3):
1045         check_mesh_peer_connected(dev[i])
1046
1047     hwsim_utils.test_connectivity(dev[0], dev[1])
1048     hwsim_utils.test_connectivity(dev[1], dev[2])
1049     hwsim_utils.test_connectivity(dev[0], dev[2])
1050
1051     # dev0 and dev1 are mesh gates
1052     subprocess.call(['iw', 'dev', dev[0].ifname, 'set', 'mesh_param',
1053                      'mesh_gate_announcements=1'])
1054     subprocess.call(['iw', 'dev', dev[1].ifname, 'set', 'mesh_param',
1055                      'mesh_gate_announcements=1'])
1056
1057     # wait for gate announcement frames
1058     time.sleep(1)
1059
1060     # data frame from dev2 -> external sta should be sent to both gates
1061     dev[2].request("DATA_TEST_CONFIG 1")
1062     dev[2].request("DATA_TEST_TX {} {} 0".format(external_sta, addr2))
1063     dev[2].request("DATA_TEST_CONFIG 0")
1064
1065     capfile = os.path.join(p['logdir'], "hwsim0.pcapng")
1066     filt = "wlan.sa==%s && wlan_mgt.fixed.mesh_addr5==%s" % (addr2,
1067                                                              external_sta)
1068     for i in range(15):
1069         da = run_tshark(capfile, filt, [ "wlan.da" ])
1070         if addr0 in da and addr1 in da:
1071             logger.debug("Frames seen in tshark iteration %d" % i)
1072             break
1073         time.sleep(0.3)
1074
1075     if addr0 not in da:
1076         raise Exception("Frame to gate %s not observed" % addr0)
1077     if addr1 not in da:
1078         raise Exception("Frame to gate %s not observed" % addr1)
1079
1080 def test_wpas_mesh_pmksa_caching(dev, apdev):
1081     """Secure mesh network and PMKSA caching"""
1082     check_mesh_support(dev[0], secure=True)
1083     dev[0].request("SET sae_groups ")
1084     id = add_mesh_secure_net(dev[0])
1085     dev[0].mesh_group_add(id)
1086
1087     dev[1].request("SET sae_groups ")
1088     id = add_mesh_secure_net(dev[1])
1089     dev[1].mesh_group_add(id)
1090
1091     # Check for mesh joined
1092     check_mesh_group_added(dev[0])
1093     check_mesh_group_added(dev[1])
1094
1095     # Check for peer connected
1096     check_mesh_peer_connected(dev[0])
1097     check_mesh_peer_connected(dev[1])
1098
1099     addr0 = dev[0].own_addr()
1100     addr1 = dev[1].own_addr()
1101     pmksa0 = dev[0].get_pmksa(addr1)
1102     pmksa1 = dev[1].get_pmksa(addr0)
1103     if pmksa0 is None or pmksa1 is None:
1104         raise Exception("No PMKSA cache entry created")
1105     if pmksa0['pmkid'] != pmksa1['pmkid']:
1106         raise Exception("PMKID mismatch in PMKSA cache entries")
1107
1108     if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1109         raise Exception("Failed to remove peer")
1110     pmksa0b = dev[0].get_pmksa(addr1)
1111     if pmksa0b is None:
1112         raise Exception("PMKSA cache entry not maintained")
1113     time.sleep(0.1)
1114
1115     if "FAIL" not in dev[0].request("MESH_PEER_ADD " + addr1):
1116         raise Exception("MESH_PEER_ADD unexpectedly succeeded in no_auto_peer=0 case")
1117
1118 def test_wpas_mesh_pmksa_caching2(dev, apdev):
1119     """Secure mesh network and PMKSA caching with no_auto_peer=1"""
1120     check_mesh_support(dev[0], secure=True)
1121     addr0 = dev[0].own_addr()
1122     addr1 = dev[1].own_addr()
1123     dev[0].request("SET sae_groups ")
1124     id = add_mesh_secure_net(dev[0])
1125     dev[0].set_network(id, "no_auto_peer", "1")
1126     dev[0].mesh_group_add(id)
1127
1128     dev[1].request("SET sae_groups ")
1129     id = add_mesh_secure_net(dev[1])
1130     dev[1].set_network(id, "no_auto_peer", "1")
1131     dev[1].mesh_group_add(id)
1132
1133     # Check for mesh joined
1134     check_mesh_group_added(dev[0])
1135     check_mesh_group_added(dev[1])
1136
1137     # Check for peer connected
1138     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1139     if ev is None:
1140         raise Exception("Missing no-initiate message")
1141     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1142         raise Exception("MESH_PEER_ADD failed")
1143     check_mesh_peer_connected(dev[0])
1144     check_mesh_peer_connected(dev[1])
1145
1146     pmksa0 = dev[0].get_pmksa(addr1)
1147     pmksa1 = dev[1].get_pmksa(addr0)
1148     if pmksa0 is None or pmksa1 is None:
1149         raise Exception("No PMKSA cache entry created")
1150     if pmksa0['pmkid'] != pmksa1['pmkid']:
1151         raise Exception("PMKID mismatch in PMKSA cache entries")
1152
1153     if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1154         raise Exception("Failed to remove peer")
1155     pmksa0b = dev[0].get_pmksa(addr1)
1156     if pmksa0b is None:
1157         raise Exception("PMKSA cache entry not maintained")
1158
1159     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1160     if ev is None:
1161         raise Exception("Missing no-initiate message (2)")
1162     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1163         raise Exception("MESH_PEER_ADD failed (2)")
1164     check_mesh_peer_connected(dev[0])
1165     check_mesh_peer_connected(dev[1])
1166
1167     pmksa0c = dev[0].get_pmksa(addr1)
1168     pmksa1c = dev[1].get_pmksa(addr0)
1169     if pmksa0c is None or pmksa1c is None:
1170         raise Exception("No PMKSA cache entry created (2)")
1171     if pmksa0c['pmkid'] != pmksa1c['pmkid']:
1172         raise Exception("PMKID mismatch in PMKSA cache entries")
1173     if pmksa0['pmkid'] != pmksa0c['pmkid']:
1174         raise Exception("PMKID changed")
1175
1176     hwsim_utils.test_connectivity(dev[0], dev[1])
1177
1178 def test_wpas_mesh_pmksa_caching_no_match(dev, apdev):
1179     """Secure mesh network and PMKSA caching with no PMKID match"""
1180     check_mesh_support(dev[0], secure=True)
1181     addr0 = dev[0].own_addr()
1182     addr1 = dev[1].own_addr()
1183     dev[0].request("SET sae_groups ")
1184     id = add_mesh_secure_net(dev[0])
1185     dev[0].set_network(id, "no_auto_peer", "1")
1186     dev[0].mesh_group_add(id)
1187
1188     dev[1].request("SET sae_groups ")
1189     id = add_mesh_secure_net(dev[1])
1190     dev[1].set_network(id, "no_auto_peer", "1")
1191     dev[1].mesh_group_add(id)
1192
1193     # Check for mesh joined
1194     check_mesh_group_added(dev[0])
1195     check_mesh_group_added(dev[1])
1196
1197     # Check for peer connected
1198     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1199     if ev is None:
1200         raise Exception("Missing no-initiate message")
1201     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1202         raise Exception("MESH_PEER_ADD failed")
1203     check_mesh_peer_connected(dev[0])
1204     check_mesh_peer_connected(dev[1])
1205
1206     pmksa0 = dev[0].get_pmksa(addr1)
1207     pmksa1 = dev[1].get_pmksa(addr0)
1208     if pmksa0 is None or pmksa1 is None:
1209         raise Exception("No PMKSA cache entry created")
1210     if pmksa0['pmkid'] != pmksa1['pmkid']:
1211         raise Exception("PMKID mismatch in PMKSA cache entries")
1212
1213     if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1214         raise Exception("Failed to remove peer")
1215
1216     if "OK" not in dev[1].request("PMKSA_FLUSH"):
1217         raise Exception("Failed to flush PMKSA cache")
1218
1219     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1220     if ev is None:
1221         raise Exception("Missing no-initiate message (2)")
1222     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1223         raise Exception("MESH_PEER_ADD failed (2)")
1224     check_mesh_peer_connected(dev[0])
1225     check_mesh_peer_connected(dev[1])
1226
1227     pmksa0c = dev[0].get_pmksa(addr1)
1228     pmksa1c = dev[1].get_pmksa(addr0)
1229     if pmksa0c is None or pmksa1c is None:
1230         raise Exception("No PMKSA cache entry created (2)")
1231     if pmksa0c['pmkid'] != pmksa1c['pmkid']:
1232         raise Exception("PMKID mismatch in PMKSA cache entries")
1233     if pmksa0['pmkid'] == pmksa0c['pmkid']:
1234         raise Exception("PMKID did not change")
1235
1236     hwsim_utils.test_connectivity(dev[0], dev[1])
1237
1238 def test_mesh_pmksa_caching_oom(dev, apdev):
1239     """Secure mesh network and PMKSA caching failing due to OOM"""
1240     check_mesh_support(dev[0], secure=True)
1241     addr0 = dev[0].own_addr()
1242     addr1 = dev[1].own_addr()
1243     dev[0].request("SET sae_groups ")
1244     id = add_mesh_secure_net(dev[0])
1245     dev[0].set_network(id, "no_auto_peer", "1")
1246     dev[0].mesh_group_add(id)
1247
1248     dev[1].request("SET sae_groups ")
1249     id = add_mesh_secure_net(dev[1])
1250     dev[1].set_network(id, "no_auto_peer", "1")
1251     dev[1].mesh_group_add(id)
1252
1253     # Check for mesh joined
1254     check_mesh_group_added(dev[0])
1255     check_mesh_group_added(dev[1])
1256
1257     # Check for peer connected
1258     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1259     if ev is None:
1260         raise Exception("Missing no-initiate message")
1261     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1262         raise Exception("MESH_PEER_ADD failed")
1263     check_mesh_peer_connected(dev[0])
1264     check_mesh_peer_connected(dev[1])
1265
1266     if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1267         raise Exception("Failed to remove peer")
1268     pmksa0b = dev[0].get_pmksa(addr1)
1269     if pmksa0b is None:
1270         raise Exception("PMKSA cache entry not maintained")
1271
1272     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1273     if ev is None:
1274         raise Exception("Missing no-initiate message (2)")
1275
1276     with alloc_fail(dev[0], 1, "wpa_auth_sta_init;mesh_rsn_auth_sae_sta"):
1277         if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1278             raise Exception("MESH_PEER_ADD failed (2)")
1279         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
1280
1281 def test_mesh_oom(dev, apdev):
1282     """Mesh network setup failing due to OOM"""
1283     check_mesh_support(dev[0], secure=True)
1284     dev[0].request("SET sae_groups ")
1285
1286     with alloc_fail(dev[0], 1, "mesh_config_create"):
1287         add_open_mesh_network(dev[0])
1288         ev = dev[0].wait_event(["Failed to init mesh"])
1289         if ev is None:
1290             raise Exception("Init failure not reported")
1291
1292     with alloc_fail(dev[0], 4, "=wpa_supplicant_mesh_init"):
1293         add_open_mesh_network(dev[0], basic_rates="60 120 240")
1294         ev = dev[0].wait_event(["Failed to init mesh"])
1295         if ev is None:
1296             raise Exception("Init failure not reported")
1297
1298     for i in range(1, 66):
1299         dev[0].dump_monitor()
1300         logger.info("Test instance %d" % i)
1301         try:
1302             with alloc_fail(dev[0], i, "wpa_supplicant_mesh_init"):
1303                 add_open_mesh_network(dev[0])
1304                 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
1305                 ev = dev[0].wait_event(["Failed to init mesh",
1306                                         "MESH-GROUP-STARTED"])
1307                 if ev is None:
1308                     raise Exception("Init failure not reported")
1309         except Exception, e:
1310             if i < 15:
1311                 raise
1312             logger.info("Ignore no-oom for i=%d" % i)
1313
1314     with alloc_fail(dev[0], 5, "=wpa_supplicant_mesh_init"):
1315         id = add_mesh_secure_net(dev[0])
1316         dev[0].mesh_group_add(id)
1317         ev = dev[0].wait_event(["Failed to init mesh"])
1318         if ev is None:
1319             raise Exception("Init failure not reported")
1320
1321 def test_mesh_add_interface_oom(dev):
1322     """wpa_supplicant mesh with dynamic interface addition failing"""
1323     check_mesh_support(dev[0])
1324     for i in range(1, 3):
1325         mesh = None
1326         try:
1327             with alloc_fail(dev[0], i, "wpas_mesh_add_interface"):
1328                 mesh = dev[0].request("MESH_INTERFACE_ADD").strip()
1329         finally:
1330             if mesh and mesh != "FAIL":
1331                 dev[0].request("MESH_GROUP_REMOVE " + mesh)
1332
1333 def test_mesh_scan_oom(dev):
1334     """wpa_supplicant mesh scan results and OOM"""
1335     check_mesh_support(dev[0])
1336     add_open_mesh_network(dev[0])
1337     check_mesh_group_added(dev[0])
1338     for i in range(5):
1339         dev[1].scan(freq="2412")
1340         res = dev[1].request("SCAN_RESULTS")
1341         if "[MESH]" in res:
1342             break
1343     for r in res.splitlines():
1344         if "[MESH]" in r:
1345             break
1346     bssid = r.split('\t')[0]
1347
1348     bss = dev[1].get_bss(bssid)
1349     if bss is None:
1350         raise Exception("Could not get BSS entry for mesh")
1351
1352     for i in range(1, 3):
1353         with alloc_fail(dev[1], i, "mesh_attr_text"):
1354             bss = dev[1].get_bss(bssid)
1355             if bss and "mesh_id" in bss:
1356                 raise Exception("Unexpected BSS result during OOM")
1357
1358 def test_mesh_drv_fail(dev, apdev):
1359     """Mesh network setup failing due to driver command failure"""
1360     check_mesh_support(dev[0], secure=True)
1361     dev[0].request("SET sae_groups ")
1362
1363     with fail_test(dev[0], 1, "nl80211_join_mesh"):
1364         add_open_mesh_network(dev[0])
1365         ev = dev[0].wait_event(["mesh join error"])
1366         if ev is None:
1367             raise Exception("Join failure not reported")
1368
1369     dev[0].dump_monitor()
1370     with fail_test(dev[0], 1, "wpa_driver_nl80211_if_add"):
1371         if "FAIL" not in dev[0].request("MESH_INTERFACE_ADD").strip():
1372             raise Exception("Interface added unexpectedly")
1373
1374     dev[0].dump_monitor()
1375     with fail_test(dev[0], 1, "wpa_driver_nl80211_init_mesh"):
1376         add_open_mesh_network(dev[0])
1377         ev = dev[0].wait_event(["Could not join mesh"])
1378         if ev is None:
1379             raise Exception("Join failure not reported")
1380
1381 def test_mesh_sae_groups_invalid(dev, apdev):
1382     """Mesh with invalid SAE group configuration"""
1383     check_mesh_support(dev[0], secure=True)
1384
1385     dev[0].request("SET sae_groups 25")
1386     id = add_mesh_secure_net(dev[0])
1387     dev[0].mesh_group_add(id)
1388
1389     dev[1].request("SET sae_groups 123 122 121")
1390     id = add_mesh_secure_net(dev[1])
1391     dev[1].mesh_group_add(id)
1392
1393     check_mesh_group_added(dev[0])
1394     check_mesh_group_added(dev[1])
1395
1396     ev = dev[0].wait_event(["new peer notification"], timeout=10)
1397     if ev is None:
1398         raise Exception("dev[0] did not see peer")
1399     ev = dev[1].wait_event(["new peer notification"], timeout=10)
1400     if ev is None:
1401         raise Exception("dev[1] did not see peer")
1402
1403     ev = dev[0].wait_event(["MESH-PEER-CONNECTED"], timeout=0.1)
1404     if ev is not None:
1405         raise Exception("Unexpected connection(0)")
1406
1407     ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
1408     if ev is not None:
1409         raise Exception("Unexpected connection(1)")
1410
1411     # Additional coverage in mesh_rsn_sae_group() with non-zero
1412     # wpa_s->mesh_rsn->sae_group_index.
1413     dev[0].dump_monitor()
1414     dev[1].dump_monitor()
1415     id = add_mesh_secure_net(dev[2])
1416     dev[2].mesh_group_add(id)
1417     check_mesh_group_added(dev[2])
1418     check_mesh_peer_connected(dev[0])
1419     check_mesh_peer_connected(dev[2])
1420     ev = dev[1].wait_event(["new peer notification"], timeout=10)
1421     if ev is None:
1422         raise Exception("dev[1] did not see peer(2)")
1423     dev[0].dump_monitor()
1424     dev[1].dump_monitor()
1425     dev[2].dump_monitor()
1426
1427     dev[0].request("SET sae_groups ")
1428     dev[1].request("SET sae_groups ")
1429
1430 def test_mesh_sae_failure(dev, apdev):
1431     """Mesh and local SAE failures"""
1432     check_mesh_support(dev[0], secure=True)
1433
1434     dev[0].request("SET sae_groups ")
1435     dev[1].request("SET sae_groups ")
1436
1437     funcs = [ (1, "=mesh_rsn_auth_sae_sta", True),
1438               (1, "mesh_rsn_build_sae_commit;mesh_rsn_auth_sae_sta", False),
1439               (1, "auth_sae_init_committed;mesh_rsn_auth_sae_sta", True),
1440               (1, "=mesh_rsn_protect_frame", True),
1441               (2, "=mesh_rsn_protect_frame", True),
1442               (1, "aes_siv_encrypt;mesh_rsn_protect_frame", True),
1443               (1, "=mesh_rsn_process_ampe", True),
1444               (1, "aes_siv_decrypt;mesh_rsn_process_ampe", True) ]
1445     for count, func, success in funcs:
1446         id = add_mesh_secure_net(dev[0])
1447         dev[0].mesh_group_add(id)
1448
1449         with alloc_fail(dev[1], count, func):
1450             id = add_mesh_secure_net(dev[1])
1451             dev[1].mesh_group_add(id)
1452             check_mesh_group_added(dev[0])
1453             check_mesh_group_added(dev[1])
1454             if success:
1455                 # retry is expected to work
1456                 check_mesh_peer_connected(dev[0])
1457                 check_mesh_peer_connected(dev[1])
1458             else:
1459                 wait_fail_trigger(dev[1], "GET_ALLOC_FAIL")
1460         dev[0].mesh_group_remove()
1461         dev[1].mesh_group_remove()
1462         check_mesh_group_removed(dev[0])
1463         check_mesh_group_removed(dev[1])
1464
1465 def test_mesh_failure(dev, apdev):
1466     """Mesh and local failures"""
1467     check_mesh_support(dev[0])
1468
1469     funcs = [ (1, "ap_sta_add;mesh_mpm_add_peer", True),
1470               (1, "wpabuf_alloc;mesh_mpm_send_plink_action", True) ]
1471     for count, func, success in funcs:
1472         add_open_mesh_network(dev[0])
1473
1474         with alloc_fail(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_ALLOC_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     funcs = [ (1, "mesh_mpm_init_link", True) ]
1490     for count, func, success in funcs:
1491         add_open_mesh_network(dev[0])
1492
1493         with fail_test(dev[1], count, func):
1494             add_open_mesh_network(dev[1])
1495             check_mesh_group_added(dev[0])
1496             check_mesh_group_added(dev[1])
1497             if success:
1498                 # retry is expected to work
1499                 check_mesh_peer_connected(dev[0])
1500                 check_mesh_peer_connected(dev[1])
1501             else:
1502                 wait_fail_trigger(dev[1], "GET_FAIL")
1503         dev[0].mesh_group_remove()
1504         dev[1].mesh_group_remove()
1505         check_mesh_group_removed(dev[0])
1506         check_mesh_group_removed(dev[1])
1507
1508 def test_mesh_invalid_frequency(dev, apdev):
1509     """Mesh and invalid frequency configuration"""
1510     check_mesh_support(dev[0])
1511     add_open_mesh_network(dev[0], freq=None)
1512     ev = dev[0].wait_event(["MESH-GROUP-STARTED",
1513                             "Could not join mesh"])
1514     if ev is None or "Could not join mesh" not in ev:
1515         raise Exception("Mesh join failure not reported")
1516     dev[0].request("REMOVE_NETWORK all")
1517
1518     add_open_mesh_network(dev[0], freq="2413")
1519     ev = dev[0].wait_event(["MESH-GROUP-STARTED",
1520                             "Could not join mesh"])
1521     if ev is None or "Could not join mesh" not in ev:
1522         raise Exception("Mesh join failure not reported")
1523
1524 def test_mesh_default_beacon_int(dev, apdev):
1525     """Mesh and default beacon interval"""
1526     check_mesh_support(dev[0])
1527     try:
1528         dev[0].request("SET beacon_int 200")
1529         add_open_mesh_network(dev[0])
1530         check_mesh_group_added(dev[0])
1531     finally:
1532         dev[0].request("SET beacon_int 0")
1533
1534 def test_mesh_scan_parse_error(dev, apdev):
1535     """Mesh scan element parse error"""
1536     check_mesh_support(dev[0])
1537     params = { "ssid": "open",
1538                "beacon_int": "2000" }
1539     hapd = hostapd.add_ap(apdev[0], params)
1540     bssid = apdev[0]['bssid']
1541     hapd.set('vendor_elements', 'dd0201')
1542     for i in range(10):
1543         dev[0].scan(freq=2412)
1544         if bssid in dev[0].request("SCAN_RESULTS"):
1545             break
1546     # This will fail in IE parsing due to the truncated IE in the Probe
1547     # Response frame.
1548     bss = dev[0].request("BSS " + bssid)
1549
1550 def test_mesh_missing_mic(dev, apdev):
1551     """Secure mesh network and missing MIC"""
1552     check_mesh_support(dev[0], secure=True)
1553
1554     dev[0].request("SET ext_mgmt_frame_handling 1")
1555     dev[0].request("SET sae_groups ")
1556     id = add_mesh_secure_net(dev[0])
1557     dev[0].mesh_group_add(id)
1558
1559     dev[1].request("SET sae_groups ")
1560     id = add_mesh_secure_net(dev[1])
1561     dev[1].mesh_group_add(id)
1562
1563     # Check for mesh joined
1564     check_mesh_group_added(dev[0])
1565     check_mesh_group_added(dev[1])
1566
1567     count = 0
1568     remove_mic = True
1569     while True:
1570         count += 1
1571         if count > 15:
1572             raise Exception("Did not see Action frames")
1573         rx_msg = dev[0].mgmt_rx()
1574         if rx_msg is None:
1575             ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
1576             if ev:
1577                 break
1578             raise Exception("MGMT-RX timeout")
1579         if rx_msg['subtype'] == 13:
1580             payload = rx_msg['payload']
1581             frame = rx_msg['frame']
1582             (categ, action) = struct.unpack('BB', payload[0:2])
1583             if categ == 15 and action == 1 and remove_mic:
1584                 # Mesh Peering Open
1585                 pos = frame.find('\x8c\x10')
1586                 if not pos:
1587                     raise Exception("Could not find MIC element")
1588                 logger.info("Found MIC at %d" % pos)
1589                 # Remove MIC
1590                 rx_msg['frame'] = frame[0:pos]
1591                 remove_mic = False
1592         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'))):
1593             raise Exception("MGMT_RX_PROCESS failed")
1594         ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
1595         if ev:
1596             break
1597
1598 def test_mesh_pmkid_mismatch(dev, apdev):
1599     """Secure mesh network and PMKID mismatch"""
1600     check_mesh_support(dev[0], secure=True)
1601     addr0 = dev[0].own_addr()
1602     addr1 = dev[1].own_addr()
1603     dev[0].request("SET sae_groups ")
1604     id = add_mesh_secure_net(dev[0])
1605     dev[0].set_network(id, "no_auto_peer", "1")
1606     dev[0].mesh_group_add(id)
1607
1608     dev[1].request("SET sae_groups ")
1609     id = add_mesh_secure_net(dev[1])
1610     dev[1].set_network(id, "no_auto_peer", "1")
1611     dev[1].mesh_group_add(id)
1612
1613     # Check for mesh joined
1614     check_mesh_group_added(dev[0])
1615     check_mesh_group_added(dev[1])
1616
1617     # Check for peer connected
1618     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1619     if ev is None:
1620         raise Exception("Missing no-initiate message")
1621     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1622         raise Exception("MESH_PEER_ADD failed")
1623     check_mesh_peer_connected(dev[0])
1624     check_mesh_peer_connected(dev[1])
1625
1626     if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1627         raise Exception("Failed to remove peer")
1628
1629     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1630     if ev is None:
1631         raise Exception("Missing no-initiate message (2)")
1632     dev[0].dump_monitor()
1633     dev[1].dump_monitor()
1634     dev[0].request("SET ext_mgmt_frame_handling 1")
1635     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1636         raise Exception("MESH_PEER_ADD failed (2)")
1637
1638     count = 0
1639     break_pmkid = True
1640     while True:
1641         count += 1
1642         if count > 50:
1643             raise Exception("Did not see Action frames")
1644         rx_msg = dev[0].mgmt_rx()
1645         if rx_msg is None:
1646             ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.1)
1647             if ev:
1648                 break
1649             raise Exception("MGMT-RX timeout")
1650         if rx_msg['subtype'] == 13:
1651             payload = rx_msg['payload']
1652             frame = rx_msg['frame']
1653             (categ, action) = struct.unpack('BB', payload[0:2])
1654             if categ == 15 and action == 1 and break_pmkid:
1655                 # Mesh Peering Open
1656                 pos = frame.find('\x75\x14')
1657                 if not pos:
1658                     raise Exception("Could not find Mesh Peering Management element")
1659                 logger.info("Found Mesh Peering Management element at %d" % pos)
1660                 # Break PMKID to hit "Mesh RSN: Invalid PMKID (Chosen PMK did
1661                 # not match calculated PMKID)"
1662                 rx_msg['frame'] = frame[0:pos + 6] + '\x00\x00\x00\x00' + frame[pos + 10:]
1663                 break_pmkid = False
1664         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'))):
1665             raise Exception("MGMT_RX_PROCESS failed")
1666         ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
1667         if ev:
1668             break
1669
1670 def test_mesh_peering_proto(dev, apdev):
1671     """Mesh peering management protocol testing"""
1672     check_mesh_support(dev[0])
1673
1674     dev[0].request("SET ext_mgmt_frame_handling 1")
1675     add_open_mesh_network(dev[0], beacon_int=160)
1676     add_open_mesh_network(dev[1], beacon_int=160)
1677
1678     count = 0
1679     test = 1
1680     while True:
1681         count += 1
1682         if count > 50:
1683             raise Exception("Did not see Action frames")
1684         rx_msg = dev[0].mgmt_rx()
1685         if rx_msg is None:
1686             ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
1687             if ev:
1688                 break
1689             raise Exception("MGMT-RX timeout")
1690         if rx_msg['subtype'] == 13:
1691             payload = rx_msg['payload']
1692             frame = rx_msg['frame']
1693             (categ, action) = struct.unpack('BB', payload[0:2])
1694             if categ == 15 and action == 1 and test == 1:
1695                 # Mesh Peering Open
1696                 pos = frame.find('\x75\x04')
1697                 if not pos:
1698                     raise Exception("Could not find Mesh Peering Management element")
1699                 logger.info("Found Mesh Peering Management element at %d" % pos)
1700                 # Remove the element to hit
1701                 # "MPM: No Mesh Peering Management element"
1702                 rx_msg['frame'] = frame[0:pos]
1703                 test += 1
1704             elif categ == 15 and action == 1 and test == 2:
1705                 # Mesh Peering Open
1706                 pos = frame.find('\x72\x0e')
1707                 if not pos:
1708                     raise Exception("Could not find Mesh ID element")
1709                 logger.info("Found Mesh ID element at %d" % pos)
1710                 # Remove the element to hit
1711                 # "MPM: No Mesh ID or Mesh Configuration element"
1712                 rx_msg['frame'] = frame[0:pos] + frame[pos + 16:]
1713                 test += 1
1714             elif categ == 15 and action == 1 and test == 3:
1715                 # Mesh Peering Open
1716                 pos = frame.find('\x72\x0e')
1717                 if not pos:
1718                     raise Exception("Could not find Mesh ID element")
1719                 logger.info("Found Mesh ID element at %d" % pos)
1720                 # Replace Mesh ID to hit "MPM: Mesh ID or Mesh Configuration
1721                 # element do not match local MBSS"
1722                 rx_msg['frame'] = frame[0:pos] + '\x72\x0etest-test-test' + frame[pos + 16:]
1723                 test += 1
1724             elif categ == 15 and action == 1 and test == 4:
1725                 # Mesh Peering Open
1726                 # Remove IEs to hit
1727                 # "MPM: Ignore too short action frame 1 ie_len 0"
1728                 rx_msg['frame'] = frame[0:26]
1729                 test += 1
1730             elif categ == 15 and action == 1 and test == 5:
1731                 # Mesh Peering Open
1732                 # Truncate IEs to hit
1733                 # "MPM: Failed to parse PLINK IEs"
1734                 rx_msg['frame'] = frame[0:30]
1735                 test += 1
1736             elif categ == 15 and action == 1 and test == 6:
1737                 # Mesh Peering Open
1738                 pos = frame.find('\x75\x04')
1739                 if not pos:
1740                     raise Exception("Could not find Mesh Peering Management element")
1741                 logger.info("Found Mesh Peering Management element at %d" % pos)
1742                 # Truncate the element to hit
1743                 # "MPM: Invalid peer mgmt ie" and
1744                 # "MPM: Mesh parsing rejected frame"
1745                 rx_msg['frame'] = frame[0:pos] + '\x75\x00\x00\x00' + frame[pos + 6:]
1746                 test += 1
1747         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'))):
1748             raise Exception("MGMT_RX_PROCESS failed")
1749         ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
1750         if ev:
1751             break
1752
1753     if test != 7:
1754         raise Exception("Not all test frames completed")
1755
1756 def test_mesh_mpm_init_proto(dev, apdev):
1757     """Mesh peering management protocol testing for peer addition"""
1758     check_mesh_support(dev[0])
1759     add_open_mesh_network(dev[0])
1760     check_mesh_group_added(dev[0])
1761     dev[0].dump_monitor()
1762
1763     dev[0].request("SET ext_mgmt_frame_handling 1")
1764
1765     addr = "020000000100"
1766     hdr = "d000ac00020000000000" + addr + addr + "1000"
1767     fixed = "0f010000"
1768     supp_rates = "010802040b168c129824"
1769     ext_supp_rates = "3204b048606c"
1770     mesh_id = "720e777061732d6d6573682d6f70656e"
1771     mesh_conf = "710701010001000009"
1772     mpm = "75040000079d"
1773     ht_capab = "2d1a7c001bffff000000000000000000000100000000000000000000"
1774     ht_oper = "3d160b000000000000000000000000000000000000000000"
1775
1776     dev[0].request("NOTE no supported rates")
1777     frame = hdr + fixed + ext_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
1778     if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
1779         raise Exception("MGMT_RX_PROCESS failed")
1780
1781     dev[0].request("NOTE Invalid supported rates element length 33+0")
1782     long_supp_rates = "012100112233445566778899aabbccddeeff00112233445566778899aabbccddeeff00"
1783     frame = hdr + fixed + long_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
1784     if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
1785         raise Exception("MGMT_RX_PROCESS failed")
1786
1787     dev[0].request("NOTE Too short mesh config")
1788     short_mesh_conf = "710401010001"
1789     frame = hdr + fixed + supp_rates + mesh_id + short_mesh_conf + mpm + ht_capab + ht_oper
1790     if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
1791         raise Exception("MGMT_RX_PROCESS failed")
1792
1793     dev[0].request("NOTE Add STA failure")
1794     frame = hdr + fixed + supp_rates + ext_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
1795     with fail_test(dev[0], 1, "wpa_driver_nl80211_sta_add"):
1796         if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
1797             raise Exception("MGMT_RX_PROCESS failed")
1798
1799     dev[0].request("NOTE Send Action failure")
1800     with fail_test(dev[0], 1, "driver_nl80211_send_action"):
1801         if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
1802             raise Exception("MGMT_RX_PROCESS failed")
1803
1804     dev[0].request("NOTE Set STA failure")
1805     addr = "020000000101"
1806     hdr = "d000ac00020000000000" + addr + addr + "1000"
1807     frame = hdr + fixed + supp_rates + ext_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
1808     with fail_test(dev[0], 2, "wpa_driver_nl80211_sta_add"):
1809         if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
1810             raise Exception("MGMT_RX_PROCESS failed")
1811
1812     dev[0].request("NOTE ap_sta_add OOM")
1813     addr = "020000000102"
1814     hdr = "d000ac00020000000000" + addr + addr + "1000"
1815     frame = hdr + fixed + supp_rates + ext_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
1816     with alloc_fail(dev[0], 1, "ap_sta_add"):
1817         if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
1818             raise Exception("MGMT_RX_PROCESS failed")
1819
1820     dev[0].request("NOTE hostapd_get_aid() failure")
1821     addr = "020000000103"
1822     hdr = "d000ac00020000000000" + addr + addr + "1000"
1823     frame = hdr + fixed + supp_rates + ext_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
1824     with fail_test(dev[0], 1, "hostapd_get_aid"):
1825         if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
1826             raise Exception("MGMT_RX_PROCESS failed")
1827
1828     if "OK" not in dev[0].request("MESH_PEER_REMOVE 02:00:00:00:01:00"):
1829         raise Exception("Failed to remove peer")
1830     if "FAIL" not in dev[0].request("MESH_PEER_REMOVE 02:00:00:00:01:02"):
1831         raise Exception("Unexpected MESH_PEER_REMOVE success")
1832     if "FAIL" not in dev[1].request("MESH_PEER_REMOVE 02:00:00:00:01:02"):
1833         raise Exception("Unexpected MESH_PEER_REMOVE success(2)")
1834     if "FAIL" not in dev[1].request("MESH_PEER_ADD 02:00:00:00:01:02"):
1835         raise Exception("Unexpected MESH_PEER_ADD success")
1836
1837 def test_mesh_holding(dev, apdev):
1838     """Mesh MPM FSM and HOLDING state event OPN_ACPT"""
1839     check_mesh_support(dev[0])
1840     add_open_mesh_network(dev[0])
1841     add_open_mesh_network(dev[1])
1842     check_mesh_group_added(dev[0])
1843     check_mesh_group_added(dev[1])
1844     check_mesh_peer_connected(dev[0])
1845     check_mesh_peer_connected(dev[1])
1846
1847     addr0 = dev[0].own_addr()
1848     addr1 = dev[1].own_addr()
1849
1850     dev[0].request("SET ext_mgmt_frame_handling 1")
1851     if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1852         raise Exception("Failed to remove peer")
1853
1854     rx_msg = dev[0].mgmt_rx()
1855     if rx_msg is None:
1856         raise Exception("MGMT-RX timeout")
1857     if rx_msg['subtype'] != 13:
1858         raise Exception("Unexpected management frame")
1859     payload = rx_msg['payload']
1860     (categ, action) = struct.unpack('BB', payload[0:2])
1861     if categ != 0x0f or action != 0x03:
1862         raise Exception("Did not see Mesh Peering Close")
1863
1864     peer_lid = payload[-6:-4].encode("hex")
1865     my_lid = payload[-4:-2].encode("hex")
1866
1867     # Drop Mesh Peering Close and instead, process an unexpected Mesh Peering
1868     # Open to trigger transmission of another Mesh Peering Close in the HOLDING
1869     # state based on an OPN_ACPT event.
1870
1871     dst = addr0.replace(':', '')
1872     src = addr1.replace(':', '')
1873     hdr = "d000ac00" + dst + src + src + "1000"
1874     fixed = "0f010000"
1875     supp_rates = "010802040b168c129824"
1876     ext_supp_rates = "3204b048606c"
1877     mesh_id = "720e777061732d6d6573682d6f70656e"
1878     mesh_conf = "710701010001000009"
1879     mpm = "7504" + my_lid + peer_lid
1880     ht_capab = "2d1a7c001bffff000000000000000000000100000000000000000000"
1881     ht_oper = "3d160b000000000000000000000000000000000000000000"
1882
1883     frame = hdr + fixed + supp_rates + ext_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
1884     if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
1885         raise Exception("MGMT_RX_PROCESS failed")
1886     time.sleep(0.1)
1887
1888 def test_mesh_cnf_rcvd_event_cls_acpt(dev, apdev):
1889     """Mesh peering management protocol testing - CLS_ACPT event in CNF_RCVD"""
1890     check_mesh_support(dev[0])
1891     add_open_mesh_network(dev[0])
1892     check_mesh_group_added(dev[0])
1893     dev[0].dump_monitor()
1894
1895     dev[0].request("SET ext_mgmt_frame_handling 1")
1896     add_open_mesh_network(dev[1])
1897     check_mesh_group_added(dev[1])
1898
1899     addr0 = dev[0].own_addr()
1900     addr1 = dev[1].own_addr()
1901
1902     rx_msg = dev[0].mgmt_rx()
1903     # Drop Mesh Peering Open
1904
1905     rx_msg = dev[0].mgmt_rx()
1906     # Allow Mesh Peering Confirm to go through
1907     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'))):
1908         raise Exception("MGMT_RX_PROCESS failed")
1909
1910     payload = rx_msg['payload']
1911     peer_lid = payload[51:53].encode("hex")
1912     my_lid = payload[53:55].encode("hex")
1913
1914     dst = addr0.replace(':', '')
1915     src = addr1.replace(':', '')
1916     hdr = "d000ac00" + dst + src + src + "1000"
1917     fixed = "0f03"
1918     mesh_id = "720e777061732d6d6573682d6f70656e"
1919     mpm = "75080000" + peer_lid + my_lid + "3700"
1920     frame = hdr + fixed + mesh_id + mpm
1921
1922     # Inject Mesh Peering Close to hit "state CNF_RCVD event CLS_ACPT" to
1923     # HOLDING transition.
1924     if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + frame):
1925         raise Exception("MGMT_RX_PROCESS failed")
1926
1927 def test_mesh_opn_snt_event_cls_acpt(dev, apdev):
1928     """Mesh peering management protocol testing - CLS_ACPT event in OPN_SNT"""
1929     check_mesh_support(dev[0])
1930     add_open_mesh_network(dev[0])
1931     check_mesh_group_added(dev[0])
1932     dev[0].dump_monitor()
1933
1934     dev[0].request("SET ext_mgmt_frame_handling 1")
1935     add_open_mesh_network(dev[1])
1936     check_mesh_group_added(dev[1])
1937
1938     addr0 = dev[0].own_addr()
1939     addr1 = dev[1].own_addr()
1940
1941     rx_msg = dev[0].mgmt_rx()
1942     # Drop Mesh Peering Open
1943
1944     rx_msg = dev[0].mgmt_rx()
1945     # Drop Mesh Peering Confirm
1946
1947     payload = rx_msg['payload']
1948     peer_lid = "0000"
1949     my_lid = payload[53:55].encode("hex")
1950
1951     dst = addr0.replace(':', '')
1952     src = addr1.replace(':', '')
1953     hdr = "d000ac00" + dst + src + src + "1000"
1954     fixed = "0f03"
1955     mesh_id = "720e777061732d6d6573682d6f70656e"
1956     mpm = "75080000" + peer_lid + my_lid + "3700"
1957     frame = hdr + fixed + mesh_id + mpm
1958
1959     # Inject Mesh Peering Close to hit "state OPN_SNTevent CLS_ACPT" to
1960     # HOLDING transition.
1961     if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + frame):
1962         raise Exception("MGMT_RX_PROCESS failed")